CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
feat: 新增任务运行防休眠功能
Bob4c774d8529ae
diff --git a/AGENTS.md b/AGENTS.mdindex c77ca79..6867d2c 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -6,13 +6,14 @@CodexBar 是一个 macOS 15+ 菜单栏应用,使用 Swift 6、SwiftUI + AppKit + MVVM。应用通过本机 Codex app-server 读取账号、额度和 token 用量,通过可选 Codex Hook 记录本机 Codex 工作流事件,并在菜单栏面板、设置窗口和日志窗口中展示状态。-工程只有一个 Xcode app target:`CodexBar`。当前没有独立测试 target 或 `*Tests*` 目录。+工程包含主 App target `CodexBar` 和随 App 嵌入的命令行 helper target `CodexBarHelper`。当前没有独立测试 target 或 `*Tests*` 目录。## 重要边界- 应用是 `LSUIElement` 菜单栏 App,不显示 Dock 图标,也不依赖主窗口。- 最低系统版本是 macOS 15.0。- App Sandbox 关闭,因为需要启动本机 `codex`、读取用户 Codex 登录状态,并写入用户级 Hook 配置。+- `CodexBarHelper` 只允许已签名的 CodexBar 通过 XPC 请求切换 `/usr/bin/pmset -a disablesleep`,并只在 `/Library/Application Support/CodexBar/` 维护恢复哨兵;不要给 root helper 增加网络、任意命令或其他文件访问能力。- 除手动重置机会过期时间查询、Sparkle 更新、用户显式开启跨设备同步后的 CloudKit private database 同步外,App 自身不应新增网络请求。- Codex 账号、额度、token 用量只在本机处理。Hook 工作流统计默认只写本机文件,跨设备同步只上传 daily 聚合数据,不上传原始事件、会话 ID、轮次 ID、请求日志或认证文件。- 不要回滚或清理与当前任务无关的未提交变更;仓库可能处于脏工作树状态。@@ -50,6 +51,8 @@ Tag:- `CodexBar/Services/`: app-server、Codex CLI 解析、Codex 版本探测、Hook 设置、工作流统计、同步、日志、登录项和更新服务。- `CodexBar/Views/`: 菜单面板、设置窗口、日志窗口和共享 Liquid Glass 样式。- `CodexBar/Resources/`: Info.plist、entitlements、图标和 asset catalog。+- `Shared/`: 主 App 与 root helper XPC 契约。+- `CodexBarHelper/`: 防休眠 root helper 入口和 LaunchDaemon plist。- `Docs/`: app-server、Codex Hook、跨设备同步和开发文档。- `Scripts/`: Release 构建、公证、DMG 和 Sparkle appcast 发布脚本。@@ -73,7 +76,7 @@ Scripts/appcast.sh`Scripts/build.sh` 默认执行 Release archive、导出 Developer ID app、公证、staple 和 Gatekeeper 校验。没有发布凭据或不需要完整发布流程时,不要把它当作普通本地验证命令。-当前没有自动化测试套件。修改后至少跑一次 `xcodebuild ... build`;如果改动涉及菜单面板、窗口焦点、Hook 或同步逻辑,需要手动说明还应覆盖的交互场景。+当前没有自动化测试套件。修改后至少跑一次 `xcodebuild ... build`;如果改动涉及菜单面板、窗口焦点、Hook、同步或防休眠逻辑,需要手动说明还应覆盖的交互场景。防休眠还应检查 App 包内 helper/plist 位置、签名、首次系统授权、运行/等待切换和异常退出后的恢复。## Swift 与并发约定diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxprojindex adfbccd..8a10fa0 100644--- a/CodexBar.xcodeproj/project.pbxproj+++ b/CodexBar.xcodeproj/project.pbxproj@@ -7,10 +7,53 @@objects = {/* Begin PBXBuildFile section */+ B10000000000000000000001 /* CodexBarHelperXPC.swift in Sources */ = {isa = PBXBuildFile; fileRef = B10000000000000000000011 /* CodexBarHelperXPC.swift */; };+ B10000000000000000000002 /* CodexBarHelperXPC.swift in Sources */ = {isa = PBXBuildFile; fileRef = B10000000000000000000011 /* CodexBarHelperXPC.swift */; };+ B10000000000000000000003 /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = B10000000000000000000012 /* main.swift */; };+ B10000000000000000000004 /* app.zabrian.codexbar.helper.plist in Copy LaunchDaemons */ = {isa = PBXBuildFile; fileRef = B10000000000000000000013 /* app.zabrian.codexbar.helper.plist */; };+ B10000000000000000000005 /* CodexBarHelper in Embed CodexBar Helper */ = {isa = PBXBuildFile; fileRef = B10000000000000000000014 /* CodexBarHelper */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };+ B10000000000000000000006 /* app.zabrian.codexbar.debug.helper.plist in Copy LaunchDaemons */ = {isa = PBXBuildFile; fileRef = B10000000000000000000015 /* app.zabrian.codexbar.debug.helper.plist */; };C42A52F12FDACDEC004A2B53 /* Sparkle in Frameworks */ = {isa = PBXBuildFile; productRef = C42A52F02FDACDEC004A2B53 /* Sparkle */; };/* End PBXBuildFile section */+/* Begin PBXContainerItemProxy section */+ B10000000000000000000052 /* PBXContainerItemProxy */ = {+ isa = PBXContainerItemProxy;+ containerPortal = C4A0FD8D2FD9302E000263A7 /* Project object */;+ proxyType = 1;+ remoteGlobalIDString = B10000000000000000000031;+ remoteInfo = CodexBarHelper;+ };+/* End PBXContainerItemProxy section */++/* Begin PBXCopyFilesBuildPhase section */+ B10000000000000000000023 /* Embed CodexBar Helper */ = {+ isa = PBXCopyFilesBuildPhase;+ dstPath = "";+ dstSubfolder = Resources;+ files = (+ B10000000000000000000005 /* CodexBarHelper in Embed CodexBar Helper */,+ );+ name = "Embed CodexBar Helper";+ };+ B10000000000000000000024 /* Copy LaunchDaemons */ = {+ isa = PBXCopyFilesBuildPhase;+ dstPath = Contents/Library/LaunchDaemons;+ dstSubfolder = Wrapper;+ files = (+ B10000000000000000000004 /* app.zabrian.codexbar.helper.plist in Copy LaunchDaemons */,+ B10000000000000000000006 /* app.zabrian.codexbar.debug.helper.plist in Copy LaunchDaemons */,+ );+ name = "Copy LaunchDaemons";+ };+/* End PBXCopyFilesBuildPhase section */+/* Begin PBXFileReference section */+ B10000000000000000000011 /* CodexBarHelperXPC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CodexBarHelperXPC.swift; sourceTree = "<group>"; };+ B10000000000000000000012 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };+ B10000000000000000000013 /* app.zabrian.codexbar.helper.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = app.zabrian.codexbar.helper.plist; sourceTree = "<group>"; };+ B10000000000000000000014 /* CodexBarHelper */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = CodexBarHelper; sourceTree = BUILT_PRODUCTS_DIR; };+ B10000000000000000000015 /* app.zabrian.codexbar.debug.helper.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = app.zabrian.codexbar.debug.helper.plist; sourceTree = "<group>"; };C4A0FD952FD9302E000263A7 /* CodexBar.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = CodexBar.app; sourceTree = BUILT_PRODUCTS_DIR; };/* End PBXFileReference section */@@ -36,6 +79,11 @@/* End PBXFileSystemSynchronizedRootGroup section *//* Begin PBXFrameworksBuildPhase section */+ B10000000000000000000022 /* Frameworks */ = {+ isa = PBXFrameworksBuildPhase;+ files = (+ );+ };C4A0FD922FD9302E000263A7 /* Frameworks */ = {isa = PBXFrameworksBuildPhase;files = (@@ -45,10 +93,30 @@/* End PBXFrameworksBuildPhase section *//* Begin PBXGroup section */+ B10000000000000000000041 /* Shared */ = {+ isa = PBXGroup;+ children = (+ B10000000000000000000011 /* CodexBarHelperXPC.swift */,+ );+ path = Shared;+ sourceTree = "<group>";+ };+ B10000000000000000000042 /* CodexBarHelper */ = {+ isa = PBXGroup;+ children = (+ B10000000000000000000012 /* main.swift */,+ B10000000000000000000015 /* app.zabrian.codexbar.debug.helper.plist */,+ B10000000000000000000013 /* app.zabrian.codexbar.helper.plist */,+ );+ path = CodexBarHelper;+ sourceTree = "<group>";+ };C4A0FD8C2FD9302E000263A7 = {isa = PBXGroup;children = (9E664A4C2FDD47530016B96E /* CodexBar */,+ B10000000000000000000041 /* Shared */,+ B10000000000000000000042 /* CodexBarHelper */,C4A0FD962FD9302E000263A7 /* Products */,);sourceTree = "<group>";@@ -57,6 +125,7 @@isa = PBXGroup;children = (C4A0FD952FD9302E000263A7 /* CodexBar.app */,+ B10000000000000000000014 /* CodexBarHelper */,);name = Products;sourceTree = "<group>";@@ -64,6 +133,20 @@/* End PBXGroup section *//* Begin PBXNativeTarget section */+ B10000000000000000000031 /* CodexBarHelper */ = {+ isa = PBXNativeTarget;+ buildConfigurationList = B10000000000000000000032 /* Build configuration list for PBXNativeTarget "CodexBarHelper" */;+ buildPhases = (+ B10000000000000000000021 /* Sources */,+ B10000000000000000000022 /* Frameworks */,+ );+ buildRules = (+ );+ name = CodexBarHelper;+ productName = CodexBarHelper;+ productReference = B10000000000000000000014 /* CodexBarHelper */;+ productType = "com.apple.product-type.tool";+ };C4A0FD942FD9302E000263A7 /* CodexBar */ = {isa = PBXNativeTarget;buildConfigurationList = C4A0FDA02FD9302E000263A7 /* Build configuration list for PBXNativeTarget "CodexBar" */;@@ -71,9 +154,14 @@C4A0FD912FD9302E000263A7 /* Sources */,C4A0FD922FD9302E000263A7 /* Frameworks */,C4A0FD932FD9302E000263A7 /* Resources */,+ B10000000000000000000023 /* Embed CodexBar Helper */,+ B10000000000000000000024 /* Copy LaunchDaemons */,);buildRules = ();+ dependencies = (+ B10000000000000000000051 /* PBXTargetDependency */,+ );fileSystemSynchronizedGroups = (9E664A4C2FDD47530016B96E /* CodexBar */,);@@ -95,6 +183,9 @@LastSwiftUpdateCheck = 2650;LastUpgradeCheck = 2660;TargetAttributes = {+ B10000000000000000000031 = {+ CreatedOnToolsVersion = 26.5;+ };C4A0FD942FD9302E000263A7 = {CreatedOnToolsVersion = 26.5;};@@ -118,6 +209,7 @@projectRoot = "";targets = (C4A0FD942FD9302E000263A7 /* CodexBar */,+ B10000000000000000000031 /* CodexBarHelper */,);};/* End PBXProject section */@@ -131,14 +223,71 @@/* End PBXResourcesBuildPhase section *//* Begin PBXSourcesBuildPhase section */+ B10000000000000000000021 /* Sources */ = {+ isa = PBXSourcesBuildPhase;+ files = (+ B10000000000000000000002 /* CodexBarHelperXPC.swift in Sources */,+ B10000000000000000000003 /* main.swift in Sources */,+ );+ };C4A0FD912FD9302E000263A7 /* Sources */ = {isa = PBXSourcesBuildPhase;files = (+ B10000000000000000000001 /* CodexBarHelperXPC.swift in Sources */,);};/* End PBXSourcesBuildPhase section */+/* Begin PBXTargetDependency section */+ B10000000000000000000051 /* PBXTargetDependency */ = {+ isa = PBXTargetDependency;+ target = B10000000000000000000031 /* CodexBarHelper */;+ targetProxy = B10000000000000000000052 /* PBXContainerItemProxy */;+ };+/* End PBXTargetDependency section */+/* Begin XCBuildConfiguration section */+ B10000000000000000000033 /* Debug configuration for PBXNativeTarget "CodexBarHelper" */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ CODE_SIGN_STYLE = Automatic;+ CREATE_INFOPLIST_SECTION_IN_BINARY = YES;+ CURRENT_PROJECT_VERSION = 1;+ DEAD_CODE_STRIPPING = YES;+ DEVELOPMENT_TEAM = 4KJ362VJW5;+ ENABLE_APP_SANDBOX = NO;+ ENABLE_HARDENED_RUNTIME = YES;+ GENERATE_INFOPLIST_FILE = YES;+ MACOSX_DEPLOYMENT_TARGET = 15.0;+ PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar.debug.helper;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SKIP_INSTALL = YES;+ SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;+ SWIFT_VERSION = 6.0;+ };+ name = Debug;+ };+ B10000000000000000000034 /* Release configuration for PBXNativeTarget "CodexBarHelper" */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ "CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";+ CODE_SIGN_STYLE = Automatic;+ CREATE_INFOPLIST_SECTION_IN_BINARY = YES;+ CURRENT_PROJECT_VERSION = 1;+ DEAD_CODE_STRIPPING = YES;+ DEVELOPMENT_TEAM = 4KJ362VJW5;+ ENABLE_APP_SANDBOX = NO;+ ENABLE_HARDENED_RUNTIME = YES;+ GENERATE_INFOPLIST_FILE = YES;+ MACOSX_DEPLOYMENT_TARGET = 15.0;+ PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar.helper;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SKIP_INSTALL = YES;+ SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES;+ SWIFT_VERSION = 6.0;+ };+ name = Release;+ };C4A0FD9E2FD9302E000263A7 /* Debug configuration for PBXProject "CodexBar" */ = {isa = XCBuildConfiguration;buildSettings = {@@ -274,7 +423,7 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- CURRENT_PROJECT_VERSION = 53;+ CURRENT_PROJECT_VERSION = 54;DEAD_CODE_STRIPPING = YES;DEVELOPMENT_TEAM = 4KJ362VJW5;ENABLE_APP_INTENTS_METADATA_GENERATION = NO;@@ -282,16 +431,17 @@ENABLE_HARDENED_RUNTIME = YES;ENABLE_PREVIEWS = YES;ENABLE_USER_SELECTED_FILES = NO;+ EXCLUDED_SOURCE_FILE_NAMES = app.zabrian.codexbar.helper.plist;GENERATE_INFOPLIST_FILE = NO;INFOPLIST_FILE = CodexBar/Resources/Info.plist;- INFOPLIST_KEY_CFBundleDisplayName = CodexBar;+ INFOPLIST_KEY_CFBundleDisplayName = "CodexBar Debug";INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.developer-tools";LD_RUNPATH_SEARCH_PATHS = ("$(inherited)","@executable_path/../Frameworks",);- MARKETING_VERSION = 3.4.3;- PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;+ MARKETING_VERSION = 3.5.0;+ PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar.debug;PRODUCT_NAME = "$(TARGET_NAME)";REGISTER_APP_GROUPS = YES;STRING_CATALOG_GENERATE_SYMBOLS = YES;@@ -313,7 +463,7 @@"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";CODE_SIGN_STYLE = Automatic;COMBINE_HIDPI_IMAGES = YES;- CURRENT_PROJECT_VERSION = 53;+ CURRENT_PROJECT_VERSION = 54;DEAD_CODE_STRIPPING = YES;DEVELOPMENT_TEAM = 4KJ362VJW5;ENABLE_APP_INTENTS_METADATA_GENERATION = NO;@@ -321,6 +471,7 @@ENABLE_HARDENED_RUNTIME = YES;ENABLE_PREVIEWS = YES;ENABLE_USER_SELECTED_FILES = NO;+ EXCLUDED_SOURCE_FILE_NAMES = app.zabrian.codexbar.debug.helper.plist;GENERATE_INFOPLIST_FILE = NO;INFOPLIST_FILE = CodexBar/Resources/Info.plist;INFOPLIST_KEY_CFBundleDisplayName = CodexBar;@@ -329,7 +480,7 @@"$(inherited)","@executable_path/../Frameworks",);- MARKETING_VERSION = 3.4.3;+ MARKETING_VERSION = 3.5.0;PRODUCT_BUNDLE_IDENTIFIER = app.zabrian.codexbar;PRODUCT_NAME = "$(TARGET_NAME)";PROVISIONING_PROFILE_SPECIFIER = "";@@ -346,6 +497,14 @@/* End XCBuildConfiguration section *//* Begin XCConfigurationList section */+ B10000000000000000000032 /* Build configuration list for PBXNativeTarget "CodexBarHelper" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ B10000000000000000000033 /* Debug configuration for PBXNativeTarget "CodexBarHelper" */,+ B10000000000000000000034 /* Release configuration for PBXNativeTarget "CodexBarHelper" */,+ );+ defaultConfigurationName = Release;+ };C4A0FD902FD9302E000263A7 /* Build configuration list for PBXProject "CodexBar" */ = {isa = XCConfigurationList;buildConfigurations = (diff --git a/CodexBar.xcodeproj/xcuserdata/bob.xcuserdatad/xcschemes/xcschememanagement.plist b/CodexBar.xcodeproj/xcuserdata/bob.xcuserdatad/xcschemes/xcschememanagement.plistindex e815e2c..bf0b194 100644--- a/CodexBar.xcodeproj/xcuserdata/bob.xcuserdatad/xcschemes/xcschememanagement.plist+++ b/CodexBar.xcodeproj/xcuserdata/bob.xcuserdatad/xcschemes/xcschememanagement.plist@@ -9,6 +9,11 @@<key>orderHint</key><integer>0</integer></dict>+ <key>CodexBarHelper.xcscheme_^#shared#^_</key>+ <dict>+ <key>orderHint</key>+ <integer>1</integer>+ </dict></dict><key>SuppressBuildableAutocreation</key><dict>diff --git a/CodexBar/Controllers/SettingsWindowController.swift b/CodexBar/Controllers/SettingsWindowController.swiftindex a1ff738..e2a8027 100644--- a/CodexBar/Controllers/SettingsWindowController.swift+++ b/CodexBar/Controllers/SettingsWindowController.swift@@ -13,6 +13,7 @@ final class SettingsWindowController: HostingWindowController {private let menuBarQuotaSettings: MenuBarQuotaSettingsprivate let mainPanelSettings: MainPanelSettingsprivate let notificationSettings: NotificationSettings+ private let keepAliveController: KeepAliveControllerprivate let onSyncChanged: (Bool) -> Voidprivate let onRebuildWorkflowData: WorkflowSyncScheduler.RebuildHandlerprivate lazy var notificationOptionsPanelController = NotificationOptionsPanelController(@@ -31,6 +32,7 @@ final class SettingsWindowController: HostingWindowController {menuBarQuotaSettings: MenuBarQuotaSettings,mainPanelSettings: MainPanelSettings,notificationSettings: NotificationSettings,+ keepAliveController: KeepAliveController,screenProvider: @escaping () -> NSScreen?,onSyncChanged: @escaping (Bool) -> Void,onRebuildWorkflowData: @escaping WorkflowSyncScheduler.RebuildHandler@@ -44,6 +46,7 @@ final class SettingsWindowController: HostingWindowController {self.menuBarQuotaSettings = menuBarQuotaSettingsself.mainPanelSettings = mainPanelSettingsself.notificationSettings = notificationSettings+ self.keepAliveController = keepAliveControllerself.onSyncChanged = onSyncChangedself.onRebuildWorkflowData = onRebuildWorkflowDatasuper.init(screenProvider: screenProvider)@@ -64,6 +67,7 @@ final class SettingsWindowController: HostingWindowController {menuBarQuotaSettings: menuBarQuotaSettings,mainPanelSettings: mainPanelSettings,notificationSettings: notificationSettings,+ keepAliveController: keepAliveController,onSyncChanged: onSyncChanged,onRebuildWorkflowData: onRebuildWorkflowData,onNotificationOptionsAction: { [weak self] action in@@ -103,6 +107,7 @@ final class SettingsWindowController: HostingWindowController {syncSettings.refresh()menuBarQuotaSettings.refresh()mainPanelSettings.refresh()+ keepAliveController.refresh()}private func handleNotificationOptionsAction(_ action: NotificationOptionsPanelAction) {diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swiftindex 91876e0..b5a25e2 100644--- a/CodexBar/Controllers/StatusItemController.swift+++ b/CodexBar/Controllers/StatusItemController.swift@@ -13,6 +13,10 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {codexStatusService: codexStatusService)lazy var activityMonitor = CodexActivityMonitor(codexHookSettings: codexHookSettings)+ lazy var keepAliveController = KeepAliveController(+ activityMonitor: activityMonitor,+ codexHookSettings: codexHookSettings+ )let syncSettings = WorkflowSyncSettings()let globalHotKeySettings = GlobalHotKeySettings()let menuBarQuotaSettings = MenuBarQuotaSettings()@@ -35,6 +39,7 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {menuBarQuotaSettings: menuBarQuotaSettings,mainPanelSettings: mainPanelSettings,notificationSettings: notificationSettings,+ keepAliveController: keepAliveController,appUpdater: appUpdater)controller.install()@@ -50,10 +55,12 @@ final class CodexBarAppDelegate: NSObject, NSApplicationDelegate {notificationService.start()self.notificationService = notificationServiceactivityMonitor.start()+ keepAliveController.start()}func applicationWillTerminate(_: Notification) {statusItemController?.uninstall()+ keepAliveController.stop()activityMonitor.stop()}@@ -75,6 +82,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {private let menuBarQuotaSettings: MenuBarQuotaSettingsprivate let mainPanelSettings: MainPanelSettingsprivate let notificationSettings: NotificationSettings+ private let keepAliveController: KeepAliveControllerprivate let appUpdater: AppUpdaterprivate let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)private let popover = NSPopover()@@ -104,7 +112,8 @@ private final class StatusItemController: NSObject, NSMenuDelegate {globalHotKeySettings: globalHotKeySettings,menuBarQuotaSettings: menuBarQuotaSettings,mainPanelSettings: mainPanelSettings,- notificationSettings: notificationSettings+ notificationSettings: notificationSettings,+ keepAliveController: keepAliveController) { [weak self] inself?.statusItem.button?.window?.screen} onSyncChanged: { [weak self] enabled in@@ -172,6 +181,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {menuBarQuotaSettings: MenuBarQuotaSettings,mainPanelSettings: MainPanelSettings,notificationSettings: NotificationSettings,+ keepAliveController: KeepAliveController,appUpdater: AppUpdater) {self.viewModel = viewModel@@ -184,6 +194,7 @@ private final class StatusItemController: NSObject, NSMenuDelegate {self.menuBarQuotaSettings = menuBarQuotaSettingsself.mainPanelSettings = mainPanelSettingsself.notificationSettings = notificationSettings+ self.keepAliveController = keepAliveControllerself.appUpdater = appUpdatersuper.init()}diff --git a/CodexBar/Resources/Info.plist b/CodexBar/Resources/Info.plistindex 435709d..2805f2e 100644--- a/CodexBar/Resources/Info.plist+++ b/CodexBar/Resources/Info.plist@@ -5,7 +5,7 @@<key>CFBundleDevelopmentRegion</key><string>$(DEVELOPMENT_LANGUAGE)</string><key>CFBundleDisplayName</key>- <string>CodexBar</string>+ <string>$(INFOPLIST_KEY_CFBundleDisplayName)</string><key>CFBundleExecutable</key><string>$(EXECUTABLE_NAME)</string><key>CFBundleIconName</key>diff --git a/CodexBar/Services/KeepAlive/KeepAliveController.swift b/CodexBar/Services/KeepAlive/KeepAliveController.swiftnew file mode 100644index 0000000..eb813cd--- /dev/null+++ b/CodexBar/Services/KeepAlive/KeepAliveController.swift@@ -0,0 +1,723 @@+import AppKit+import Combine+import CryptoKit+import Foundation+import IOKit+import ServiceManagement++@MainActor+final 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 errorMessage: String?++ private let activityMonitor: CodexActivityMonitor+ private let codexHookSettings: CodexHookSettings+ private let defaults: UserDefaults+ private let systemSleepService = SystemSleepService()+ private var hasRunningTasks = false+ /// 保留仍活跃且已经进入过运行态的任务, 避免普通快照刷新被误判成新任务+ private var startedRunningTaskIDs = Set<UUID>()+ /// 记录上一份快照中的等待任务, 用于识别等待批准后恢复运行的状态转换+ private var waitingTaskIDs = Set<UUID>()+ private var connection: NSXPCConnection?+ private var appliedSleepDisabled: Bool?+ private var requestInFlight = false+ private var requestGeneration: UInt64 = 0+ private var retryTask: Task<Void, Never>?+ private var maximumDurationTask: Task<Void, Never>?+ private var maximumDurationStartedAt: Date?+ private var helperRegistrationTask: Task<Void, Never>?+ private var isRefreshingHelper = false+ private var cancellables = Set<AnyCancellable>()+ private var isStarted = false++ init(+ activityMonitor: CodexActivityMonitor,+ codexHookSettings: CodexHookSettings,+ defaults: UserDefaults = .standard+ ) {+ self.activityMonitor = activityMonitor+ self.codexHookSettings = codexHookSettings+ self.defaults = defaults+ isEnabled = defaults.bool(forKey: Self.enabledKey)+ maximumDuration = (defaults.object(forKey: Self.maximumDurationKey) as? Int)+ .flatMap(MaximumDuration.init(rawValue:)) ?? .twelveHours+ }++ func start() {+ guard !isStarted else {+ return+ }+ isStarted = true++ codexHookSettings.$isEnabled+ .removeDuplicates()+ .sink { [weak self] isHookEnabled in+ guard !isHookEnabled else {+ return+ }+ self?.setEnabled(false)+ }+ .store(in: &cancellables)++ activityMonitor.$snapshot+ .sink { [weak self] snapshot in+ self?.handleActivitySnapshot(snapshot)+ }+ .store(in: &cancellables)++ NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)+ .sink { [weak self] _ in+ self?.refresh()+ }+ .store(in: &cancellables)++ refreshRegistrationAndSleepState()+ }++ func stop() {+ guard isStarted else {+ return+ }+ isStarted = false+ cancellables.removeAll()+ cancelRetryTask()+ cancelHelperRegistrationTask()+ startedRunningTaskIDs.removeAll()+ waitingTaskIDs.removeAll()+ resetMaximumDurationState()++ if connection != nil {+ applySleepDisabled(false)+ }+ _ = systemSleepService.endPreventingIdleSleep()+ invalidateConnection()+ }++ func refresh() {+ refreshRegistrationAndSleepState()+ }++ private func refreshRegistrationAndSleepState() {+ refreshHelperStatus()+ if isEnabled || helperStatus.isRegisteredOrAwaitingApproval {+ ensureHelperRegistration(opensSystemSettings: false)+ }+ reconcileSleepState()+ }++ func setEnabled(_ enabled: Bool) {+ guard !enabled || codexHookSettings.isEnabled else {+ return+ }+ guard enabled != isEnabled else {+ return+ }++ isEnabled = enabled+ defaults.set(enabled, forKey: Self.enabledKey)+ errorMessage = nil++ if enabled {+ ensureHelperRegistration(opensSystemSettings: true)+ } else {+ resetMaximumDurationState()+ }+ reconcileSleepState()+ }++ func setMaximumDuration(_ duration: MaximumDuration) {+ guard duration != maximumDuration else {+ return+ }++ maximumDuration = duration+ defaults.set(duration.rawValue, forKey: Self.maximumDurationKey)++ guard let maximumDurationStartedAt else {+ return+ }++ if let deadline = maximumDurationDeadline(from: maximumDurationStartedAt),+ Date() >= deadline {+ reachMaximumDuration()+ return+ }++ hasReachedMaximumDuration = false+ scheduleMaximumDurationTask()+ reconcileSleepState()+ }++ private func handleActivitySnapshot(_ snapshot: CodexActivitySnapshot) {+ let runningTaskIDs = Set(snapshot.runningTasks.map(\.id))+ let currentWaitingTaskIDs = Set(snapshot.waitingTasks.map(\.id))+ let activeTaskIDs = runningTaskIDs.union(currentWaitingTaskIDs)++ startedRunningTaskIDs.formIntersection(activeTaskIDs)+ let newRunningTaskIDs = runningTaskIDs.subtracting(startedRunningTaskIDs)+ let resumedRunningTaskIDs = runningTaskIDs+ .intersection(waitingTaskIDs)+ .subtracting(currentWaitingTaskIDs)+ startedRunningTaskIDs.formUnion(runningTaskIDs)+ waitingTaskIDs = currentWaitingTaskIDs++ hasRunningTasks = !runningTaskIDs.isEmpty+ if activeTaskIDs.isEmpty {+ resetMaximumDurationState()+ } else if !newRunningTaskIDs.isEmpty || !resumedRunningTaskIDs.isEmpty {+ restartMaximumDurationPeriod()+ }+ reconcileSleepState()+ }++ private func restartMaximumDurationPeriod() {+ guard isEnabled else {+ return+ }++ maximumDurationStartedAt = Date()+ hasReachedMaximumDuration = false+ if helperStatus == .enabled, !isRefreshingHelper {+ scheduleMaximumDurationTask()+ }+ }++ func openSystemSettings() {+ SMAppService.openSystemSettingsLoginItems()+ }++ private func ensureHelperRegistration(opensSystemSettings: Bool) {+ let service = Self.helperService+ refreshHelperStatus()++ switch helperStatus {+ case .enabled, .requiresApproval:+ if helperRegistrationNeedsRefresh {+ refreshRegisteredHelper(opensSystemSettings: opensSystemSettings)+ } else if helperStatus == .requiresApproval, opensSystemSettings {+ openSystemSettings()+ }+ return+ case .notRegistered, .notFound:+ guard Self.helperAssetsArePresent else {+ errorMessage = "服务异常, 请重新安装 CodexBar"+ return+ }+ }++ do {+ try service.register()+ } catch {+ refreshHelperStatus()+ if !helperStatus.isRegisteredOrAwaitingApproval {+ errorMessage = "注册服务失败: \(error.localizedDescription)"+ }+ }++ refreshHelperStatus()+ recordHelperRegistrationIfCurrent()+ if helperStatus == .requiresApproval, opensSystemSettings {+ openSystemSettings()+ }+ }++ private func refreshRegisteredHelper(opensSystemSettings: Bool) {+ guard helperRegistrationTask == nil,+ Self.helperAssetsArePresent else {+ return+ }++ isRefreshingHelper = true+ cancelRetryTask()+ invalidateConnection()+ errorMessage = nil++ let service = Self.helperService+ helperRegistrationTask = Task { @MainActor [weak self] in+ guard let self else {+ return+ }++ var registrationError: Error?+ do {+ try Task.checkCancellation()+ try await service.unregister()+ try Task.checkCancellation()+ try await registerRefreshedHelper(service)+ } catch is CancellationError {+ return+ } catch {+ registrationError = error+ }++ guard isStarted, !Task.isCancelled else {+ return+ }++ refreshHelperStatus()+ if helperStatus.isRegisteredOrAwaitingApproval {+ recordHelperRegistrationIfCurrent()+ } else if let registrationError {+ errorMessage = "更新服务失败: \(registrationError.localizedDescription)"+ }++ isRefreshingHelper = false+ helperRegistrationTask = nil+ if helperStatus == .requiresApproval, opensSystemSettings {+ openSystemSettings()+ }+ reconcileSleepState(force: true)+ }+ }++ private func registerRefreshedHelper(_ service: SMAppService) async throws {+ await Task.yield()++ var retryDelays = Self.helperRegistrationRetryDelays.makeIterator()+ while true {+ do {+ try service.register()+ return+ } catch {+ guard Self.isTransientHelperRegistrationError(error),+ let retryDelay = retryDelays.next() else {+ throw error+ }+ try await Task.sleep(for: retryDelay)+ }+ }+ }++ private static func isTransientHelperRegistrationError(_ error: Error) -> Bool {+ let error = error as NSError+ return error.domain == SMAppServiceErrorDomain+ && error.code == operationNotPermittedErrorCode+ }++ private func refreshHelperStatus() {+ helperStatus = HelperStatus(Self.helperService.status)+ if helperStatus == .enabled {+ errorMessage = nil+ } else if helperStatus != .requiresApproval {+ _ = systemSleepService.endPreventingIdleSleep()+ isPreventingSleep = false+ resetMaximumDurationState()+ }+ }++ private func reconcileSleepState(force: Bool = false) {+ let wantsSleepDisabled = shouldDisableSleep++ guard wantsSleepDisabled else {+ cancelRetryTask()+ if connection != nil, appliedSleepDisabled != false || isPreventingSleep {+ applySleepDisabled(false)+ } else {+ _ = systemSleepService.endPreventingIdleSleep()+ }+ return+ }++ if force {+ appliedSleepDisabled = nil+ }+ applySleepDisabled(true)+ }++ private func applySleepDisabled(_ disabled: Bool) {+ guard appliedSleepDisabled != disabled else {+ return+ }++ if disabled {+ let result = systemSleepService.beginPreventingIdleSleep()+ guard result == kIOReturnSuccess else {+ errorMessage = "阻止空闲休眠失败 (\(result))"+ scheduleRetryIfNeeded(for: true)+ return+ }+ }++ let connection = connection ?? makeConnection()+ appliedSleepDisabled = disabled+ requestInFlight = true+ requestGeneration &+= 1+ let generation = requestGeneration++ let errorHandler: (Error) -> Void = { [weak self] error in+ Task { @MainActor in+ guard let self, generation == self.requestGeneration else {+ return+ }+ self.handleConnectionFailure(error)+ }+ }+ guard let helper = connection.remoteObjectProxyWithErrorHandler(errorHandler)+ as? CodexBarHelperProtocol else {+ handleConnectionFailure(KeepAliveError.invalidHelperProxy)+ return+ }++ helper.setSleepDisabled(disabled) { [weak self] exitCode, sleepDisabledAfterOperation in+ Task { @MainActor in+ guard let self, generation == self.requestGeneration else {+ return+ }+ self.requestInFlight = false+ guard exitCode == 0 else {+ if disabled {+ _ = self.systemSleepService.endPreventingIdleSleep()+ }+ self.invalidateConnection()+ self.errorMessage = "切换休眠状态失败 (\(exitCode))"+ self.scheduleRetryIfNeeded(for: disabled)+ return+ }++ self.cancelRetryTask()+ self.isPreventingSleep = disabled+ self.errorMessage = nil+ if disabled {+ self.beginMaximumDurationCountdownIfNeeded()+ } else {+ self.finishSleepRestore(+ sleepDisabledAfterOperation: sleepDisabledAfterOperation+ )+ }+ }+ }+ }++ 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+ reconcileSleepState()+ }++ private func finishSleepRestore(sleepDisabledAfterOperation: Bool) {+ let idleSleepResult = systemSleepService.endPreventingIdleSleep()+ if idleSleepResult != kIOReturnSuccess {+ errorMessage = "恢复空闲休眠策略失败 (\(idleSleepResult))"+ }++ let shouldRequestSystemSleep = !sleepDisabledAfterOperation+ && SystemSleepService.currentStatus()?.shouldSleepForLidClosure == true++ guard shouldRequestSystemSleep else {+ return+ }++ let result = SystemSleepService.requestSystemSleep()+ if result != kIOReturnSuccess {+ errorMessage = "请求系统休眠失败 (\(result))"+ }+ }++ private func resetMaximumDurationState() {+ cancelMaximumDurationTask()+ maximumDurationStartedAt = nil+ hasReachedMaximumDuration = false+ }++ private func cancelMaximumDurationTask() {+ maximumDurationTask?.cancel()+ maximumDurationTask = nil+ }++ private func maximumDurationDeadline(from startedAt: Date) -> Date? {+ maximumDuration.timeInterval.map(startedAt.addingTimeInterval)+ }++ private func makeConnection() -> NSXPCConnection {+ let connection = NSXPCConnection(+ machServiceName: CodexBarHelperIPC.machServiceName,+ options: .privileged+ )+ connection.remoteObjectInterface = NSXPCInterface(+ with: CodexBarHelperProtocol.self+ )+ connection.invalidationHandler = { [weak self, weak connection] in+ Task { @MainActor in+ guard let self, self.connection === connection else {+ return+ }+ let shouldRetry = self.requestInFlight || self.isPreventingSleep+ let desiredSleepDisabled = self.shouldDisableSleep+ self.connection = nil+ self.appliedSleepDisabled = nil+ self.requestInFlight = false+ self.isPreventingSleep = false+ if shouldRetry {+ self.scheduleRetryIfNeeded(for: desiredSleepDisabled)+ }+ }+ }+ connection.interruptionHandler = { [weak self] in+ Task { @MainActor in+ self?.handleConnectionFailure(KeepAliveError.connectionInterrupted)+ }+ }+ connection.resume()+ self.connection = connection+ return connection+ }++ private func handleConnectionFailure(_ error: Error) {+ let shouldRetry = requestInFlight || isPreventingSleep+ let desiredSleepDisabled = shouldDisableSleep+ invalidateConnection()+ errorMessage = "连接服务失败: \(error.localizedDescription)"+ if shouldRetry {+ scheduleRetryIfNeeded(for: desiredSleepDisabled)+ }+ }++ private func invalidateConnection() {+ requestGeneration &+= 1+ let connection = connection+ self.connection = nil+ connection?.invalidationHandler = nil+ connection?.interruptionHandler = nil+ connection?.invalidate()+ appliedSleepDisabled = nil+ requestInFlight = false+ isPreventingSleep = false+ }++ private func cancelRetryTask() {+ retryTask?.cancel()+ retryTask = nil+ }++ private func cancelHelperRegistrationTask() {+ helperRegistrationTask?.cancel()+ helperRegistrationTask = nil+ isRefreshingHelper = false+ }++ private func scheduleRetryIfNeeded(for disabled: Bool) {+ guard isStarted,+ helperStatus == .enabled,+ disabled == shouldDisableSleep,+ retryTask == nil else {+ return+ }++ retryTask = Task { @MainActor [weak self] in+ try? await Task.sleep(for: .seconds(2))+ guard !Task.isCancelled, let self else {+ return+ }+ retryTask = nil+ guard disabled == shouldDisableSleep else {+ reconcileSleepState()+ return+ }+ appliedSleepDisabled = nil+ applySleepDisabled(disabled)+ }+ }++ private var shouldDisableSleep: Bool {+ isStarted+ && isEnabled+ && hasRunningTasks+ && helperStatus == .enabled+ && !isRefreshingHelper+ && !hasReachedMaximumDuration+ }++ private static let enabledKey = "KeepAlive.isEnabled"+ private static let maximumDurationKey = "KeepAlive.maximumContinuousDurationSeconds"+ private static let helperRegistrationFingerprintKey =+ "KeepAlive.helperRegistrationFingerprint"+ private static let helperRegistrationRetryDelays: [Duration] = [+ .milliseconds(500),+ .seconds(1),+ .seconds(2)+ ]+ private static let operationNotPermittedErrorCode = 1++ private static var helperService: SMAppService {+ SMAppService.daemon(plistName: CodexBarHelperIPC.daemonPlistName)+ }++ private static var helperAssetsArePresent: Bool {+ FileManager.default.fileExists(atPath: daemonPlistURL.path)+ && FileManager.default.isExecutableFile(atPath: helperExecutableURL.path)+ }++ private var helperRegistrationNeedsRefresh: Bool {+ guard let fingerprint = Self.helperRegistrationFingerprint else {+ return false+ }+ return defaults.string(forKey: Self.helperRegistrationFingerprintKey) != fingerprint+ }++ private func recordHelperRegistrationIfCurrent() {+ guard helperStatus.isRegisteredOrAwaitingApproval,+ let fingerprint = Self.helperRegistrationFingerprint else {+ return+ }+ defaults.set(fingerprint, forKey: Self.helperRegistrationFingerprintKey)+ }++ private static var helperRegistrationFingerprint: String? {+ guard let helperData = try? Data(contentsOf: helperExecutableURL, options: .mappedIfSafe),+ let daemonPlistData = try? Data(contentsOf: daemonPlistURL, options: .mappedIfSafe) else {+ return nil+ }++ var hasher = SHA256()+ for (name, data) in [+ (helperExecutableURL.lastPathComponent, helperData),+ (daemonPlistURL.lastPathComponent, daemonPlistData)+ ] {+ hasher.update(data: Data("\(name)\n\(data.count)\n".utf8))+ hasher.update(data: data)+ }+ return hasher.finalize().map { String(format: "%02x", $0) }.joined()+ }++ private static var appContentsURL: URL {+ Bundle.main.bundleURL.appending(path: "Contents", directoryHint: .isDirectory)+ }++ private static var helperExecutableURL: URL {+ appContentsURL+ .appending(path: "Resources", directoryHint: .isDirectory)+ .appending(path: "CodexBarHelper")+ }++ private static var daemonPlistURL: URL {+ appContentsURL+ .appending(path: "Library/LaunchDaemons", directoryHint: .isDirectory)+ .appending(path: CodexBarHelperIPC.daemonPlistName)+ }+}++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 invalidHelperProxy+ case connectionInterrupted++ var errorDescription: String? {+ switch self {+ case .invalidHelperProxy:+ "服务接口无效"+ case .connectionInterrupted:+ "服务连接中断"+ }+ }+}diff --git a/CodexBar/Services/KeepAlive/SystemSleepService.swift b/CodexBar/Services/KeepAlive/SystemSleepService.swiftnew file mode 100644index 0000000..6f5f75c--- /dev/null+++ b/CodexBar/Services/KeepAlive/SystemSleepService.swift@@ -0,0 +1,98 @@+import Foundation+import IOKit+import IOKit.pwr_mgt++@MainActor+final class SystemSleepService {+ struct Status: Equatable, Sendable {+ let isLidClosed: Bool+ let lidClosureCausesSleep: Bool++ var shouldSleepForLidClosure: Bool {+ isLidClosed && lidClosureCausesSleep+ }+ }++ private var idleSleepAssertionID = IOPMAssertionID(kIOPMNullAssertionID)++ func beginPreventingIdleSleep() -> IOReturn {+ guard idleSleepAssertionID == IOPMAssertionID(kIOPMNullAssertionID) else {+ return kIOReturnSuccess+ }++ var assertionID = IOPMAssertionID(kIOPMNullAssertionID)+ let result = IOPMAssertionCreateWithName(+ kIOPMAssertionTypePreventUserIdleSystemSleep as CFString,+ IOPMAssertionLevel(kIOPMAssertionLevelOn),+ "Codex 任务正在运行" as CFString,+ &assertionID+ )+ if result == kIOReturnSuccess {+ idleSleepAssertionID = assertionID+ }+ return result+ }++ func endPreventingIdleSleep() -> IOReturn {+ guard idleSleepAssertionID != IOPMAssertionID(kIOPMNullAssertionID) else {+ return kIOReturnSuccess+ }++ let result = IOPMAssertionRelease(idleSleepAssertionID)+ if result == kIOReturnSuccess || result == kIOReturnNotFound {+ idleSleepAssertionID = IOPMAssertionID(kIOPMNullAssertionID)+ }+ return result == kIOReturnNotFound ? kIOReturnSuccess : result+ }++ static func currentStatus() -> Status? {+ let rootDomain = IOServiceGetMatchingService(+ kIOMainPortDefault,+ IOServiceMatching("IOPMrootDomain")+ )+ guard rootDomain != IO_OBJECT_NULL else {+ return nil+ }+ defer {+ IOObjectRelease(rootDomain)+ }++ guard let isLidClosed = booleanProperty("AppleClamshellState", of: rootDomain),+ let lidClosureCausesSleep = booleanProperty(+ "AppleClamshellCausesSleep",+ of: rootDomain+ ) else {+ return nil+ }+ return Status(+ isLidClosed: isLidClosed,+ lidClosureCausesSleep: lidClosureCausesSleep+ )+ }++ static func requestSystemSleep() -> IOReturn {+ let connection = IOPMFindPowerManagement(mach_port_t(MACH_PORT_NULL))+ guard connection != IO_OBJECT_NULL else {+ return kIOReturnNotFound+ }+ defer {+ IOServiceClose(connection)+ }+ return IOPMSleepSystem(connection)+ }++ private static func booleanProperty(+ _ key: String,+ of rootDomain: io_service_t+ ) -> Bool? {+ guard let value = IORegistryEntryCreateCFProperty(+ rootDomain,+ key as CFString,+ kCFAllocatorDefault,+ 0+ )?.takeRetainedValue() else {+ return nil+ }+ return (value as? NSNumber)?.boolValue+ }+}diff --git a/CodexBar/Services/Notifications/NotificationSoundOption.swift b/CodexBar/Services/Notifications/NotificationSoundOption.swiftindex 5039de5..b25fe6f 100644--- a/CodexBar/Services/Notifications/NotificationSoundOption.swift+++ b/CodexBar/Services/Notifications/NotificationSoundOption.swift@@ -60,7 +60,7 @@ enum NotificationSoundOption: String, Identifiable {case .silent:"静音"case .systemDefault:- "系统提示音"+ "默认"case .basso:"Basso"case .blow:diff --git a/CodexBar/Services/Settings/WorkflowSyncSettings.swift b/CodexBar/Services/Settings/WorkflowSyncSettings.swiftindex 2034099..9527a5f 100644--- a/CodexBar/Services/Settings/WorkflowSyncSettings.swift+++ b/CodexBar/Services/Settings/WorkflowSyncSettings.swift@@ -174,7 +174,7 @@ final class WorkflowSyncSettings: ObservableObject {private nonisolated static func querySyncAvailability() async -> WorkflowSyncAvailabilityResult {await withCheckedContinuation { continuation in- CKContainer.default().accountStatus { status, error in+ WorkflowSyncCloudKit.makeContainer().accountStatus { status, error incontinuation.resume(returning: WorkflowSyncFailureReason.availabilityResult(status: status,diff --git a/CodexBar/Services/Workflow/WorkflowSyncService.swift b/CodexBar/Services/Workflow/WorkflowSyncService.swiftindex c5abef0..9010902 100644--- a/CodexBar/Services/Workflow/WorkflowSyncService.swift+++ b/CodexBar/Services/Workflow/WorkflowSyncService.swift@@ -4,6 +4,14 @@ import Foundationimport IOKitimport Security+nonisolated enum WorkflowSyncCloudKit {+ private static let containerIdentifier = "iCloud.app.zabrian.codexbar"++ static func makeContainer() -> CKContainer {+ CKContainer(identifier: containerIdentifier)+ }+}+/// 将本机 daily.jsonl 的脱敏聚合行同步到 CloudKit private databaseactor WorkflowSyncService {private let database: CKDatabase@@ -16,7 +24,7 @@ actor WorkflowSyncService {private var cachedAccountSalt: Data?init(- container: CKContainer = .default(),+ container: CKContainer = WorkflowSyncCloudKit.makeContainer(),fileManager: FileManager = .default,directoryURL: URL = WorkflowStorage.syncDirectoryURL()) {diff --git a/CodexBar/Views/Settings/AppSettingsView.swift b/CodexBar/Views/Settings/AppSettingsView.swiftindex 63d7f22..85822a4 100644--- a/CodexBar/Views/Settings/AppSettingsView.swift+++ b/CodexBar/Views/Settings/AppSettingsView.swift@@ -13,6 +13,7 @@ struct AppSettingsView: View {@ObservedObject var menuBarQuotaSettings: MenuBarQuotaSettings@ObservedObject var mainPanelSettings: MainPanelSettings@ObservedObject var notificationSettings: NotificationSettings+ @ObservedObject var keepAliveController: KeepAliveControllerlet onSyncChanged: (Bool) -> Voidlet onRebuildWorkflowData: WorkflowSyncScheduler.RebuildHandlerlet onNotificationOptionsAction: (NotificationOptionsPanelAction) -> Void@@ -43,11 +44,13 @@ struct AppSettingsView: View {LiquidGlassDivider()syncRowLiquidGlassDivider()- rebuildWorkflowDataRow+ keepAliveRowLiquidGlassDivider()- versionRow+ rebuildWorkflowDataRowLiquidGlassDivider()codexVersionSection+ LiquidGlassDivider()+ versionRow}.padding(Metrics.panelPadding).liquidGlassSurface(cornerRadius: Metrics.panelCornerRadius)@@ -79,9 +82,7 @@ struct AppSettingsView: View {menuBarQuotaSettings.refresh()mainPanelSettings.refresh()appUpdater.refreshAutomaticCheckSetting()- refreshCodexVersionSection()- notificationSettings.refreshAuthorizationStatus()- refreshRebuildableDates()+ refreshStatusRows()}.onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ incodexHookSettings.refresh()@@ -89,9 +90,7 @@ struct AppSettingsView: View {menuBarQuotaSettings.refresh()mainPanelSettings.refresh()codexHookSettings.verifyInstalledHooks()- refreshCodexVersionSection()- notificationSettings.refreshAuthorizationStatus()- refreshRebuildableDates()+ refreshStatusRows()}.onReceive(NotificationCenter.default.publisher(for: .settingsWindowDidOpen)) { _ inselectedRebuildRange = nil@@ -123,6 +122,7 @@ private extension AppSettingsView {static let panelCornerRadius: CGFloat = 10static let notificationOptionsButtonSize: CGFloat = 22static let menuBarQuotaPickerWidth: CGFloat = 72+ static let keepAliveDurationPickerWidth: CGFloat = 88static let syncStatusRowHeight: CGFloat = 16static let syncStatusValueWidth: CGFloat = 160static let statusAnimation = Animation.codexStatus@@ -247,6 +247,104 @@ private extension AppSettingsView {}}+ var keepAliveRow: some View {+ let caption = keepAliveCaption++ return VStack(alignment: .leading, spacing: 4) {+ SettingsToggleRow(+ icon: "moon.zzz",+ 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)))+ }+ }++ SettingsIndentedRow(alignment: .top) {+ Text(caption.message)+ .font(.caption)+ .foregroundStyle(caption.isError ? .red : .secondary)+ .fixedSize(horizontal: false, vertical: true)+ .contentTransition(.opacity)++ Spacer(minLength: 8)++ if caption.showsSystemSettingsButton {+ Button("打开系统设置") {+ keepAliveController.openSystemSettings()+ }+ .controlSize(.small)+ .fixedSize()+ .transition(.opacity.combined(with: .move(edge: .trailing)))+ }+ }+ }+ .animation(Metrics.statusAnimation, value: caption)+ .animation(Metrics.statusAnimation, value: keepAliveController.isEnabled)+ }++ var keepAliveCaption: KeepAliveCaption {+ if let errorMessage = keepAliveController.errorMessage {+ return KeepAliveCaption(message: errorMessage, isError: true)+ }+ guard codexHookSettings.isEnabled else {+ return KeepAliveCaption(message: "需要启用 CodexBar Hook")+ }+ guard keepAliveController.isEnabled else {+ return KeepAliveCaption(message: "当有 Codex 任务运行时禁止系统休眠, 任务结束后自动恢复")+ }++ switch keepAliveController.helperStatus {+ case .requiresApproval:+ return KeepAliveCaption(+ message: "需要授权允许 CodexBar 后台运行",+ showsSystemSettingsButton: true+ )+ case .notRegistered, .notFound:+ return KeepAliveCaption(message: "CodexBarHelper 尚未注册")+ case .enabled:+ if keepAliveController.hasReachedMaximumDuration {+ let action = keepAliveController.isPreventingSleep+ ? "正在恢复系统休眠"+ : "已允许系统休眠"+ return KeepAliveCaption(+ message: "已达到禁用休眠上限 (\(keepAliveController.maximumDuration.title)); \(action)"+ )+ }+ if keepAliveController.isPreventingSleep {+ return KeepAliveCaption(message: "当前禁止系统休眠")+ }+ return KeepAliveCaption(message: "当前允许系统休眠")+ }+ }+var syncRow: some View {let state = syncRowStatelet lastSyncText = syncSettings.lastUploadAtText@@ -399,6 +497,13 @@ private extension AppSettingsView {rebuildableDates = WorkflowStorage.rebuildableEventDateKeys()}+ func refreshStatusRows() {+ refreshCodexVersionSection()+ notificationSettings.refreshAuthorizationStatus()+ keepAliveController.refresh()+ refreshRebuildableDates()+ }+func rebuildWorkflowData() {let dateKeys = selectedRebuildDateKeysguard !dateKeys.isEmpty, !isRebuildingWorkflowData else {@@ -470,7 +575,7 @@ private extension AppSettingsView {)if notificationSettings.isEnabled, notificationSettings.isAuthorizationDenied {- notificationDeniedRows+ notificationDeniedRow.transition(.identity).transaction { transaction intransaction.animation = nil@@ -508,14 +613,19 @@ private extension AppSettingsView {}}- @ViewBuilder- var notificationDeniedRows: some View {- SettingsCaptionMessageRow(message: "系统通知权限未开启, 请在系统设置中允许 CodexBar 发送通知")+ var notificationDeniedRow: some View {SettingsIndentedRow {+ Text("系统通知权限未开启")+ .font(.caption)+ .foregroundStyle(.red)++ Spacer(minLength: 8)+Button("打开系统设置") {notificationSettings.openSystemNotificationSettings()}.controlSize(.small)+ .fixedSize()}}@@ -954,6 +1064,12 @@ private struct RebuildStatus {let isError: Bool}+private struct KeepAliveCaption: Equatable {+ let message: String+ var isError = false+ var showsSystemSettingsButton = false+}+private struct SyncRowState {/// 由 WorkflowSyncSettings.isEffectivelyActive 统一判定, 视图层不再拼接业务谓词let isActive: Booldiff --git a/CodexBarHelper/app.zabrian.codexbar.debug.helper.plist b/CodexBarHelper/app.zabrian.codexbar.debug.helper.plistnew file mode 100644index 0000000..2559151--- /dev/null+++ b/CodexBarHelper/app.zabrian.codexbar.debug.helper.plist@@ -0,0 +1,25 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>AssociatedBundleIdentifiers</key>+ <array>+ <string>app.zabrian.codexbar.debug</string>+ </array>+ <key>BundleProgram</key>+ <string>Contents/Resources/CodexBarHelper</string>+ <key>KeepAlive</key>+ <true/>+ <key>Label</key>+ <string>app.zabrian.codexbar.debug.helper</string>+ <key>MachServices</key>+ <dict>+ <key>app.zabrian.codexbar.debug.helper</key>+ <true/>+ </dict>+ <key>ProcessType</key>+ <string>Background</string>+ <key>RunAtLoad</key>+ <true/>+</dict>+</plist>diff --git a/CodexBarHelper/app.zabrian.codexbar.helper.plist b/CodexBarHelper/app.zabrian.codexbar.helper.plistnew file mode 100644index 0000000..d82b022--- /dev/null+++ b/CodexBarHelper/app.zabrian.codexbar.helper.plist@@ -0,0 +1,25 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>AssociatedBundleIdentifiers</key>+ <array>+ <string>app.zabrian.codexbar</string>+ </array>+ <key>BundleProgram</key>+ <string>Contents/Resources/CodexBarHelper</string>+ <key>KeepAlive</key>+ <true/>+ <key>Label</key>+ <string>app.zabrian.codexbar.helper</string>+ <key>MachServices</key>+ <dict>+ <key>app.zabrian.codexbar.helper</key>+ <true/>+ </dict>+ <key>ProcessType</key>+ <string>Background</string>+ <key>RunAtLoad</key>+ <true/>+</dict>+</plist>diff --git a/CodexBarHelper/main.swift b/CodexBarHelper/main.swiftnew file mode 100644index 0000000..734da84--- /dev/null+++ b/CodexBarHelper/main.swift@@ -0,0 +1,531 @@+import Darwin+import Foundation+import os+import Security++private let helperLog = Logger(+ subsystem: CodexBarHelperIPC.machServiceName,+ category: "helper"+)++private enum CodexBarHelperStorage {+ static let sentinelURL: URL = {+ guard let applicationSupportURL = FileManager.default.urls(+ for: .applicationSupportDirectory,+ in: .localDomainMask+ ).first else {+ preconditionFailure("无法获取 Application Support 目录")+ }+ return applicationSupportURL+ .appending(path: "CodexBar", directoryHint: .isDirectory)+ .appending(path: CodexBarHelperIPC.machServiceName + ".state")+ }()+}++private struct PmsetResult {+ let exitCode: Int32+ let output: String+}++private struct SleepRestoreResult {+ let exitCode: Int32+ let restoredSleepDisabled: Bool+}++private enum SleepRestoreTrigger: String {+ case appRequest = "CodexBar 主动请求"+ case connectionWatchdog = "CodexBar 连接断开"+ case helperStartup = "Helper 启动恢复"+ case sentinelCheck = "Helper 定时恢复"+ case helperTermination = "Helper 退出恢复"+}++private enum PmsetRunner {+ static func setSleepDisabled(_ disabled: Bool) -> PmsetResult {+ run(arguments: ["-a", "disablesleep", disabled ? "1" : "0"])+ }++ static func currentSleepDisabled() -> (result: PmsetResult, value: Bool?) {+ let result = run(arguments: ["-g"])+ return (result, parseSleepDisabled(from: result.output))+ }++ private static func run(arguments: [String]) -> PmsetResult {+ let process = Process()+ process.executableURL = URL(fileURLWithPath: "/usr/bin/pmset")+ process.arguments = arguments++ let pipe = Pipe()+ process.standardOutput = pipe+ process.standardError = pipe++ do {+ try process.run()+ } catch {+ return PmsetResult(exitCode: -1, output: error.localizedDescription)+ }++ let data = pipe.fileHandleForReading.readDataToEndOfFile()+ process.waitUntilExit()+ return PmsetResult(+ exitCode: process.terminationStatus,+ output: String(data: data, encoding: .utf8) ?? ""+ )+ }++ private static func parseSleepDisabled(from output: String) -> Bool? {+ for line in output.split(whereSeparator: \.isNewline) {+ let fields = line.split(whereSeparator: \.isWhitespace)+ guard fields.count >= 2, fields[0] == "SleepDisabled" else {+ continue+ }+ switch fields[1] {+ case "0":+ return false+ case "1":+ return true+ default:+ return nil+ }+ }+ // pmset 只在 disablesleep=1 时输出 SleepDisabled; 字段缺失表示默认值 0+ return false+ }+}++private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, CodexBarHelperProtocol,+ @unchecked Sendable {+ private let queue = DispatchQueue(label: CodexBarHelperIPC.machServiceName + ".state")+ private let sentinelURL = CodexBarHelperStorage.sentinelURL+ private var connections = Set<ObjectIdentifier>()+ private var watchdog: DispatchWorkItem?+ private var sentinelTimer: DispatchSourceTimer?+ private var signalSources = [DispatchSourceSignal]()+ private var listener: NSXPCListener?++ func run() {+ guard geteuid() == 0 else {+ helperLog.error("Helper 启动失败: 需要 root 身份")+ exit(EXIT_FAILURE)+ }++ do {+ try ensureSentinelDirectory()+ } catch {+ let sentinelDirectoryPath = sentinelURL.deletingLastPathComponent().path+ helperLog.error(+ "Helper 启动失败: 无法访问休眠设置目录; path=\(sentinelDirectoryPath, privacy: .public), detail=\(error.localizedDescription, privacy: .public)"+ )+ exit(EXIT_FAILURE)+ }++ if sentinelPreviousState() != nil {+ _ = restoreSleep(trigger: .helperStartup)+ }++ installSentinelTimer()+ installSignalHandlers()++ let clientCodeSigningRequirement: String+ do {+ clientCodeSigningRequirement = try Self.makeClientCodeSigningRequirement()+ } catch {+ helperLog.error(+ "Helper 启动失败: \(error.localizedDescription, privacy: .public)"+ )+ exit(EXIT_FAILURE)+ }++ let listener = NSXPCListener(machServiceName: CodexBarHelperIPC.machServiceName)+ listener.setConnectionCodeSigningRequirement(clientCodeSigningRequirement)+ listener.delegate = self+ listener.resume()+ self.listener = listener+ }++ func setSleepDisabled(+ _ disabled: Bool,+ reply: @escaping @Sendable (Int32, Bool) -> Void+ ) {+ queue.async { [self] in+ if disabled {+ reply(disableSleep(), true)+ } else {+ let result = restoreSleep(trigger: .appRequest)+ reply(result.exitCode, result.restoredSleepDisabled)+ }+ }+ }++ func listener(+ _: NSXPCListener,+ shouldAcceptNewConnection newConnection: NSXPCConnection+ ) -> Bool {+ let identifier = ObjectIdentifier(newConnection)+ newConnection.exportedInterface = NSXPCInterface(+ with: CodexBarHelperProtocol.self+ )+ newConnection.exportedObject = self++ let connectionDropped: () -> Void = { [weak self] in+ self?.connectionDropped(identifier)+ }+ newConnection.invalidationHandler = connectionDropped+ newConnection.interruptionHandler = connectionDropped++ queue.sync {+ connections.insert(identifier)+ watchdog?.cancel()+ watchdog = nil+ }+ newConnection.resume()+ return true+ }++ private func connectionDropped(_ identifier: ObjectIdentifier) {+ queue.async { [self] in+ guard connections.remove(identifier) != nil,+ connections.isEmpty,+ sentinelPreviousState() != nil else {+ return+ }++ watchdog?.cancel()+ let workItem = DispatchWorkItem { [weak self] in+ guard let self else {+ return+ }+ watchdog = nil+ guard connections.isEmpty, sentinelPreviousState() != nil else {+ return+ }+ _ = restoreSleep(trigger: .connectionWatchdog)+ }+ watchdog = workItem+ queue.asyncAfter(+ deadline: .now() + CodexBarHelperIPC.watchdogGraceSeconds,+ execute: workItem+ )+ }+ }++ private func disableSleep() -> Int32 {+ var didCreateSentinel = false+ if sentinelPreviousState() == nil {+ let current = PmsetRunner.currentSleepDisabled()+ guard current.result.exitCode == 0, let wasDisabled = current.value else {+ helperLog.error(+ "读取休眠设置失败: error=\(current.result.exitCode) detail=\(current.result.output, privacy: .public)"+ )+ return current.result.exitCode == 0 ? -1 : current.result.exitCode+ }++ do {+ try writeSentinel(previouslyDisabled: wasDisabled)+ didCreateSentinel = true+ } catch {+ let sentinelPath = sentinelURL.path+ helperLog.error(+ "保存休眠设置失败: path=\(sentinelPath, privacy: .public), detail=\(error.localizedDescription, privacy: .public)"+ )+ return -1+ }+ }++ let result = PmsetRunner.setSleepDisabled(true)+ guard result.exitCode == 0 else {+ if didCreateSentinel {+ try? FileManager.default.removeItem(at: sentinelURL)+ }+ helperLog.error(+ "关闭系统休眠失败: error=\(result.exitCode), detail=\(result.output, privacy: .public)"+ )+ return result.exitCode+ }++ helperLog.notice("系统休眠已关闭: 任务正在运行")+ return 0+ }++ @discardableResult+ private func restoreSleep(trigger: SleepRestoreTrigger) -> SleepRestoreResult {+ guard let previouslyDisabled = sentinelPreviousState() else {+ return SleepRestoreResult(exitCode: 0, restoredSleepDisabled: true)+ }++ let previousValue = previouslyDisabled ? 1 : 0+ let result = PmsetRunner.setSleepDisabled(previouslyDisabled)+ guard result.exitCode == 0 else {+ helperLog.error(+ "恢复系统休眠失败: reason=\(trigger.rawValue, privacy: .public), SleepDisabled=\(previousValue), error=\(result.exitCode), detail=\(result.output, privacy: .public)"+ )+ return SleepRestoreResult(+ exitCode: result.exitCode,+ restoredSleepDisabled: true+ )+ }++ try? FileManager.default.removeItem(at: sentinelURL)+ helperLog.notice(+ "系统休眠已恢复: reason=\(trigger.rawValue, privacy: .public), SleepDisabled=\(previousValue)"+ )+ return SleepRestoreResult(+ exitCode: 0,+ restoredSleepDisabled: previouslyDisabled+ )+ }++ private func installSentinelTimer() {+ let timer = DispatchSource.makeTimerSource(queue: queue)+ timer.schedule(+ deadline: .now() + CodexBarHelperIPC.sentinelCheckIntervalSeconds,+ repeating: CodexBarHelperIPC.sentinelCheckIntervalSeconds,+ leeway: .seconds(5)+ )+ timer.setEventHandler { [weak self] in+ guard let self,+ connections.isEmpty,+ watchdog == nil,+ sentinelPreviousState() != nil else {+ return+ }+ _ = restoreSleep(trigger: .sentinelCheck)+ }+ timer.resume()+ sentinelTimer = timer+ }++ private func installSignalHandlers() {+ for signalNumber in [SIGTERM, SIGINT] {+ signal(signalNumber, SIG_IGN)+ let source = DispatchSource.makeSignalSource(signal: signalNumber, queue: queue)+ source.setEventHandler { [weak self] in+ guard let self else {+ exit(EXIT_SUCCESS)+ }+ _ = restoreSleep(trigger: .helperTermination)+ exit(EXIT_SUCCESS)+ }+ source.resume()+ signalSources.append(source)+ }+ }++ private func ensureSentinelDirectory() throws {+ let directoryURL = sentinelURL.deletingLastPathComponent()+ var info = stat()+ if lstat(directoryURL.path, &info) == 0 {+ try validateSentinelDirectory(info)+ return+ }++ guard errno == ENOENT else {+ throw POSIXError(POSIXErrorCode(rawValue: errno) ?? .EIO)+ }+ try FileManager.default.createDirectory(+ at: directoryURL,+ withIntermediateDirectories: false+ )+ try FileManager.default.setAttributes(+ [.ownerAccountID: 0, .groupOwnerAccountID: 0, .posixPermissions: 0o755],+ ofItemAtPath: directoryURL.path+ )+ }++ private func validateSentinelDirectory(_ info: stat) throws {+ guard info.st_mode & S_IFMT == S_IFDIR else {+ throw CodexBarHelperError.insecureSentinelDirectory(+ "目录类型错误: actual=\(fileTypeName(info.st_mode)), expected=directory"+ )+ }+ guard info.st_uid == 0 else {+ throw CodexBarHelperError.insecureSentinelDirectory(+ "所有者错误: actual=\(info.st_uid), expected=0"+ )+ }+ guard info.st_mode & 0o022 == 0 else {+ throw CodexBarHelperError.insecureSentinelDirectory(+ "目录权限错误: actual=\(permissionString(info.st_mode)), forbidden=0022"+ )+ }+ }++ private func writeSentinel(previouslyDisabled: Bool) throws {+ try Data(previouslyDisabled ? "1".utf8 : "0".utf8).write(+ to: sentinelURL,+ options: .atomic+ )+ try FileManager.default.setAttributes(+ [.ownerAccountID: 0, .groupOwnerAccountID: 0, .posixPermissions: 0o600],+ ofItemAtPath: sentinelURL.path+ )+ guard try readSentinelPreviousState() != nil else {+ throw CodexBarHelperError.invalidSentinel("记录不存在")+ }+ }++ private func sentinelPreviousState() -> Bool? {+ try? readSentinelPreviousState()+ }++ private func readSentinelPreviousState() throws -> Bool? {+ var info = stat()+ guard lstat(sentinelURL.path, &info) == 0 else {+ if errno == ENOENT {+ return nil+ }+ throw CodexBarHelperError.invalidSentinel(+ "读取属性失败: errno=\(errno)"+ )+ }+ guard info.st_mode & S_IFMT == S_IFREG else {+ throw CodexBarHelperError.invalidSentinel(+ "文件类型错误: actual=\(fileTypeName(info.st_mode)), expected=file"+ )+ }+ guard info.st_uid == 0 else {+ throw CodexBarHelperError.invalidSentinel(+ "所有者错误: actual=\(info.st_uid), expected=0"+ )+ }+ guard info.st_mode & 0o022 == 0 else {+ throw CodexBarHelperError.invalidSentinel(+ "文件权限错误: actual=\(permissionString(info.st_mode)), forbidden=0022"+ )+ }++ let data: Data+ do {+ data = try Data(contentsOf: sentinelURL)+ } catch {+ throw CodexBarHelperError.invalidSentinel(+ "读取内容失败: detail=\(error.localizedDescription)"+ )+ }+ guard let value = String(data: data, encoding: .utf8) else {+ throw CodexBarHelperError.invalidSentinel(+ "文件编码错误: actual=unknown, expected=UTF-8"+ )+ }++ switch value {+ case "0":+ return false+ case "1":+ return true+ default:+ throw CodexBarHelperError.invalidSentinel(+ "文件内容错误: actual=\(data.count), expected=0|1"+ )+ }+ }++ private func fileTypeName(_ mode: mode_t) -> String {+ let type = mode & S_IFMT+ if type == S_IFREG {+ return "file"+ }+ if type == S_IFDIR {+ return "directory"+ }+ if type == S_IFLNK {+ return "symlink"+ }+ return String(format: "0x%X", Int32(type))+ }++ private func permissionString(_ mode: mode_t) -> String {+ String(format: "%04o", Int32(mode & 0o7777))+ }++ private static func makeClientCodeSigningRequirement() throws -> String {+ var runningCode: SecCode?+ var status = SecCodeCopySelf(SecCSFlags(), &runningCode)+ guard status == errSecSuccess, let runningCode else {+ throw CodexBarHelperError.codeSigningValidationFailed(+ "读取运行签名失败: Operation=SecCodeCopySelf, Status=\(status)"+ )+ }++ var staticCode: SecStaticCode?+ status = SecCodeCopyStaticCode(runningCode, SecCSFlags(), &staticCode)+ guard status == errSecSuccess, let staticCode else {+ throw CodexBarHelperError.codeSigningValidationFailed(+ "读取静态签名失败: Operation=SecCodeCopyStaticCode, Status=\(status)"+ )+ }++ var signingInformation: CFDictionary?+ status = SecCodeCopySigningInformation(+ staticCode,+ SecCSFlags(rawValue: kSecCSSigningInformation),+ &signingInformation+ )+ guard status == errSecSuccess, let signingInformation else {+ throw CodexBarHelperError.codeSigningValidationFailed(+ "读取签名信息失败: Operation=SecCodeCopySigningInformation, Status=\(status)"+ )+ }++ let values = signingInformation as NSDictionary+ guard let teamIdentifier = values[kSecCodeInfoTeamIdentifier] as? String else {+ throw CodexBarHelperError.codeSigningValidationFailed("Team ID 缺失")+ }+ guard let helperIdentifier = values[kSecCodeInfoIdentifier] as? String else {+ throw CodexBarHelperError.codeSigningValidationFailed("Helper 标识符缺失")+ }++ let helperSuffix = CodexBarHelperIPC.helperBundleIdentifierSuffix+ guard helperIdentifier.hasSuffix(helperSuffix) else {+ throw CodexBarHelperError.codeSigningValidationFailed(+ "Helper 标识符错误: actual=\(helperIdentifier), expected=*\(helperSuffix)"+ )+ }++ let clientIdentifier = String(helperIdentifier.dropLast(helperSuffix.count))+ let identifierCharacters = CharacterSet.alphanumerics.union(+ CharacterSet(charactersIn: ".-")+ )+ guard !teamIdentifier.isEmpty else {+ throw CodexBarHelperError.codeSigningValidationFailed("Team ID 为空")+ }+ guard teamIdentifier.unicodeScalars.allSatisfy(CharacterSet.alphanumerics.contains) else {+ throw CodexBarHelperError.codeSigningValidationFailed(+ "Team ID 格式错误: \(teamIdentifier)"+ )+ }+ guard !clientIdentifier.isEmpty else {+ throw CodexBarHelperError.codeSigningValidationFailed("客户端标识符为空")+ }+ guard clientIdentifier.unicodeScalars.allSatisfy(identifierCharacters.contains) else {+ throw CodexBarHelperError.codeSigningValidationFailed(+ "客户端标识符格式错误: \(clientIdentifier)"+ )+ }++ return "anchor apple generic"+ + " and certificate leaf[subject.OU] = \"\(teamIdentifier)\""+ + " and identifier \"\(clientIdentifier)\""+ }+}++private enum CodexBarHelperError: LocalizedError {+ case insecureSentinelDirectory(String)+ case invalidSentinel(String)+ case codeSigningValidationFailed(String)++ var errorDescription: String? {+ switch self {+ case let .insecureSentinelDirectory(detail):+ "休眠设置目录无效: \(detail)"+ case let .invalidSentinel(detail):+ "休眠设置记录无效: \(detail)"+ case let .codeSigningValidationFailed(reason):+ "签名校验失败: \(reason)"+ }+ }+}++private let runtime = CodexBarHelperRuntime()+runtime.run()+dispatchMain()diff --git a/Docs/CodexHook.md b/Docs/CodexHook.mdindex 48a1087..cce793a 100644--- a/Docs/CodexHook.md+++ b/Docs/CodexHook.md@@ -140,6 +140,8 @@ Hook 数据目录:`CodexActivityMonitor` 是 `@MainActor ObservableObject` 长期对象。Hook 开启时它启动 `HookEventTailReader`,关闭时停止读取并清空状态;通知与触觉开关只控制是否发送对应提醒,不控制监测器生命周期。实时状态只保存在内存,不写入新的历史文件,也不增加 CloudKit 字段或网络请求。+可选的 `KeepAliveController` 复用同一份实时快照,只在 `runningTasks` 非空且尚未达到用户选择的最长防休眠期限时请求关闭系统休眠并持有 `PreventUserIdleSystemSleep` assertion。已经确认进入 `waitingApproval` 的任务不计入运行数量;自动 reviewer 仍保持 `.running`,因此不会被误当成用户等待。控制器以稳定的任务 `id` 识别首次进入运行态的新任务,并记录上一份快照的等待任务;每个新运行任务以及同一任务从等待恢复运行都会把唯一共享起点更新为当前时间,即使旧任务仍在运行或上一周期已经到期也会开始新周期。普通 Hook 活动仍按实时状态机规则更新任务的 `lastActivityAt` 和过期时间,但不会更新防休眠期限的独立起点;App 激活和设置刷新同样不会续期。最后一个运行任务离开运行态或最近运行阶段对应的期限到期后恢复任务开始前的休眠设置,再释放 assertion,让 macOS 按当前空闲计时、其他 assertion 和电源策略重新评估是否应休眠;普通合盖且恢复结果为 `SleepDisabled=0` 时还会主动请求休眠。关闭 Hook 会同步关闭并持久化防休眠选项、请求恢复系统休眠,并使设置项置灰;重新开启 Hook 不会自动重新开启防休眠。该功能不改变 Hook 事件、原始文件或聚合口径,详细边界见 [KeepAlive.md](KeepAlive.md)。+`HookEventTailReader` 是独立 actor,文件 I/O 和 JSON 解码不占用 MainActor。读取分为两类批次:- `bootstrap`:App 启动、当前活动事件文件被截断或替换时,按 512 KB 分块流式读取滚动 24 小时涉及的日期文件,并按事件时间过滤窗口之外的数据。每次尝试开始时清空恢复态,成功后只发布一次最终快照,整个 bootstrap 不发布活动 transition。读取前记录各文件 inode 和 size;当前文件只读到当时最后一个完整换行,后续新增字节由 live 消费。文件边界变化时最多重试三次,连续失败则再次清空恢复态并跳过当前已有字节,避免把历史事件误当 live 通知。@@ -198,7 +200,7 @@ CodexBar 最多保留最近 210 天数据。完整链路见 [CrossDeviceSync.md](CrossDeviceSync.md)。本节只保留和 Hook 统计直接相关的同步摘要。-设置页「跨设备同步」由 `WorkflowSyncSettings` 管理。该开关只有在 Codex Hook 开启且 `CKContainer.default().accountStatus` 为 `available` 时可操作;账号不可用时开关禁用,并在开关下方显示「同步不可用」。关闭 Hook 后不会继续触发工作流统计同步。同步使用 CloudKit private database,数据归属当前登录的 iCloud 账号,不跨 iCloud 账号迁移或合并。CodexBar 自己创建和维护的记录都保存在 custom zone `CodexBarZone`,不会写入 `_defaultZone`。+设置页「跨设备同步」由 `WorkflowSyncSettings` 管理。该开关只有在 Codex Hook 开启且 `WorkflowSyncCloudKit.makeContainer().accountStatus` 为 `available` 时可操作;`WorkflowSyncCloudKit` 固定使用 `iCloud.app.zabrian.codexbar` 容器。账号不可用时开关禁用,并在开关下方显示「同步不可用」。关闭 Hook 后不会继续触发工作流统计同步。同步使用 CloudKit private database,数据归属当前登录的 iCloud 账号,不跨 iCloud 账号迁移或合并。CodexBar 自己创建和维护的记录都保存在 custom zone `CodexBarZone`,不会写入 `_defaultZone`。CloudKit 中每个 iCloud 账号会保存一条账号级 salt:diff --git a/Docs/CrossDeviceSync.md b/Docs/CrossDeviceSync.mdindex de46d6b..2e4cabe 100644--- a/Docs/CrossDeviceSync.md+++ b/Docs/CrossDeviceSync.md@@ -20,7 +20,7 @@- `sessionIds` 和 `turnIds`- CodexBar 设置项、快捷键、日志窗口内容-同步目标是当前 macOS 登录的 iCloud 账号的 CloudKit private database。数据不会跨 iCloud 账号迁移或合并;切换 iCloud 账号后会进入另一个 private database。+同步目标是当前 macOS 登录的 iCloud 账号在 `iCloud.app.zabrian.codexbar` 容器中的 CloudKit private database。代码显式使用该容器标识,不通过 App bundle identifier 推导默认容器,因此独立 bundle identifier 的 Debug 构建不会误连到不存在的 `iCloud.app.zabrian.codexbar.debug`。数据不会跨 iCloud 账号迁移或合并;切换 iCloud 账号后会进入另一个 private database。## 代码入口@@ -86,7 +86,7 @@ Sync/cursor.data## CloudKit 数据结构-CloudKit 使用默认 container 的 private database。CodexBar 自己创建和维护的记录都保存在 custom zone `CodexBarZone`;不会向 CloudKit `_defaultZone` 写入同步数据。+CloudKit 使用显式标识为 `iCloud.app.zabrian.codexbar` 的 container private database。CodexBar 自己创建和维护的记录都保存在 custom zone `CodexBarZone`;不会向 CloudKit `_defaultZone` 写入同步数据。账号级 metadata 记录保存在 custom zone `CodexBarZone`:@@ -166,7 +166,7 @@ deviceId = HMAC_SHA256(accountSalt, IOPlatformUUID)```textCodex Hook 已开启Codex Hook 当前没有正在更新-CKContainer.default().accountStatus == .available+WorkflowSyncCloudKit.makeContainer().accountStatus == .available```UI 状态:diff --git a/Docs/DevelopmentGuide.md b/Docs/DevelopmentGuide.mdindex 152b6b9..3f9d807 100644--- a/Docs/DevelopmentGuide.md+++ b/Docs/DevelopmentGuide.md@@ -2,7 +2,7 @@本文面向继续开发 CodexBar 的维护者, 记录当前 App 的主要流程, 数据边界和模块协作方式-更细的 app-server 协议见 [AppServer.md](AppServer.md), Codex Hook 统计口径见 [CodexHook.md](CodexHook.md), 跨设备同步链路见 [CrossDeviceSync.md](CrossDeviceSync.md)+更细的 app-server 协议见 [AppServer.md](AppServer.md), Codex Hook 统计口径见 [CodexHook.md](CodexHook.md), 跨设备同步链路见 [CrossDeviceSync.md](CrossDeviceSync.md), 防休眠边界见 [KeepAlive.md](KeepAlive.md)## 1. 应用定位与工程边界@@ -21,15 +21,17 @@ App 通过本机 Codex app-server 读取账号, 额度和 token 用量, 通过 C源码目录职责:-| 目录 | 职责 |-| ----------------------- | ----------------------------------------------------------------------- |-| `CodexBar/App/` | SwiftUI 入口和 AppDelegate 启动分支 |-| `CodexBar/Controllers/` | 菜单栏, 菜单面板, 侧边 child panel, 设置窗口, 日志窗口和窗口行为 |-| `CodexBar/Models/` | account, quota, usage, workflow, activity, 日期网格、快捷键和错误模型 |-| `CodexBar/Services/` | app-server, Codex CLI 解析, 版本探测, Hook 设置, 统计维护, 更新, 登录项 |-| `CodexBar/Views/` | 菜单面板, 设置窗口, 日志窗口和共享 Liquid Glass 样式 |-| `Docs/` | app-server, Hook 和开发文档 |-| `Scripts/` | Release 构建、公证、DMG 和 appcast 发布脚本 |+| 目录 | 职责 |+| ----------------------- | --------------------------------------------------------------------- |+| `CodexBar/App/` | SwiftUI 入口和 AppDelegate 启动分支 |+| `CodexBar/Controllers/` | 菜单栏, 菜单面板, 侧边 child panel, 设置窗口, 日志窗口和窗口行为 |+| `CodexBar/Models/` | account, quota, usage, workflow, activity, 日期网格、快捷键和错误模型 |+| `CodexBar/Services/` | app-server, Codex CLI 解析, Hook、统计、防休眠、更新和登录项 |+| `CodexBar/Views/` | 菜单面板, 设置窗口, 日志窗口和共享 Liquid Glass 样式 |+| `Shared/` | 主 App 与 root helper 共用的最小 XPC 契约 |+| `CodexBarHelper/` | 防休眠 root helper 与嵌入 App 的 LaunchDaemon plist |+| `Docs/` | app-server, Hook 和开发文档 |+| `Scripts/` | Release 构建、公证、DMG 和 appcast 发布脚本 |## 2. 总体架构@@ -72,6 +74,7 @@ sequenceDiagram- `WorkflowViewModel`: Hook 工作流统计快照- `CodexHookSettings`: Hook 配置状态和写入操作- `CodexActivityMonitor`: Hook 实时任务状态、UI 快照和 live transition+- `KeepAliveController`: 订阅实时任务快照、维护用户偏好和 helper 授权/XPC 状态- `WorkflowSyncSettings`: 跨设备同步偏好、账号可用性、同步中和失败状态- `GlobalHotKeySettings`: 全局快捷键配置和错误状态- `MenuBarQuotaSettings`: 菜单栏额度指示偏好和窗口选择@@ -90,7 +93,19 @@ sequenceDiagram启动时还会把系统 tooltip 首次出现延迟 `NSInitialToolTipDelay` 设置为 200 ms, 让主面板同步图标等短提示更快出现。-App 退出时, `applicationWillTerminate` 调用 `StatusItemController.uninstall()` 和 `CodexActivityMonitor.stop()`, 关闭菜单面板与实时 tail, 注销全局快捷键, 移除订阅并从系统状态栏移除 status item+App 退出时, `applicationWillTerminate` 调用 `StatusItemController.uninstall()`、`KeepAliveController.stop()` 和 `CodexActivityMonitor.stop()`, 关闭菜单面板与实时 tail, 注销全局快捷键, 释放防休眠连接, 移除订阅并从系统状态栏移除 status item。`KeepAliveController.stop()` 会先进入停止态,再取消 XPC 重试、最长时限任务和 Helper 注册任务;注册任务的迟到结果只有在控制器仍运行且任务未取消时才能提交状态或重新收敛防休眠++### 3.1 任务运行期防休眠++设置页「阻止系统休眠」持久化到 `KeepAlive.isEnabled`,依赖 Codex Hook。最长防休眠期限为 1、2、4、8、12、24 小时或无限制,缺失或无效值回退为 12 小时,持久化键为 `KeepAlive.maximumContinuousDurationSeconds`。`KeepAliveController` 订阅 Hook 开关;Hook 关闭时立即把防休眠选项设为关闭、清除开启偏好并请求恢复,设置页在 Hook 关闭期间将该选项置灰,Hook 重新开启后不会自动恢复开启。控制器只把 `CodexActivitySnapshot.runningTasks` 非空视为需要保活;`waitingTasks`、最近完成和最近终止都不计入。多个并发任务中只要仍有一个运行任务就继续保活,最后一个运行任务进入等待、完成、终止或从快照移除后立即请求恢复。++控制器用 `CodexActivityTaskSnapshot.id` 识别新运行任务,并记录上一份快照中的等待任务,只维护一个期限起点。第一个运行任务触发保活时建立起点;后续任何首次进入运行态的新任务,或同一任务从 `waitingApproval` 恢复为 `running`,都会把起点更新为当前时间并重排到期任务,因此旧任务仍在运行或本轮已经到期都不妨碍新的运行阶段开始完整周期。同一运行阶段内的工具事件、其他 Hook 更新、App 激活和设置刷新不会更新起点;无限制不创建计时任务。最后一个运行任务进入等待时会恢复系统休眠,获批恢复运行时从恢复时刻重新获得完整期限;多任务中即使还有其他任务一直运行,这次恢复也会更新全部运行任务共享的截止时间。到期后控制器设置上限锁存状态并请求恢复,直到新运行任务或等待任务恢复运行、所有运行和等待任务都消失、功能关闭或 helper 不再可用。用户把期限改大且按最近运行阶段起点仍有剩余时间,或改为无限制时,也可以继续当前周期。++`SystemSleepService` 在进入保活前创建 `kIOPMAssertionTypePreventUserIdleSystemSleep` assertion,再由 helper 设置 `SleepDisabled=1`:前者明确阻止空闲休眠,后者覆盖普通 assertion 无法覆盖的合盖和手动休眠。每次 App 成功恢复时,先由 helper 还原任务开始前的 `SleepDisabled`,再释放 assertion,使 macOS 的空闲休眠策略在全局禁休眠已经解除后重新计算当前空闲时间、其他 assertion 和电源条件;因此已经达到空闲期限的开盖 Mac 可以由系统立即休眠,App 不自行猜测空闲期限或绕过系统条件强制休眠。随后只要 helper 确认结果为 `SleepDisabled=0`,且 `AppleClamshellState` 与 `AppleClamshellCausesSleep` 表明当前处于普通合盖应休眠状态,App 就调用 `IOPMSleepSystem` 补偿禁休眠期间被抑制的合盖休眠。该恢复流程统一覆盖任务等待、完成、终止、空闲、用户关闭功能和期限到达;App 已退出后的 helper 兜底恢复仍只负责还原原设置。++普通 power assertion 或 `caffeinate` 不能可靠阻止 MacBook 合盖休眠,因此工程使用 `SMAppService.daemon` 注册嵌入 App 的 `CodexBarHelper`,由 root helper 执行 `/usr/bin/pmset -a disablesleep 1/0`;空闲休眠 assertion 由无特权的主 App 持有,root helper 只负责固定的休眠设置切换和恢复哨兵。helper 只接受 Team ID 与当前构建配置 bundle identifier 都匹配的 CodexBar XPC 客户端。Debug 使用 `app.zabrian.codexbar.debug` 和独立的 helper 服务身份,Release 使用 `app.zabrian.codexbar`,避免开发授权影响正式版本。Mach service 名由当前进程的 bundle identifier 派生:App 添加 `.helper` 后缀,helper 直接使用自身 identifier;LaunchDaemon plist 名和 helper 私有哨兵文件名再由 service 名派生。首次开启可能进入 `requiresApproval`,设置页提供「打开系统设置」;批准后 App 再次 active 时刷新状态并按当前任务快照收敛。控制器按固定顺序计算嵌入的 helper 可执行文件与当前 LaunchDaemon plist 的内容 SHA-256,并把已注册服务对应的指纹保存在当前 App 身份的 `UserDefaults`。每次启动都会检查已注册或等待批准的服务,即使功能关闭;任一文件内容变化时会注销并重新注册,两个文件内容均未变化时不会因 App 本体更新重复注册。功能关闭且服务未注册时不主动注册。注册任务在注销前和注销完成后检查取消状态,停止后的结果不会提交状态、打开系统设置或触发防休眠。针对 macOS 在注销后立即重新注册可能返回的 `SMAppServiceErrorDomain Code=1` 竞态,只做 0.5、1、2 秒有限退避重试,其他错误不重试。++helper 在切换前把原始 `SleepDisabled` 值写入 root-owned `0600` 哨兵,恢复时写回原值而不是无条件写 `0`,避免覆盖用户或其他工具原有的禁休眠设置,并在 XPC reply 中把恢复后的值返回给 App。App 连接断开后有 15 秒看门狗,helper 每 60 秒自检残留哨兵;helper 启动、收到终止信号或 App 正常请求时也会尝试恢复。详细打包、安全边界与手动验收见 [KeepAlive.md](KeepAlive.md)。## 4. 菜单栏, 菜单面板与窗口流程@@ -921,6 +936,7 @@ CloudKit Production schema 必须包含当前 schema `4` 使用的字段;schem- `WorkflowSyncSettings.refresh()`- `MenuBarQuotaSettings.refresh()`- `MainPanelSettings.refresh()`+- `KeepAliveController.refresh()`设置窗口按 SwiftUI 内容 `fittingSize` 自适应高度, 但必须校验尺寸有限且夹紧到当前屏幕可见区域内的安全上限, 避免 SwiftUI 初始化或状态刷新重入时给出异常尺寸导致空白大窗口。`MenuBarQuotaSettings.refresh()` 可能被设置页 `onAppear` 和 `didBecomeActive` 调用, 发布 `selection` 时需要延后到下一轮 MainActor, 避免在 SwiftUI view update 中同步发布造成未定义布局行为。@@ -934,15 +950,16 @@ CloudKit Production schema 必须包含当前 schema `4` 使用的字段;schem- `CodexCLIVersionViewModel.refresh()`- `CodexStatusViewModel.refreshCodexConnectionInfo()`- `NotificationSettings.refreshAuthorizationStatus()`+- `KeepAliveController.refresh()`- `WorkflowStorage.rebuildableEventDateKeys()`-App 再次成为 active 时, 也会刷新 Hook、同步、菜单栏额度、主面板、Codex 版本、通知授权和可重建日期, 并重新运行 `hooks/list` 验证。`SettingsWindowController.open()` 发布 `.settingsWindowDidOpen` 后, 日期重建范围、确认弹窗和上次结果消息恢复为未选择状态。+App 再次成为 active 时, 也会刷新 Hook、同步、菜单栏额度、主面板、Codex 版本、通知授权、防休眠 helper 状态和可重建日期, 并重新运行 `hooks/list` 验证。`SettingsWindowController.open()` 发布 `.settingsWindowDidOpen` 后, 日期重建范围、确认弹窗和上次结果消息恢复为未选择状态。版本探测内部有 60 秒节流, 避免 `onAppear` 和 `didBecomeActive` 连续触发时重复启动子进程设置项:-主设置卡片依次展示「开机自动启动」「自动检查更新」「菜单栏额度指示」「设置快捷键」「CodexBar Hook」「主面板任务中心」「系统通知」「跨设备同步」「重建数据」「CodexBar 版本」和「Codex 版本」。+主设置卡片依次展示「开机自动启动」「自动检查更新」「菜单栏额度指示」「设置快捷键」「CodexBar Hook」「主面板任务中心」「系统通知」「跨设备同步」「阻止系统休眠」「重建数据」「Codex 版本」和「CodexBar 版本」。跨设备同步开启时,状态子行始终保留固定 16 pt 高的单行布局;右侧固定宽度 `ZStack` 让同步时间和 `.mini` 进度指示以交叉淡入淡出切换,不对 AppKit 进度控件应用几何缩放,也不改变该行高度或控件位置。关闭同步后移除整行占位,让设置窗口 fitting size 随开关状态缩回。@@ -957,15 +974,17 @@ App 再次成为 active 时, 也会刷新 Hook、同步、菜单栏额度、主| 系统通知 | `NotificationSettings` + `UNUserNotificationCenter` | 总开关、五类通知子开关、任务触觉开关与阈值写入 `UserDefaults`; 首次开启时请求系统通知授权 || Codex TUI 通知 | `CodexCLINotificationSettings` + app-server `config/read` / `config/batchWrite` | 读取用户级 `[tui].notifications`; 缺失时按开启处理,关闭/开启分别 upsert `false` / `true`,不修改顶层 `notify` || 跨设备同步 | `WorkflowSyncSettings` + CloudKit account status + `WorkflowSyncScheduler` | Hook 开启且同步账号可用时写入 `UserDefaults`; 开启时标记 `needsBackfill` 并请求调度同步 |+| 阻止系统休眠 | `KeepAliveController` + `CodexActivityMonitor` + `SMAppService` | Hook 开启时允许写入 `KeepAlive.isEnabled`; 运行任务出现后通过 helper 和 idle sleep assertion 阻止休眠,等待、结束、关闭或到期后恢复 || 重建数据 | `WorkflowStorage.rebuildableEventDateKeys()` + `WorkflowSyncScheduler` | 选择最近 210 天内的日期范围, 将范围内非空本机事件日期交给调度器逐日重建, 并登记当前设备对应日期的待云端替换状态 |-| CodexBar 版本 | Bundle + AppUpdater 状态 | 有更新状态时优先显示动态消息 || Codex 版本 | `CodexCLIVersionSnapshot` + 当前 app-server 握手信息 | 路径点击复制到剪贴板 |+| CodexBar 版本 | Bundle + AppUpdater 状态 | 有更新状态时优先显示动态消息 |错误显示:- 开机启动失败显示在设置组与底部按钮组之间的独立错误组- Hook 设置失败, 全局禁用, 自动信任写入失败或验证异常显示在 Hook 选项下方- 同步账号不可用时显示在跨设备同步开关下方+- 防休眠依赖、helper 授权、注册状态、当前休眠状态和切换错误显示在阻止系统休眠开关下方- 同步运行失败不在设置页展示原始错误; 主面板同步图标 tooltip 显示归类后的短错误- 重建行始终保留一行消息位置: 未选择时显示「未选择重建日期范围」, 只选择起点时显示「选择结束日期」, 范围完成且存在数据时显示完整日历范围的「已选择 X 天」, 范围内没有非空事件文件时显示「没有可重建的本地数据」; 完成或失败后改为对应结果消息- 没有登录项错误时不渲染错误组@@ -1131,7 +1150,7 @@ App 再次成为 active 时, 也会刷新 Hook、同步、菜单栏额度、主通知与触觉反馈判定在 `CodexBar/Services/Notifications/`, 偏好类随其他设置类放在 `CodexBar/Services/Settings/`:- `NotificationSettings` (`Services/Settings/`): 总开关、五类通知子开关及各自的声音、任务触觉开关、低额度阈值 (5%/10%/25%, 默认 10%) 和长任务时长 (30s/1m/2m/5m, 默认 1m), 持久化到 UserDefaults; 负责系统授权请求、被拒状态镜像和设置页选项面板可展示状态-- `NotificationSoundOption`: 定义系统提示音、静音、14 个经典提示音和 17 个现代提示音;非静音选项统一生成 `UNNotificationSound` 并为设置页提供同源 WAV 试听资源+- `NotificationSoundOption`: 定义默认、静音、14 个经典提示音和 17 个现代提示音;非静音选项统一生成 `UNNotificationSound` 并为设置页提供同源 WAV 试听资源- `CodexCLINotificationSettings` (`Services/Settings/`): 通过 app-server 读取和写入用户级 `tui.notifications`; 支持解析布尔值与事件数组,缺失时按默认开启,写入后回读验证并把错误显示在通知选项行- `CodexNotificationService`: 集中判定、去重、调度与发送; 由 `CodexBarAppDelegate` 创建, 订阅 `CodexStatusViewModel.$snapshot`、`CodexActivityMonitor` live transition 与 `NSWorkspace.didWakeNotification`; 五类正式通知共用 `CodexNotificationContent` 文案工厂并按类型附加用户选择的声音,系统提交失败时重试一次,等待与完成 transition 还会按偏好请求 AppKit `.levelChange` 触觉反馈- `CodexActivityMonitor`: Hook 开启期间始终运行并维护并发任务;向 UI 发布快照,向提醒服务发布 live transition。`PermissionRequest` 先作为审批候选,只有同 turn 的 rollout reviewer 为 `user` 才确认等待;自动 reviewer 或未知 reviewer 保持运行。单个 live 批次先完整应用事件,再按任务键合并已确认的等待候选;只有批次结束后仍处于等待的任务会使用最终快照发布一次等待 transition,完成候选保持顺序并按 completion ID 做批内去重。通知与触觉开关不会停止活动监测@@ -1140,7 +1159,7 @@ App 再次成为 active 时, 也会刷新 Hook、同步、菜单栏额度、主活动并发以 session 为边界:不同 session 可以同时运行;同一 session 的 turn 按顺序执行。收到新的 `UserPromptSubmit` 时,monitor 会让该 session 中更早且缺少结束信号的 turn 立即退出活动列表,但保留为等待终态确认任务并触发一次即时 rollout 查询;5 秒内收到 Hook `Stop`、rollout `task_complete` 或 `turn_aborted` 时按真实终态归类,到期仍无终态才生成灰色最近终止记录。子 Agent 事件只能通过共享 session 关联父任务,早于当前顶层任务可信开始时间的事件会被当作上一 turn 的迟到事件忽略。已完成和已终止任务键分别保留 24 小时 tombstone,避免迟到事件恢复旧任务或误操作同 session 的新 turn。终止不会触发绿色完成状态、长任务通知或完成触觉反馈。Hook `Stop` 与 rollout `task_complete` 均视为完成信号,先到者生效,后到者按任务键和 session 回退键去重;重复完成不会覆盖首次确认结果,也不会缩短去重窗口或再次触发反馈。-设置页交互: 「系统通知」主开关行保留在设置窗口内, 子选项 (五类通知子开关与声音、任务触觉开关、Codex TUI 通知开关及两个阈值 Picker) 在主选项右侧的子面板中展开 (`NotificationOptionsPanelController`, 复用 SidePanelSupport 抽屉机制挂在设置窗口上, 内容用常驻 hosting controller + ObservableObject 驱动)。五类通知按需使用双行布局:第一行展示通知名称、可选阈值和开关,阈值 Picker 位于开关前;通知开启且依赖可用时,第二行展示「通知音效」、加宽的声音菜单和独立播放按钮,关闭时整行从布局移除。控制器订阅五类通知开关和 Hook 状态;入场期间暂停 fitting-size 更新,动画完成后重新测量,后续内容变化在 SwiftUI 完成布局后按 fitting size 动画调整面板高度并保持面板顶边位置,避免收起后残留空白。菜单顶层提供系统提示音和静音,其他声音按「经典提示音」和「现代提示音」子菜单分组。选择任意声音时立即试听,播放按钮可重复试听当前非静音选项,新的试听会停止上一段自定义声音;系统提示音使用 `NSSound.beep()`, 静音不播放预览且禁用播放按钮,其余声音优先播放 App 包内与正式通知同源的 WAV。选项依次排列为「任务完成通知」「任务等待通知」「额度预警通知」「额度重置通知」「重置临期通知」「任务触觉反馈」和「Codex TUI 通知」。主开关开启后仅在系统授权允许时展开, 首次授权场景会等待授权结果; 点击行内滑杆按钮可手动展开; 设置窗口 resign key/关闭、主开关关闭或授权变为被拒时自动收起。任务完成、任务等待与任务触觉子项在 Hook 未开启时显示为关闭并置灰, 不修改各自持久化偏好及声音, Hook 重新开启后恢复用户原选择。「Codex TUI 通知」与用户级 `[tui] notifications` 联动,面板打开时刷新,写入后回读验证;已有 CLI 会话需重启后生效。该项不服从 CodexBar 通知发送判定,也不修改顶层 `notify`。「主面板任务中心」沿用相同依赖语义;关闭只隐藏活动卡片和任务中心入口,不停止 Monitor、状态点、通知或触觉反馈。授权被拒的引导文案与"打开系统设置"按钮仍内联显示在主开关行下方, 插入提示时不触发设置项纵向动画。+设置页交互: 「系统通知」主开关行保留在设置窗口内, 子选项 (五类通知子开关与声音、任务触觉开关、Codex TUI 通知开关及两个阈值 Picker) 在主选项右侧的子面板中展开 (`NotificationOptionsPanelController`, 复用 SidePanelSupport 抽屉机制挂在设置窗口上, 内容用常驻 hosting controller + ObservableObject 驱动)。五类通知按需使用双行布局:第一行展示通知名称、可选阈值和开关,阈值 Picker 位于开关前;通知开启且依赖可用时,第二行展示「通知音效」、加宽的声音菜单和独立播放按钮,关闭时整行从布局移除。控制器订阅五类通知开关和 Hook 状态;入场期间暂停 fitting-size 更新,动画完成后重新测量,后续内容变化在 SwiftUI 完成布局后按 fitting size 动画调整面板高度并保持面板顶边位置,避免收起后残留空白。菜单顶层提供默认和静音,其他声音按「经典提示音」和「现代提示音」子菜单分组。选择任意声音时立即试听,播放按钮可重复试听当前非静音选项,新的试听会停止上一段自定义声音;默认使用 `NSSound.beep()`, 静音不播放预览且禁用播放按钮,其余声音优先播放 App 包内与正式通知同源的 WAV。选项依次排列为「任务完成通知」「任务等待通知」「额度预警通知」「额度重置通知」「重置临期通知」「任务触觉反馈」和「Codex TUI 通知」。主开关开启后仅在系统授权允许时展开, 首次授权场景会等待授权结果; 点击行内滑杆按钮可手动展开; 设置窗口 resign key/关闭、主开关关闭或授权变为被拒时自动收起。任务完成、任务等待与任务触觉子项在 Hook 未开启时显示为关闭并置灰, 不修改各自持久化偏好及声音, Hook 重新开启后恢复用户原选择。「Codex TUI 通知」与用户级 `[tui] notifications` 联动,面板打开时刷新,写入后回读验证;已有 CLI 会话需重启后生效。该项不服从 CodexBar 通知发送判定,也不修改顶层 `notify`。「主面板任务中心」沿用相同依赖语义;关闭只隐藏活动卡片和任务中心入口,不停止 Monitor、状态点、通知或触觉反馈。授权被拒的引导文案与"打开系统设置"按钮仍内联显示在主开关行下方, 插入提示时不触发设置项纵向动画。`NotificationOptionsView` 的两个实际行构建器保留 `@_optimize(none)`:Swift 6.3.3 在 `-O` 下优化这些包含原生 mini Switch 的动态布局时会漏绘开关 thumb。该约束只覆盖 `optionRow` 和带 accessory 的 `notificationOptionRow` 实现,其余通知视图与 Release target 继续使用正常优化;调整这两个构建器的编译属性后需要用 Release 产物人工检查开启状态的 thumb。@@ -1156,7 +1175,7 @@ App 再次成为 active 时, 也会刷新 Hook、同步、菜单栏额度、主额度低阈值、额度重置和重置机会通知只在系统成功接收后把去重键写入 UserDefaults (`Notification.sentKeys`),最多保留 300 条。键包含账号维度;额度重置窗口提供 `resetsAt` 时,去重键还包含该时间,缺失时仍发送通知但不生成周期去重键。额度重置观察状态和等待通知跟踪集合保存在当前进程内;通知不按预测时间调度,也不补发已错过的状态转换。可信额度快照持续推进重置观察状态,stale 快照不参与判定;窗口消失时移除对应观察状态,快照为 `nil` 时清空全部观察状态。Hook bootstrap 只恢复任务状态,不发布 transition,因此不产生历史任务通知或触觉反馈。-五类声音分别使用 `Notification.lowQuotaSound`、`Notification.quotaResetSound`、`Notification.longTaskSound`、`Notification.taskWaitingSound` 和 `Notification.creditExpirySound`。偏好缺失或保存值未知时回退到系统提示音,兼容升级前的用户数据;系统提示音提交 `.default`,静音提交 `nil`,其他选项提交 App 包根资源目录中的 `CodexBar-<Name>.wav`,由系统通知中心按系统授权、专注模式和通知设置决定是否实际播放。+五类声音分别使用 `Notification.lowQuotaSound`、`Notification.quotaResetSound`、`Notification.longTaskSound`、`Notification.taskWaitingSound` 和 `Notification.creditExpirySound`。偏好缺失或保存值未知时回退到默认,兼容升级前的用户数据;默认提交 `.default`,静音提交 `nil`,其他选项提交 App 包根资源目录中的 `CodexBar-<Name>.wav`,由系统通知中心按系统授权、专注模式和通知设置决定是否实际播放。「任务触觉反馈」使用 `Notification.taskHapticEnabled` 持久化,缺失时默认开启。等待批准和任意任务完成 transition 都启动一段触觉反馈任务:每 100 ms 请求一次 `.levelChange`,连续 10 次;新 transition 会取消并重启当前序列,开关关闭后会在下一脉冲前停止。触觉反馈不受长任务阈值与系统通知授权影响;App 内「系统通知」总开关关闭时不触发。`NSHapticFeedbackManager.defaultPerformer` 会按当前输入设备、辅助功能与系统偏好决定是否实际反馈及震感强弱。diff --git a/Docs/KeepAlive.md b/Docs/KeepAlive.mdnew file mode 100644index 0000000..44570b1--- /dev/null+++ b/Docs/KeepAlive.md@@ -0,0 +1,94 @@+# 阻止系统休眠++本文档记录设置页「阻止系统休眠」的状态口径、特权边界、恢复路径和打包要求。实现思路参考 [Nemuri](https://github.com/syfssb/nemuri) 的 `pmset disablesleep`、特权 helper 与哨兵/看门狗设计;CodexBar 直接复用自身 Hook 实时状态机,不引入第二套任务检测。++## 用户行为++- 开关默认关闭,偏好键为 `KeepAlive.isEnabled`。+- 功能依赖 Codex Hook;Hook 关闭后开关会自动关闭、清除开启偏好并恢复休眠,且在 Hook 关闭期间置灰不可操作。重新开启 Hook 后仍保持关闭,由用户决定是否再次开启。+- 首次开启通过 `SMAppService.daemon(plistName:)` 注册 LaunchDaemon。状态为 `requiresApproval` 时,设置页引导用户打开 macOS「登录项与扩展」。+- 只有 `CodexActivitySnapshot.runningTasks` 非空时,才同时把 `SleepDisabled` 设为 `1` 并持有 `PreventUserIdleSystemSleep` assertion,覆盖空闲、合盖和手动系统休眠。`waitingTasks`、最近完成、最近终止和空闲都恢复休眠。+- 并发任务采用 any-running 语义:只要还有一个运行任务就继续保活。+- 用户可选择最长防休眠期限:1、2、4、8、12、24 小时或无限制,默认 12 小时,偏好键为 `KeepAlive.maximumContinuousDurationSeconds`。有限期限只维护一个计时起点,每个新运行任务第一次出现在实时快照中,或同一任务从 `waitingApproval` 恢复为 `running` 时,都把共享起点更新为当前时间;无限制不创建到期计时器。+- 达到期限后立即恢复任务开始前的休眠设置;即使旧任务仍在运行,也不会因 App 激活、设置刷新或同一运行阶段内的普通 Hook 活动而重置期限。等待批准后恢复运行属于新的运行阶段,会清除到期状态并获得完整的新期限;多任务场景下,这次恢复也会更新所有运行任务共享的截止时间。到期后改为无限制,或改为按当前起点计算后仍未到期的更长期限,会清除到期状态并继续当前周期。每次 App 成功恢复时,先由 helper 还原 `SleepDisabled`,再释放空闲休眠 assertion,让 macOS 根据当前空闲计时、用户活动、其他 assertion 和电源策略立即重新评估是否应休眠。App 不自行推算空闲期限,也不在开盖时无条件强制休眠。如果 helper 确认恢复结果为 `SleepDisabled=0`,且系统同时确认已经合盖并且合盖应触发休眠,CodexBar 还会主动请求系统休眠。该流程统一覆盖进入等待批准、任务完成或终止、没有活动任务、关闭功能和达到期限等恢复路径,无需记录本轮是否出现过合盖休眠意图。外接显示器合盖模式或原始设置本来就是禁止休眠时不会强制休眠。所有运行和等待任务都从实时快照消失或用户关闭再开启功能也会重置计时状态。++`PermissionRequest` 本身不是等待用户。`CodexActivityMonitor` 只有在 rollout 确认同 turn 的 `approvals_reviewer == user` 后才把任务移入 `waitingApproval`;`auto_review`、兼容的自动 reviewer 或尚未确认 reviewer 时仍保持运行。因此防休眠与 UI、通知使用同一份已经归一的状态,不直接解释 Hook 事件。++## 为什么不用 caffeinate++`ProcessInfo.beginActivity`、IOKit idle sleep assertion 和 `/usr/bin/caffeinate` 适合阻止空闲休眠,但不能可靠覆盖 MacBook 合盖触发的休眠。合盖继续运行需要系统级 `/usr/bin/pmset -a disablesleep 1`,写入该设置需要 root 权限。CodexBar 同时使用 idle sleep assertion,不是因为 `pmset` 无法禁止空闲休眠,而是为了在 helper 恢复全局设置后通过释放 assertion 触发 macOS 自己重新评估已累计的空闲状态。++CodexBar 使用 macOS 15 可用的 ServiceManagement 新 API。LaunchDaemon plist 位于 App 包的 `Contents/Library/LaunchDaemons/`,helper 位于 `Contents/Resources/`;主 App 不执行 `sudo`,也不持有任意 root 命令能力。++## 组件边界++| 组件 | 职责 |+| -------------------------------- | ------------------------------------------------------------------------------- |+| `KeepAliveController` | MainActor 上订阅活动快照、保存偏好、刷新 `SMAppService.Status`、管理 XPC 和重试 |+| `SystemSleepService` | 持有/释放空闲休眠 assertion;恢复后读取当前合盖状态,并在满足条件时请求系统休眠 |+| `Shared/CodexBarHelperXPC.swift` | 从当前 bundle identifier 派生 Mach service 名,并声明恢复时限和唯一 XPC 方法 |+| `CodexBarHelper` | root 下串行执行固定的 `pmset` 命令、维护哨兵、看门狗和信号恢复 |+| LaunchDaemon plist | 声明 `BundleProgram`、Mach service、RunAtLoad 和 KeepAlive |++helper 的 XPC listener 使用代码签名 requirement。它从自身签名动态取得 Team ID,并由 helper identifier 推导对应的 App identifier,只接受两者都匹配的 Apple 签名客户端。对外接口只有:++```text+setSleepDisabled(Bool)+```++helper 不接受命令、路径或环境变量参数,不访问网络,不读取 Codex 配置、事件或会话内容。唯一写入目录是 root-owned `/Library/Application Support/CodexBar/`;哨兵文件名为当前 Mach service 名加 `.state`,因此 Release 使用 `app.zabrian.codexbar.helper.state`,Debug 使用 `app.zabrian.codexbar.debug.helper.state`。++helper 在恢复请求的 XPC reply 中同时返回成功恢复后的 `SleepDisabled` 值。App 收到成功 reply 后释放 idle sleep assertion,无论开盖还是合盖,都由 macOS 先按当前状态重新评估空闲休眠。App 只有确认 `SleepDisabled` 为 `0`,并重新读取到 `AppleClamshellState=true` 与 `AppleClamshellCausesSleep=true` 时才额外主动请求系统休眠。没有哨兵、读取失败、恢复失败或系统状态无法确认都按保守结果处理,不会误触发主动休眠。++## 原始状态与恢复++第一次请求关闭休眠时,helper 先用 `pmset -g` 读取 `SleepDisabled`;macOS 未输出该字段时按默认值 `0` 处理。helper 把原始 `0/1` 写入权限为 `0600` 的哨兵,再执行 `pmset -a disablesleep 1`。恢复时写回哨兵保存的原值,成功后才删除哨兵;因此任务开始前已经由用户或其他工具关闭休眠时,CodexBar 不会擅自改成开启休眠。++恢复路径:++1. 最后一个运行任务进入等待、完成、终止或消失时,App 立即请求恢复;等待任务恢复运行时把恢复时刻设为新的共享计时起点,并获得完整的新期限。+2. 达到从最近任务启动起计算的最长防休眠期限时请求恢复。新的运行任务、等待任务恢复运行、所有运行和等待任务都消失后再次出现任务,或用户关闭再开启功能时会开始新一轮。用户改为无限制,或改为按当前起点计算后仍未到期的更长期限,也会继续当前周期。+3. 关闭功能或正常退出 App 时在可用连接上请求恢复;连接已经断开时释放 App 持有的 assertion,并由下一条兜底恢复全局设置。+4. 最后一个 XPC 连接断开且哨兵存在时,helper 等待 15 秒后恢复;App 快速重连会取消该次看门狗。+5. helper 每 60 秒检查一次「没有连接、没有看门狗、仍有哨兵」,用于重试瞬时 `pmset` 失败。+6. helper 启动发现哨兵,或收到 `SIGTERM` / `SIGINT` 时,立即尝试恢复。++helper 的所有连接状态、命令与 timer 都在同一串行队列上修改。App 侧为每次 XPC 请求分配 generation,迟到回调不能覆盖后续任务状态;连接中断且目标状态不变时会延迟重连。若功能在断线重连等待期间关闭,App 会取消重连并释放本地 idle sleep assertion,全局 `SleepDisabled` 由 helper 的 15 秒断线看门狗恢复。凡是 App 收到成功的恢复 reply,都会在 `SleepDisabled` 已经还原后释放 idle sleep assertion,由系统重新评估空闲休眠,再检查恢复值与当前合盖状态,并在确认当前合盖应休眠时调用 `IOPMSleepSystem`;helper 在 App 已退出时执行的看门狗或启动恢复仍只负责恢复原设置。App 进程退出时其 assertion 会由系统自动释放,但异常退出路径不保证与 helper 的延迟恢复形成和正常 reply 相同的顺序。++## 打包与发布++Xcode 工程包含 `CodexBar` 和 `CodexBarHelper` 两个 target。主 target 显式依赖 helper,并在构建阶段:++- 把 helper 复制和签名到 `Contents/Resources/CodexBarHelper`。+- Debug 使用 `app.zabrian.codexbar.debug`,并只嵌入 `app.zabrian.codexbar.debug.helper.plist`。+- Release 使用 `app.zabrian.codexbar`,并只嵌入 `app.zabrian.codexbar.helper.plist`。++Debug 与 Release 使用独立的 App bundle identifier、helper bundle identifier、Mach service、LaunchDaemon label 和哨兵文件,避免开发授权与注册状态相互影响。App 从自身 bundle identifier 加 `.helper` 得到 Mach service 名,helper 直接使用自身 bundle identifier,LaunchDaemon plist 名和哨兵文件名再由该 service 名派生;helper target 的生成式 Info.plist 嵌入可执行文件,保证独立运行时也能取得自身 identifier。helper 启动时从自身代码签名读取 Team ID,并从自身 identifier 的 `.helper` 后缀推导对应的 App identifier,以生成 XPC 客户端签名要求,不在 Swift 源码中硬编码开发团队或 App identifier。由于 `pmset` 修改的是整台 Mac 的全局状态,不要同时运行 Debug 与 Release App 的防休眠功能。++Apple 要求包含 `SMAppService` LaunchDaemon 的分发 App 正确签名和公证。日常 `xcodebuild ... build` 可验证编译、bundle 结构和开发签名;完整 Developer ID 导出和公证仍走 `Scripts/build.sh`。++App 按固定顺序计算嵌入的 helper 可执行文件与当前构建配置 LaunchDaemon plist 的内容 SHA-256,并记录已注册服务对应的指纹。每次启动都会检查已注册或等待批准的服务,即使「阻止系统休眠」当前关闭;任一文件内容与记录不一致时,App 会等待 `SMAppService.unregister` 完成后重新注册,使服务使用当前 App 包内的 helper 和 plist。功能关闭且服务从未注册时不会主动注册;只有 App 本体变化而这两个嵌入文件内容不变时也不会重复注册。macOS 可能在注销刚完成时短暂拒绝重新注册;App 会先让出一次主线程事件循环,并只对 `SMAppServiceErrorDomain Code=1` 的 `Operation not permitted` 做 0.5、1、2 秒有限退避重试,其他签名、授权或配置错误立即返回。++`KeepAliveController.stop()` 先把控制器标记为停止,再取消 Helper 注册任务、XPC 重试和最长时限任务。Helper 注册任务会在注销前和注销完成后检查取消状态;只有控制器仍在运行且任务未取消时,才提交 Helper 状态、打开系统设置或重新收敛防休眠。`shouldDisableSleep` 同时要求控制器处于运行状态,因此停止后的异步结果不能重新关闭系统休眠。如果停止发生在旧 Helper 已注销而新 Helper 尚未注册时,下次 App 启动会根据当前偏好和 `SMAppService.Status` 决定是否重新注册。++开发机需要注销 Debug 和 Release 遗留的 KeepAlive 服务时,先退出所有 CodexBar 实例,再运行 `Scripts/cleanup.swift`。该独立 Swift 脚本为两个构建身份分别创建临时签名 App,并通过 `SMAppService.unregister()` 定向注销 KeepAlive LaunchDaemon;它不会调用 `sfltool resetbtm`,也不会重置其他 App 的后台项目。每个清理目标优先使用对应 App 包内的 Helper;目标包缺少可执行 Helper 时,只回退到同一 Debug 或 Release 构建配置的 Xcode 产物,不跨配置复用 Helper。可先使用 `--dry-run` 检查目标,使用 `--check` 只验证临时 App 的编译与签名,或使用 `--debug-only` / `--release-only` 只处理一个构建身份。清理后对应的 `KeepAlive.isEnabled` 偏好会被设为关闭,避免下次启动立即重新注册。++`SMAppService.unregister()` 只保证服务不再加载。macOS 的 Background Task Management 数据库可能继续保留已禁用的 App/Helper 历史记录,并在后续系统维护时清除,因此「App 后台活动」中可能暂时仍显示 CodexBar。系统没有公开的按 bundle identifier 立即删除单条 BTM 历史记录的接口;`sudo sfltool resetbtm` 会重置所有第三方 App 的后台项目与授权,不属于本脚本的定向清理范围。++## 手动验收++1. 把签名、公证后的 App 放入 `/Applications`,开启 Codex Hook。+2. 开启「阻止系统休眠」,按提示允许 CodexBar 后台项目。+3. 启动任务,确认设置行显示「当前禁止系统休眠」,`pmset -g` 显示 `SleepDisabled 1`。+4. 让任务进入等待用户批准,确认恢复为任务开始前的值;开盖时将系统空闲休眠设为较短时间,等待空闲期限先在任务运行期间经过,再确认进入等待后释放 assertion、由 macOS 按当前策略休眠;有其他有效 assertion 或近期用户活动时不应被 CodexBar 强制休眠。批准后继续运行时再次关闭休眠,并确认最长防休眠期限从恢复时重新完整计算。+5. 同时运行两个任务,确认其中一个等待或完成时不会提前恢复,最后一个停止运行后才恢复。+6. 选择较短期限并保持任务运行至到期,确认设置页提示已达到上限、系统休眠恢复;激活 App、刷新设置或让同一任务产生新 Hook 活动后仍不重新关闭休眠。+7. 分别验证等待、完成、终止、空闲、关闭功能和到期行为:开盖时由 macOS 按当前空闲计时、其他 assertion 与电源策略决定是否休眠;普通合盖且没有外接显示器时应在恢复后进入休眠;合盖连接外接显示器并处于正常外接屏工作模式时只恢复设置、不主动休眠。+8. 在开始任务前手动设置 `SleepDisabled=1`,确认到期时恢复原值且不主动休眠;结束后自行恢复测试机原有设置。+9. 在旧任务仍运行且已经到期时启动新任务,确认立即重新关闭系统休眠并从新任务启动时开始完整的新周期;另行确认到期前启动新任务,以及任一等待任务获批恢复运行,都会把共享截止时间更新为对应启动或恢复时刻加完整期限。+10. 运行期间关闭 Codex Hook,确认防休眠开关自动关闭并置灰、系统休眠恢复;重新开启 Hook 后确认防休眠开关仍保持关闭。+11. 保持服务已注册,分别替换 helper 可执行文件内容和当前构建配置的 LaunchDaemon plist 内容,确认下次启动都会刷新注册;关闭「阻止系统休眠」后重复验证,确认仍刷新已注册服务但不关闭系统休眠。仅替换 App 本体且保持这两个文件内容不变时,确认不会重复注册。+12. 运行期间正常退出与强制终止 CodexBar,确认最多经过看门狗宽限后恢复;另在 helper 刷新注册期间退出,确认停止后不再回写注册状态或重新请求防休眠,并在下次启动时按当前偏好和 `SMAppService.Status` 收敛。+13. 运行期间终止 helper,确认 launchd 重启后通过哨兵恢复,再由仍活跃的 App 按快照重新收敛。++不要在密闭包内执行合盖验收。该功能会增加耗电和发热,当前不包含低电量自动放行策略。diff --git a/Docs/UserGuide.md b/Docs/UserGuide.mdindex df244af..2f105a3 100644--- a/Docs/UserGuide.md+++ b/Docs/UserGuide.md@@ -36,7 +36,7 @@ CodexBar 是纯菜单栏 App,不显示 Dock 图标,也没有传统主窗口3. 根据需要开启「开机自动启动」和「自动检查更新」。4. 如果希望在菜单栏直接看到剩余额度,开启「菜单栏额度指示」并选择额度窗口。5. 如果希望查看工作流统计、实时任务或任务提醒,开启「CodexBar Hook」。-6. 开启 Hook 后,可继续开启「主面板任务中心」和「跨设备同步」。+6. 开启 Hook 后,可继续开启「主面板任务中心」「阻止系统休眠」和「跨设备同步」。7. 如果希望接收提醒,开启「系统通知」,允许 macOS 通知权限,再打开右侧的通知选项。如果第一步显示「未登录」或「初始化失败」,先阅读[账号状态与数据刷新](#4-账号状态与数据刷新)。@@ -75,6 +75,7 @@ CodexBar 是纯菜单栏 App,不显示 Dock 图标,也没有传统主窗口| 工作流统计 | 开启「CodexBar Hook」 || 活动卡片与任务中心 | 开启「CodexBar Hook」和「主面板任务中心」 || 任务状态点 | 开启 Hook,且当前主数据可用 |+| 阻止系统休眠 | 开启 Hook、对应开关,并允许 CodexBar 后台项目 || 跨设备同步 | 开启 Hook 和「跨设备同步」,并登录可用的 iCloud 账号 || 额度类通知 | 开启「系统通知」、macOS 通知权限和对应通知选项 || 任务类通知 | 在通知条件基础上额外开启 Hook |@@ -289,6 +290,28 @@ Token 用量和 Hook 工作流统计来自不同功能。请确认当天使用 C「主面板任务中心」依赖 Hook。Hook 关闭时,该开关会显示为关闭并置灰;重新开启 Hook 后会恢复此前选择。+### 防止任务因系统休眠中断++开启设置中的「阻止系统休眠」后,CodexBar 会在至少一个任务真正运行时同时阻止空闲、合盖和手动系统休眠,因此 MacBook 合盖后任务仍可继续。首次开启需要在 macOS「登录项与扩展」中允许 CodexBar 后台运行;设置行出现提示时点击「打开系统设置」,允许后回到 CodexBar。++开启后可选择最长防休眠期限:1、2、4、8、12、24 小时或无限制,默认 12 小时。CodexBar 只维护一个计时周期;每次启动新的运行任务,或同一任务等待用户批准后恢复运行,都会从这次启动或恢复的时间重新计时。同一任务继续产生普通 Hook 活动不会顺延,无限制不会自动到期。进入等待批准、任务完成或终止、没有活动任务、关闭功能以及达到有限期限时,CodexBar 都会恢复任务开始前的休眠设置,并释放运行期间持有的空闲休眠 assertion。macOS 随即根据当前空闲时间、用户活动、其他 App 的 assertion 和系统电源策略重新判断是否应休眠,所以开盖状态如果已经满足空闲休眠条件也可以立即进入休眠;CodexBar 不会绕过其他系统条件强制休眠。普通合盖且系统确认此次合盖应休眠时,CodexBar 还会主动请求系统休眠;外接显示器合盖工作或电脑原本就全局禁止休眠时不会强制休眠。即使旧任务仍在运行,之后启动新任务或等待任务获批恢复也会立即重新阻止休眠并开始完整的新周期。到期后改为无限制,或选择按当前起点计算后仍未到期的更长期限,也会继续当前周期。++该选项依赖 Codex Hook。关闭 Hook 时,防休眠选项会自动关闭并置灰,同时恢复任务开始前的系统休眠设置;重新开启 Hook 后不会自动恢复该选项,需要手动再次开启。++这个开关使用与活动卡片相同的任务状态:++| 实时状态 | 是否阻止休眠 |+| -------------------------- | ------------ |+| 至少一个任务正在运行 | 是 |+| 所有任务都在等待用户批准 | 否 |+| 任务全部完成或终止 | 否 |+| 已达到最近任务的防休眠上限 | 否 |+| Hook 关闭或没有活动任务 | 否 |++等待批准只指 Codex 已确认需要你处理的请求;由自动 reviewer 继续处理的权限请求仍属于运行中。多个并发任务里只要还有一个运行任务,CodexBar 就会继续阻止休眠。任务不再运行或达到期限后会恢复任务开始前的系统休眠设置;新的运行任务以及同一任务从等待恢复都会更新所有运行任务共享的计时起点,并获得完整的新期限。++合盖运行会持续耗电并产生热量。请保持 Mac 通风,不要把仍在运行任务的电脑放进密闭包中;电量不足时请主动停止任务或关闭该选项。+### 活动卡片图标| 图标与颜色 | 状态 | 含义 |@@ -537,19 +560,20 @@ CodexBar 系统通知都可以独立选择声音,默认使用 macOS 系统通### 设置项说明-| 设置项 | 图标 | 作用 | 常见问题 |-| -------------- | -------- | ---------------------------------- | ------------------------------------------------------- |-| 开机自动启动 | 电源 | 登录 macOS 后自动运行 CodexBar | 设置失败时下方会显示错误;移动 App 后建议关闭再开启一次 |-| 自动检查更新 | 循环箭头 | 定期检查 CodexBar 新版本 | 关闭后仍可手动点击「检查更新」 |-| 菜单栏额度指示 | 仪表 | 在菜单栏显示所选额度窗口 | 没有对应额度数据时自动隐藏 |-| 设置快捷键 | 键盘 | 设置全局打开或关闭菜单面板的快捷键 | 至少需要两个修饰键 |-| CodexBar Hook | 链接 | 开启工作流统计和实时任务能力 | 失败时根据该行下方提示处理 |-| 主面板任务中心 | 列表 | 在主面板显示活动卡片和任务中心入口 | 需要 Hook;Hook 关闭时置灰 |-| 系统通知 | 铃铛 | 控制 CodexBar 通知与任务触觉总开关 | 首次开启需要 macOS 授权 |-| 跨设备同步 | iCloud | 合并多台 Mac 的每日工作流统计 | 需要 Hook 和可用 iCloud 账号 |-| 重建数据 | 圆形箭头 | 重新生成所选日期的本机工作流统计 | 需要所选日期仍有本机记录 |-| CodexBar 版本 | 信息圆圈 | 查看当前版本与更新状态 | 有更新时显示下载按钮 |-| Codex 版本 | 数字圆圈 | 查看已安装 Codex 及当前使用来源 | 点击路径可以复制 |+| 设置项 | 图标 | 作用 | 常见问题 |+| -------------- | -------- | ---------------------------------- | ----------------------------------------------------------- |+| 开机自动启动 | 电源 | 登录 macOS 后自动运行 CodexBar | 设置失败时下方会显示错误;移动 App 后建议关闭再开启一次 |+| 自动检查更新 | 循环箭头 | 定期检查 CodexBar 新版本 | 关闭后仍可手动点击「检查更新」 |+| 菜单栏额度指示 | 仪表 | 在菜单栏显示所选额度窗口 | 没有对应额度数据时自动隐藏 |+| 设置快捷键 | 键盘 | 设置全局打开或关闭菜单面板的快捷键 | 至少需要两个修饰键 |+| CodexBar Hook | 链接 | 开启工作流统计和实时任务能力 | 失败时根据该行下方提示处理 |+| 主面板任务中心 | 列表 | 在主面板显示活动卡片和任务中心入口 | 需要 Hook;Hook 关闭时置灰 |+| 系统通知 | 铃铛 | 控制 CodexBar 通知与任务触觉总开关 | 首次开启需要 macOS 授权 |+| 跨设备同步 | iCloud | 合并多台 Mac 的每日工作流统计 | 需要 Hook 和可用 iCloud 账号 |+| 阻止系统休眠 | 月亮 | 仅在任务真正运行时阻止系统休眠 | 需要 Hook 和 macOS 后台项目授权;关闭 Hook 时自动关闭并置灰 |+| 重建数据 | 圆形箭头 | 重新生成所选日期的本机工作流统计 | 需要所选日期仍有本机记录 |+| Codex 版本 | 数字圆圈 | 查看已安装 Codex 及当前使用来源 | 点击路径可以复制 |+| CodexBar 版本 | 信息圆圈 | 查看当前版本与更新状态 | 有更新时显示下载按钮 |### 设置全局快捷键@@ -643,6 +667,7 @@ CodexBar 系统通知都可以独立选择声音,默认使用 macOS 系统通| 活动卡片没有出现 | 同时开启 Hook 和「主面板任务中心」 || 点击活动卡片没有反应 | 当前没有可展示任务,或主数据尚未加载 || 任务一直显示运行中 | 任务可能没有正常留下结束状态,等待后续活动或自动过期 |+| 合盖后任务仍然停止 | 检查防休眠开关、Hook 状态和 CodexBar 后台项目授权 || 跨设备同步开关置灰 | 先开启 Hook,并确认 iCloud 可用 || iCloud 图标带感叹号 | 悬停查看网络、账号或服务错误 || 收不到系统通知 | 检查总开关、macOS 权限、子选项和 Hook 依赖 |@@ -660,6 +685,7 @@ CodexBar 以本机处理为主:- 账号、额度和 Token 用量在本机读取和展示。- Hook 原始记录保存在当前 Mac,默认保留最近 210 天。- 实时任务只在当前 App 运行期间用于状态展示。+- 防休眠 helper 只在本机切换系统休眠设置并维护恢复哨兵,不访问网络或任务内容。- 菜单面板只显示项目名称,不显示完整工作目录、会话编号或轮次编号。- CodexBar 不展示提示词、回复、推理内容、工具内容或审批内容。diff --git a/README.md b/README.mdindex 0a1c42b..0bb6156 100644--- a/README.md+++ b/README.md@@ -13,6 +13,7 @@ CodexBar 是一款无 Dock 图标的 macOS 菜单栏应用。无需打开 Codex- **额度状态**:查看各时间窗口的剩余额度、重置时间和手动重置机会- **Token 热力图**:用近 30 周日历热力图回顾每日 Token 用量- **实时任务**:开启 Codex Hook 后,查看运行中、等待批准、最近完成和终止的任务+- **阻止系统休眠**:可选仅在任务真正运行时阻止 macOS 的空闲、合盖和手动休眠,可设置从最近任务启动或获批恢复起的最长期限,并在等待批准、任务结束或到期后自动恢复;恢复后会立即让系统重新评估是否已经满足休眠条件- **工作流统计**:按日期查看会话、对话轮次、工具调用、权限请求、上下文压缩和子 Agent 等数据- **及时提醒**:可选额度告急、额度恢复、等待批准、长任务完成通知与触觉反馈,各类通知声音可独立选择- **跨设备汇总**:通过可选的 iCloud 私有数据库同步每日聚合数据@@ -36,6 +37,8 @@ brew install --cask bob-zebedy/tap/codexbar更多使用方法见[使用指南与常见问题](Docs/UserGuide.md)+「阻止系统休眠」需要 Codex Hook,并在首次开启时要求 macOS 允许 CodexBar 后台项目;关闭 Hook 会自动关闭并置灰该选项。最长防休眠期限可选 1、2、4、8、12、24 小时或无限制,默认 12 小时;新任务启动以及同一任务等待用户批准后恢复运行都会重新计时,普通 Hook 活动不会续期。任务运行时,CodexBar 同时关闭系统休眠并持有阻止空闲休眠的系统 assertion。每次恢复时先还原任务开始前的系统设置,再释放 assertion,让 macOS 按当前空闲计时、其他 assertion 和电源策略立即重新判断是否应休眠;普通合盖且系统确认合盖应休眠时还会主动请求休眠。电脑原本就全局禁止休眠或处于外接显示器合盖工作模式时不会强制休眠。合盖运行会增加耗电和发热,请确保 Mac 通风良好,不要在密闭包内使用。+## 许可证本项目采用 [GNU General Public License v3.0](LICENSE)diff --git a/Scripts/cleanup.swift b/Scripts/cleanup.swiftnew file mode 100755index 0000000..0b0f0ed--- /dev/null+++ b/Scripts/cleanup.swift@@ -0,0 +1,566 @@+#!/usr/bin/env swift++import Darwin+import Foundation+import ServiceManagement++private enum CleanupBuildConfiguration: String {+ case debug = "Debug"+ case release = "Release"+}++private struct CleanupTarget {+ let appURL: URL+ let bundleIdentifier: String+ let buildConfiguration: CleanupBuildConfiguration++ var plistName: String {+ serviceLabel + ".plist"+ }++ var serviceLabel: String {+ bundleIdentifier + ".helper"+ }+}++private struct CommandOutput {+ let status: Int32+ let text: String+}++private enum CleanupError: LocalizedError {+ case message(String)+ case commandFailed(executable: String, arguments: [String], status: Int32, output: String)+ case codeSigningValidationFailed(String)++ var errorDescription: String? {+ switch self {+ case let .message(message):+ message+ case let .commandFailed(executable, arguments, status, output):+ "命令执行失败, status=\(status), command=\(([executable] + arguments).joined(separator: " "))\n\(output)"+ case let .codeSigningValidationFailed(reason):+ "签名校验失败, \(reason)"+ }+ }+}++private struct CleanupOptions {+ var releaseAppURL = URL(fileURLWithPath: "/Applications/CodexBar.app")+ var debugAppURL: URL?+ var cleansRelease = true+ var cleansDebug = true+ var signingIdentity = ProcessInfo.processInfo.environment["CODEXBAR_CLEANUP_SIGN_IDENTITY"]+ ?? "Apple Development"+ var isDryRun = false+ var isCheckOnly = false+}++private final class KeepAliveCleanupCommand {+ private let fileManager = FileManager.default+ private let scriptURL = URL(fileURLWithPath: #filePath).standardizedFileURL++ private var projectURL: URL {+ scriptURL.deletingLastPathComponent().deletingLastPathComponent()+ }++ 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)")+ }++ guard !targets.isEmpty else {+ print("清理完成: 没有可用目标")+ return+ }++ if options.isDryRun {+ return+ }++ if !options.isCheckOnly, isCodexBarRunning() {+ throw CleanupError.message("CodexBar 仍在运行")+ }++ let temporaryRoot = fileManager.temporaryDirectory+ .appending(path: "codexbar-keep-alive-cleanup.\(UUID().uuidString)", directoryHint: .isDirectory)+ try fileManager.createDirectory(at: temporaryRoot, withIntermediateDirectories: true)+ defer { try? fileManager.removeItem(at: temporaryRoot) }++ let cleanupExecutableURL = temporaryRoot.appending(path: "KeepAliveCleanup")+ try runChecked(+ "/usr/bin/xcrun",+ ["swiftc", scriptURL.path, "-o", cleanupExecutableURL.path]+ )++ for target in targets {+ let helperSourceURL = try resolveHelperSourceURL(for: target)+ try prepareAndRun(+ target: target,+ helperSourceURL: helperSourceURL,+ cleanupExecutableURL: cleanupExecutableURL,+ temporaryRoot: temporaryRoot,+ signingIdentity: options.signingIdentity,+ 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+ case "--check":+ options.isCheckOnly = true+ case "-h", "--help":+ printUsage()+ Darwin.exit(EXIT_SUCCESS)+ default:+ throw CleanupError.message("未知选项, value=\(arguments[index])")+ }+ index += 1+ }++ return options+ }++ private func printUsage() {+ print(+ """+ usage: Scripts/cleanup.swift [options]++ 仅注销 CodexBar 的 Release 和 Debug KeepAlive LaunchDaemon++ Options:+ --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 实例+ """+ )+ }++ 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+ )+ )+ }+ if options.cleansDebug {+ guard let debugAppURL = options.debugAppURL else {+ throw CleanupError.message("无法定位 Xcode Debug App")+ }+ targets.append(+ CleanupTarget(+ appURL: debugAppURL,+ bundleIdentifier: "app.zabrian.codexbar.debug",+ buildConfiguration: .debug+ )+ )+ }+ return targets+ }++ private func resolveBuiltAppURL(configuration: CleanupBuildConfiguration) throws -> URL {+ let output = try runChecked(+ "/usr/bin/xcodebuild",+ [+ "-project", projectURL.appending(path: "CodexBar.xcodeproj").path,+ "-scheme", "CodexBar",+ "-configuration", configuration.rawValue,+ "-destination", "generic/platform=macOS",+ "-showBuildSettings"+ ],+ capturesOutput: true+ ).text++ guard let targetBuildDirectory = buildSetting("TARGET_BUILD_DIR", in: output),+ let wrapperName = buildSetting("WRAPPER_NAME", in: output) else {+ throw CleanupError.message(+ "无法从 Xcode 构建设置定位 App, configuration=\(configuration.rawValue)"+ )+ }+ return URL(fileURLWithPath: targetBuildDirectory).appending(path: wrapperName)+ }++ private func buildSetting(_ name: String, in output: String) -> String? {+ let prefix = "\(name) = "+ return output.split(whereSeparator: \.isNewline)+ .lazy+ .map { $0.trimmingCharacters(in: .whitespaces) }+ .first { $0.hasPrefix(prefix) }+ .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) {+ return bundledHelperURL+ }++ let builtAppURL = try resolveBuiltAppURL(configuration: target.buildConfiguration)+ let builtHelperURL = helperURL(in: builtAppURL)+ guard fileManager.isExecutableFile(atPath: builtHelperURL.path) else {+ throw CleanupError.message(+ "CodexBarHelper 未构建, configuration=\(target.buildConfiguration.rawValue)"+ )+ }+ return builtHelperURL+ }++ private func helperURL(in appURL: URL) -> URL {+ appURL.appending(path: "Contents/Resources/CodexBarHelper")+ }++ private func isCodexBarRunning() -> Bool {+ (try? run("/usr/bin/pgrep", ["-x", "CodexBar"], capturesOutput: true).status) == 0+ }++ private func prepareAndRun(+ target: CleanupTarget,+ helperSourceURL: URL,+ cleanupExecutableURL: URL,+ temporaryRoot: URL,+ signingIdentity: String,+ isCheckOnly: Bool+ ) throws {+ let teamIdentifier = try signingTeamIdentifier(for: target.appURL)+ let cleanupAppURL = temporaryRoot+ .appending(path: "\(target.bundleIdentifier).app", directoryHint: .isDirectory)+ let contentsURL = cleanupAppURL.appending(path: "Contents", directoryHint: .isDirectory)+ let macOSURL = contentsURL.appending(path: "MacOS", directoryHint: .isDirectory)+ let daemonsURL = contentsURL.appending(path: "Library/LaunchDaemons", directoryHint: .isDirectory)+ let resourcesURL = contentsURL.appending(path: "Resources", directoryHint: .isDirectory)++ for directory in [macOSURL, daemonsURL, resourcesURL] {+ try fileManager.createDirectory(at: directory, withIntermediateDirectories: true)+ }++ var info = try propertyListDictionary(at: target.appURL.appending(path: "Contents/Info.plist"))+ info["CFBundleExecutable"] = "KeepAliveCleanup"+ info["CFBundleName"] = "CodexBar KeepAlive Cleanup"+ try writePropertyList(info, to: contentsURL.appending(path: "Info.plist"))++ let bundledPlistURL = target.appURL+ .appending(path: "Contents/Library/LaunchDaemons")+ .appending(path: target.plistName)+ let sourcePlistURL = fileManager.fileExists(atPath: bundledPlistURL.path)+ ? bundledPlistURL+ : projectURL.appending(path: "CodexBarHelper").appending(path: target.plistName)+ guard fileManager.fileExists(atPath: sourcePlistURL.path) else {+ throw CleanupError.message("LaunchDaemon 配置缺失, name=\(target.plistName)")+ }++ let destinationPlistURL = daemonsURL.appending(path: target.plistName)+ let destinationHelperURL = resourcesURL.appending(path: "CodexBarHelper")+ let destinationExecutableURL = macOSURL.appending(path: "KeepAliveCleanup")+ try fileManager.copyItem(at: sourcePlistURL, to: destinationPlistURL)+ try fileManager.copyItem(at: helperSourceURL, to: destinationHelperURL)+ try fileManager.copyItem(at: cleanupExecutableURL, to: destinationExecutableURL)+ try fileManager.setAttributes([.posixPermissions: 0o755], ofItemAtPath: destinationHelperURL.path)+ try fileManager.setAttributes([.posixPermissions: 0o755], ofItemAtPath: destinationExecutableURL.path)++ try runCodeSigningChecked(+ [+ "--force",+ "--identifier", target.serviceLabel,+ "--options", "runtime",+ "--timestamp=none",+ "--sign", signingIdentity,+ destinationHelperURL.path+ ],+ failureReason: "Helper 签名失败"+ )+ try runCodeSigningChecked(+ [+ "--force",+ "--options", "runtime",+ "--timestamp=none",+ "--sign", signingIdentity,+ cleanupAppURL.path+ ],+ failureReason: "清理 App 签名失败"+ )++ let cleanupTeamIdentifier = try signingTeamIdentifier(for: cleanupAppURL)+ guard cleanupTeamIdentifier == teamIdentifier else {+ throw CleanupError.codeSigningValidationFailed(+ "Team ID 不匹配, actual=\(cleanupTeamIdentifier), expected=\(teamIdentifier)"+ )+ }+ try runCodeSigningChecked(+ ["--verify", "--strict", "--verbose=2", cleanupAppURL.path],+ failureReason: "清理 App 验证失败"+ )++ if isCheckOnly {+ print("目标验证完成: bundle=\(target.bundleIdentifier)")+ return+ }++ try runChecked(destinationExecutableURL.path, ["--unregister-child", target.plistName])+ try runChecked(+ "/usr/bin/defaults",+ ["write", target.bundleIdentifier, "KeepAlive.isEnabled", "-bool", "false"]+ )+ _ = try run(+ "/usr/bin/defaults",+ ["delete", target.bundleIdentifier, "KeepAlive.helperRegistrationFingerprint"],+ capturesOutput: true+ )++ let serviceStatus = try run(+ "/bin/launchctl",+ ["print", "system/\(target.serviceLabel)"],+ capturesOutput: true+ )+ guard serviceStatus.status != 0 else {+ throw CleanupError.message("后台服务仍在运行, service=\(target.serviceLabel)")+ }+ }++ private func propertyListDictionary(at url: URL) throws -> [String: Any] {+ let data = try Data(contentsOf: url)+ guard let dictionary = try PropertyListSerialization.propertyList(from: data, format: nil)+ as? [String: Any] else {+ throw CleanupError.message("plist 内容无效, path=\(url.path)")+ }+ return dictionary+ }++ private func writePropertyList(_ dictionary: [String: Any], to url: URL) throws {+ let data = try PropertyListSerialization.data(+ fromPropertyList: dictionary,+ format: .xml,+ options: 0+ )+ try data.write(to: url, options: .atomic)+ }++ private func signingTeamIdentifier(for appURL: URL) throws -> String {+ let output = try runCodeSigningChecked(+ ["-dvv", appURL.path],+ failureReason: "读取签名信息失败, path=\(appURL.path)",+ capturesOutput: true+ ).text+ guard let line = output.split(whereSeparator: \.isNewline)+ .first(where: { $0.hasPrefix("TeamIdentifier=") }) else {+ throw CleanupError.codeSigningValidationFailed(+ "Team ID 缺失, path=\(appURL.path)"+ )+ }+ let teamIdentifier = String(line.dropFirst("TeamIdentifier=".count))+ guard !teamIdentifier.isEmpty else {+ throw CleanupError.codeSigningValidationFailed(+ "Team ID 为空, path=\(appURL.path)"+ )+ }+ guard teamIdentifier.unicodeScalars.allSatisfy(CharacterSet.alphanumerics.contains) else {+ throw CleanupError.codeSigningValidationFailed(+ "Team ID 格式错误, actual=\(teamIdentifier), expected=alphanumeric"+ )+ }+ return teamIdentifier+ }++ @discardableResult+ private func runCodeSigningChecked(+ _ arguments: [String],+ failureReason: String,+ capturesOutput: Bool = false+ ) throws -> CommandOutput {+ let output: CommandOutput+ do {+ output = try run(+ "/usr/bin/codesign",+ arguments,+ capturesOutput: capturesOutput+ )+ } catch {+ throw CleanupError.codeSigningValidationFailed(+ "\(failureReason), detail=\(error.localizedDescription)"+ )+ }+ guard output.status == 0 else {+ let detail = output.text.trimmingCharacters(in: .whitespacesAndNewlines)+ let detailSuffix = detail.isEmpty ? "" : ", detail=\(detail)"+ throw CleanupError.codeSigningValidationFailed(+ "\(failureReason), status=\(output.status)\(detailSuffix)"+ )+ }+ return output+ }++ @discardableResult+ private func runChecked(+ _ executable: String,+ _ arguments: [String],+ capturesOutput: Bool = false+ ) throws -> CommandOutput {+ let output = try run(executable, arguments, capturesOutput: capturesOutput)+ guard output.status == 0 else {+ throw CleanupError.commandFailed(+ executable: executable,+ arguments: arguments,+ status: output.status,+ output: output.text+ )+ }+ return output+ }++ private func run(+ _ executable: String,+ _ arguments: [String],+ capturesOutput: Bool+ ) throws -> CommandOutput {+ let process = Process()+ process.executableURL = URL(fileURLWithPath: executable)+ process.arguments = arguments++ let pipe: Pipe?+ if capturesOutput {+ let outputPipe = Pipe()+ process.standardOutput = outputPipe+ process.standardError = outputPipe+ pipe = outputPipe+ } else {+ pipe = nil+ }++ try process.run()+ let data = pipe?.fileHandleForReading.readDataToEndOfFile() ?? Data()+ process.waitUntilExit()+ return CommandOutput(+ status: process.terminationStatus,+ text: String(decoding: data, as: UTF8.self)+ )+ }+}++private func runUnregisterChild(plistName: String) -> Never {+ let service = SMAppService.daemon(plistName: plistName)+ switch service.status {+ case .enabled, .requiresApproval:+ service.unregister { error in+ if let error {+ FileHandle.standardError.write(+ Data(+ "后台服务注销失败: service=\(plistName), detail=\(error.localizedDescription)\n".utf8+ )+ )+ Darwin.exit(EXIT_FAILURE)+ }+ print("后台服务已注销: service=\(plistName)")+ Darwin.exit(EXIT_SUCCESS)+ }+ RunLoop.main.run()+ Darwin.exit(EXIT_FAILURE)+ case .notRegistered, .notFound:+ print("后台服务未注册: service=\(plistName)")+ Darwin.exit(EXIT_SUCCESS)+ @unknown default:+ FileHandle.standardError.write(+ Data("后台服务状态未知: service=\(plistName)\n".utf8)+ )+ Darwin.exit(EXIT_FAILURE)+ }+}++let arguments = Array(CommandLine.arguments.dropFirst())+if arguments.first == "--unregister-child" {+ guard arguments.count == 2 else {+ FileHandle.standardError.write(+ Data("内部参数无效: expected=2, actual=\(arguments.count)\n".utf8)+ )+ Darwin.exit(EXIT_FAILURE)+ }+ runUnregisterChild(plistName: arguments[1])+}++do {+ try KeepAliveCleanupCommand().run(arguments: arguments)+} catch {+ FileHandle.standardError.write(Data("清理失败: \(error.localizedDescription)\n".utf8))+ Darwin.exit(EXIT_FAILURE)+}diff --git a/Shared/CodexBarHelperXPC.swift b/Shared/CodexBarHelperXPC.swiftnew file mode 100644index 0000000..8d5e907--- /dev/null+++ b/Shared/CodexBarHelperXPC.swift@@ -0,0 +1,25 @@+import Foundation++nonisolated enum CodexBarHelperIPC {+ static let helperBundleIdentifierSuffix = ".helper"+ static let machServiceName = bundleIdentifier.hasSuffix(helperBundleIdentifierSuffix)+ ? bundleIdentifier+ : bundleIdentifier + helperBundleIdentifierSuffix+ static let daemonPlistName = machServiceName + ".plist"+ static let watchdogGraceSeconds: TimeInterval = 15+ static let sentinelCheckIntervalSeconds: TimeInterval = 60++ private static let bundleIdentifier: String = {+ guard let identifier = Bundle.main.bundleIdentifier, !identifier.isEmpty else {+ preconditionFailure("CodexBar bundle identifier 缺失")+ }+ return identifier+ }()+}++@objc nonisolated protocol CodexBarHelperProtocol: AnyObject {+ func setSleepDisabled(+ _ disabled: Bool,+ reply: @escaping @Sendable (Int32, Bool) -> Void+ )+}diff --git a/appcast.xml b/appcast.xmlindex 2579d32..45fef85 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.0</title>+ <sparkle:version>54</sparkle:version>+ <sparkle:shortVersionString>3.5.0</sparkle:shortVersionString>+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#3.5.0</sparkle:releaseNotesLink>+ <pubDate>Fri, 24 Jul 2026 19:03:37 +0800</pubDate>+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v3.5.0.dmg" sparkle:edSignature="3qaofG00ROUq5OWFQ0SClpIbo1v6SCUJcekOyvhrfj6DdPMf6DSeXMNO0hBYorKws6BzfaZWforXEgGIBmIzAg==" length="5807840" type="application/octet-stream"/>+ </item><item><title>CodexBar.app 3.4.3</title><sparkle:version>53</sparkle:version>