CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
fix: 避免任务结束后主动睡眠导致黑屏锁定
Bob5e28d91d4a3e
diff --git a/CodexBar.xcodeproj/project.pbxproj b/CodexBar.xcodeproj/project.pbxprojindex 011fa96..78abdd3 100644--- a/CodexBar.xcodeproj/project.pbxproj+++ b/CodexBar.xcodeproj/project.pbxproj@@ -238,7 +238,7 @@attributes = {BuildIndependentTargetsInParallel = 1;LastSwiftUpdateCheck = 2650;- LastUpgradeCheck = 2660;+ LastUpgradeCheck = 2700;TargetAttributes = {B10000000000000000000031 = {CreatedOnToolsVersion = 26.5;@@ -351,6 +351,7 @@buildSettings = {ALWAYS_SEARCH_USER_PATHS = NO;ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;+ CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;CLANG_ANALYZER_NONNULL = YES;CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";@@ -419,6 +420,7 @@buildSettings = {ALWAYS_SEARCH_USER_PATHS = NO;ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;+ CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;CLANG_ANALYZER_NONNULL = YES;CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";diff --git a/CodexBar.xcodeproj/xcshareddata/xcschemes/CodexBar.xcscheme b/CodexBar.xcodeproj/xcshareddata/xcschemes/CodexBar.xcschemeindex 28ee613..eae733b 100644--- a/CodexBar.xcodeproj/xcshareddata/xcschemes/CodexBar.xcscheme+++ b/CodexBar.xcodeproj/xcshareddata/xcschemes/CodexBar.xcscheme@@ -1,6 +1,6 @@<?xml version="1.0" encoding="UTF-8"?><Scheme- LastUpgradeVersion = "2660"+ LastUpgradeVersion = "2700"version = "1.7"><BuildActionparallelizeBuildables = "YES"diff --git a/CodexBar/Resources/Localizable.xcstrings b/CodexBar/Resources/Localizable.xcstringsindex 99e63f3..bbf1a69 100644--- a/CodexBar/Resources/Localizable.xcstrings+++ b/CodexBar/Resources/Localizable.xcstrings@@ -156,7 +156,7 @@"zh-Hans" : {"stringUnit" : {"state" : "translated",- "value" : "长时间没有进展时隐藏任务并停止参与防睡眠"+ "value" : "任务长时间没有进展时隐藏并停止参与防睡眠"}}}@@ -2369,22 +2369,6 @@}}},- "keep-alive.error.request-system-sleep-failed" : {- "localizations" : {- "en" : {- "stringUnit" : {- "state" : "translated",- "value" : "Could not request system sleep"- }- },- "zh-Hans" : {- "stringUnit" : {- "state" : "translated",- "value" : "请求系统睡眠失败"- }- }- }- },"keep-alive.error.restore-idle-sleep-failed" : {"localizations" : {"en" : {diff --git a/CodexBar/Services/KeepAlive/HelperRuntimeStatusMonitor.swift b/CodexBar/Services/KeepAlive/HelperRuntimeStatusMonitor.swiftindex 8823d39..fca8755 100644--- a/CodexBar/Services/KeepAlive/HelperRuntimeStatusMonitor.swift+++ b/CodexBar/Services/KeepAlive/HelperRuntimeStatusMonitor.swift@@ -33,13 +33,14 @@ final class HelperRuntimeStatusMonitor {case cancelled}- private(set) var isRequestInFlight = false+ var isRequestInFlight: Bool {+ requestContinuation != nil+ }private var requestGeneration: UInt64 = 0private var requestContinuation: CheckedContinuation<RequestResult, Never>?private var requestTimeoutTask: Task<Void, Never>?private var observationTask: Task<Void, Never>?- private var observationToken: UUID?func fetch(connection: NSXPCConnection,@@ -143,9 +144,7 @@ final class HelperRuntimeStatusMonitor {return}- let token = UUID()- observationToken = token- observationTask = Task { @MainActor [weak self] in+ observationTask = Task { @MainActor inwhile !Task.isCancelled {try? await Task.sleep(for: interval)guard !Task.isCancelled else {@@ -153,18 +152,12 @@ final class HelperRuntimeStatusMonitor {}await action()}- guard let self, observationToken == token else {- return- }- observationTask = nil- observationToken = nil}}func cancelObservation() {observationTask?.cancel()observationTask = nil- observationToken = nil}func cancelRequest() {@@ -185,7 +178,6 @@ final class HelperRuntimeStatusMonitor {}return await withCheckedContinuation { continuation in- isRequestInFlight = truerequestGeneration &+= 1let generation = requestGenerationrequestContinuation = continuation@@ -277,16 +269,14 @@ final class HelperRuntimeStatusMonitor {}private func finishRequest(_ result: RequestResult, generation: UInt64) {- guard generation == requestGeneration, isRequestInFlight else {+ guard generation == requestGeneration, let continuation = requestContinuation else {return}requestTimeoutTask?.cancel()requestTimeoutTask = nil- isRequestInFlight = false- let continuation = requestContinuationrequestContinuation = nil- continuation?.resume(returning: result)+ continuation.resume(returning: result)}private enum RequestResult {diff --git a/CodexBar/Services/KeepAlive/KeepAliveController.swift b/CodexBar/Services/KeepAlive/KeepAliveController.swiftindex 25eb4b1..58617e2 100644--- a/CodexBar/Services/KeepAlive/KeepAliveController.swift+++ b/CodexBar/Services/KeepAlive/KeepAliveController.swift@@ -72,8 +72,7 @@ final class KeepAliveController: ObservableObject {/// 低电量导致睡眠恢复之后回调一次, 参数是触及阈值时的电量; 由 AppDelegate 接到通知服务/// 用事件回调而不是 @Published: 触发是一次性动作, 电量回升到解除门槛以上后再次跌破要能重新发一次- /// async 是为了让补发睡眠等到通知真的提交完: 同步回调只把提交排进下一个 MainActor job,- /// 而 IOPMSleepSystem 就在当前这个 job 里, 机器会先睡下去+ /// 通知提交完成前保留空闲断言, 避免恢复系统策略后先进入空闲睡眠/// 返回值是通知有没有真的发出去, 决定这一轮算不算已通知var onLowBatteryTriggered: ((Int) async -> Bool)?@@ -1032,13 +1031,10 @@ final class KeepAliveController: ObservableObject {generation: UInt64,isObservation: Bool) {- let lidStatus = SystemSleepService.currentStatus()- let lidCausesSleep = lidStatus.map { $0.lidClosureCausesSleep ? "1" : "0" } ?? "unknown"if !isObservation || source != previousSource {let details = LogFields.joined("generation=\(generation)",- "source=\(String(describing: source))",- "lidCausesSleep=\(lidCausesSleep)"+ "source=\(String(describing: source))")AppLog.keepAlive.notice("已防止系统睡眠: \(details, privacy: .public)")}@@ -1089,33 +1085,6 @@ final class KeepAliveController: ObservableObject {}AppLog.keepAlive.notice("系统睡眠已恢复: sleepDisabled=\(sleepDisabled)")-- let lidStatus = SystemSleepService.currentStatus()- let shouldRequestSystemSleep = !sleepDisabledAfterOperation- && lidStatus?.shouldSleepForLidClosure == true-- // 合盖是边沿事件, 错过那一刻系统不会再评估- // 只有 CodexBar 自己挡过并恢复为 0 才补发, 外部来源不属于我们的合盖边沿- guard shouldRequestSystemSleep else {- let reason: String = if sleepDisabledAfterOperation {- "stillDisabled"- } else if let lidStatus {- lidStatus.isLidClosed ? "clamshellMode" : "lidOpen"- } else {- "unknown"- }- AppLog.keepAlive.notice(- "睡眠补发已跳过: reason=\(reason, privacy: .public)"- )- return- }-- AppLog.keepAlive.notice("睡眠补发已请求")- let result = SystemSleepService.requestSystemSleep()- if result != kIOReturnSuccess {- AppLog.keepAlive.error("睡眠补发失败: code=\(result)")- operationErrorMessage = KeepAliveLocalizedMessage.requestSystemSleepFailed- }}private func completePendingRequest(success: Bool) {diff --git a/CodexBar/Services/KeepAlive/KeepAliveModels.swift b/CodexBar/Services/KeepAlive/KeepAliveModels.swiftindex 018f58d..abcb560 100644--- a/CodexBar/Services/KeepAlive/KeepAliveModels.swift+++ b/CodexBar/Services/KeepAlive/KeepAliveModels.swift@@ -162,7 +162,6 @@ nonisolated enum KeepAliveLocalizedMessage {static let preventIdleSleepFailed = String(localized: "keep-alive.error.prevent-idle-sleep-failed")static let toggleSleepFailed = String(localized: "keep-alive.error.toggle-sleep-failed")static let restoreIdleSleepFailed = String(localized: "keep-alive.error.restore-idle-sleep-failed")- static let requestSystemSleepFailed = String(localized: "keep-alive.error.request-system-sleep-failed")static let connectionFailed = String(localized: "keep-alive.error.connection-failed")static let noResponse = String(localized: "keep-alive.error.no-response")static let retryLimitReached = String(localized: "keep-alive.error.retry-limit-reached")diff --git a/CodexBar/Services/KeepAlive/SystemSleepService.swift b/CodexBar/Services/KeepAlive/SystemSleepService.swiftindex fe46e7d..48433d8 100644--- a/CodexBar/Services/KeepAlive/SystemSleepService.swift+++ b/CodexBar/Services/KeepAlive/SystemSleepService.swift@@ -5,15 +5,6 @@ import os@MainActorfinal class SystemSleepService {- struct Status: Equatable, Sendable {- let isLidClosed: Bool- let lidClosureCausesSleep: Bool-- var shouldSleepForLidClosure: Bool {- isLidClosed && lidClosureCausesSleep- }- }-/// 两条断言只差类型与名字, 持有和释放的规则完全一样/// 名称必须是 ASCII: 含中文时 pmset -g assertions 的 named 会显示成空串, 断言就失去了标识private struct Assertion {@@ -154,57 +145,6 @@ final class SystemSleepService {}}- 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)- }-/// 节拍取得比系统能设的最短屏保等待时间 (1 分钟) 小private static let userActivityInterval = Duration.seconds(30)-- 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/CodexNotificationService.swift b/CodexBar/Services/Notifications/CodexNotificationService.swiftindex ff56b8f..0680ebf 100644--- a/CodexBar/Services/Notifications/CodexNotificationService.swift+++ b/CodexBar/Services/Notifications/CodexNotificationService.swift@@ -472,7 +472,7 @@ final class CodexNotificationService: NSObject {/// 由 KeepAliveController 在低电量导致睡眠恢复成功之后调用, 恢复失败不会走到这里/// 不做去重: 调用方自己保证同一轮低电量只发一次, 电量回到解除门槛以上才算下一轮- /// async 是为了让调用方能等提交完再补发睡眠, 否则合着盖的机器会先睡下去+ /// 调用方在提交完成前保留空闲断言, 避免系统先进入空闲睡眠/// 返回是否真的发出去了: 调用方据此决定这一轮算不算已通知, 提交失败就不该占掉这一轮func notifyLowBatteryProtection(percent: Int) async -> Bool {guard settings.canDeliver, settings.isLowBatteryEnabled else {@@ -488,7 +488,7 @@ final class CodexNotificationService: NSObject {// MARK: - 防睡眠时长上限/// 由 KeepAliveController 在达到时长上限且睡眠恢复成功之后调用- /// 调用时机与低电量通知相同, 必须赶在可能补发合盖睡眠之前完成提交+ /// 调用方在提交完成前保留空闲断言, 与低电量通知一致func notifyKeepAliveLimitReached(durationText: String) async -> Bool {guard settings.canDeliver, settings.isKeepAliveLimitEnabled else {return falsediff --git a/CodexBarHelper/main.swift b/CodexBarHelper/main.swiftindex 9378d62..dfe81b3 100644--- a/CodexBarHelper/main.swift+++ b/CodexBarHelper/main.swift@@ -743,7 +743,7 @@ private final class CodexBarHelperRuntime: NSObject, NSXPCListenerDelegate, @unc}guard ownership.needsRestore else {- // 未取得所有权时不写 pmset, 保留最近一次实测值供 App 判断是否需要补发系统睡眠+ // 未取得所有权时不写 pmset, 返回最近一次实测值return SleepOperationResult(exitCode: 0,source: source,diff --git a/CodexBarTests/HelperRuntimeStatusMonitorTests.swift b/CodexBarTests/HelperRuntimeStatusMonitorTests.swiftnew file mode 100644index 0000000..964f3f6--- /dev/null+++ b/CodexBarTests/HelperRuntimeStatusMonitorTests.swift@@ -0,0 +1,182 @@+import Foundation+import Testing++@Suite(.timeLimit(.minutes(1)))+struct HelperRuntimeStatusMonitorTests {+ @Test func observationCanRestartAfterCancellationBeforeFirstTick() async {+ let monitor = HelperRuntimeStatusMonitor()+ defer { monitor.cancelObservation() }+ let finished = MonitorCheckpoint()+ monitor.startObservation(interval: .seconds(60)) {+ Issue.record("Cancelled observation ran")+ }+ monitor.cancelObservation()+ monitor.startObservation(interval: .zero) {+ monitor.cancelObservation()+ finished.signal()+ }+ await finished.wait()+ }++ @Test func cancelledObservationCannotClearReplacementWhileItsActionFinishes() async {+ let monitor = HelperRuntimeStatusMonitor()+ defer { monitor.cancelObservation() }+ let oldEntered = MonitorCheckpoint()+ let oldRelease = MonitorCheckpoint()+ let oldReturned = MonitorCheckpoint()+ let replacementFinished = MonitorCheckpoint()+ var replacementTicks = 0+ monitor.startObservation(interval: .zero) {+ oldEntered.signal()+ await oldRelease.wait()+ oldReturned.signal()+ }+ await oldEntered.wait()+ monitor.cancelObservation()+ monitor.startObservation(interval: .milliseconds(1)) {+ replacementTicks += 1+ if replacementTicks == 2 {+ monitor.cancelObservation()+ replacementFinished.signal()+ }+ }+ oldRelease.signal()+ await oldReturned.wait()+ monitor.startObservation(interval: .zero) {+ Issue.record("Replacement observation was overwritten")+ monitor.cancelObservation()+ replacementFinished.signal()+ }+ await replacementFinished.wait()+ #expect(replacementTicks == 2)+ }++ @Test func cancelledStatusReplyCannotFinishNewWakeRequest() async {+ let monitor = HelperRuntimeStatusMonitor()+ let helper = MonitorHelper()+ let connection = MonitorConnection(helper: helper)+ defer { monitor.cancelRequest() }+ let statusTask = Task {+ await monitor.fetch(+ connection: connection,+ timeout: .seconds(60),+ onConnectionFailure: { _ in Issue.record("Unexpected connection failure") },+ onTimeout: { Issue.record("Unexpected timeout") }+ )+ }+ await helper.statusRequested.wait()+ #expect(monitor.isRequestInFlight)+ monitor.cancelRequest()+ #expect(!monitor.isRequestInFlight)+ #expect(await statusTask.value == nil)++ let wakeTask = Task {+ await monitor.setAutoResetWakeSchedule(connection: connection, unixTimestamp: 0, timeout: .seconds(60))+ }+ await helper.wakeRequested.wait()+ helper.statusReply?(0, CodexBarSleepOwnershipState.idle.rawValue, 0, false)+ #expect(monitor.isRequestInFlight)+ helper.wakeReply?(0)+ guard case .success = await wakeTask.value else {+ Issue.record("New wake request did not succeed")+ return+ }+ #expect(!monitor.isRequestInFlight)+ }++ @Test func timeoutClearsRequestAndLateReplyDoesNotPreventReuse() async {+ let monitor = HelperRuntimeStatusMonitor()+ let helper = MonitorHelper()+ let connection = MonitorConnection(helper: helper)+ defer { monitor.cancelRequest() }+ let result = await monitor.setAutoResetWakeSchedule(connection: connection, unixTimestamp: 0, timeout: .zero)+ guard case .timedOut = result else {+ Issue.record("Request did not time out")+ return+ }+ #expect(!monitor.isRequestInFlight)+ helper.wakeReply?(0)++ let statusTask = Task {+ await monitor.fetch(+ connection: connection,+ timeout: .seconds(60),+ onConnectionFailure: { _ in Issue.record("Unexpected connection failure") },+ onTimeout: { Issue.record("Unexpected timeout") }+ )+ }+ await helper.statusRequested.wait()+ helper.statusReply?(0, CodexBarSleepOwnershipState.owned.rawValue, 1, true)+ let status = await statusTask.value+ #expect(status?.ownership == .owned)+ #expect(status?.activeClientCount == 1)+ #expect(status?.sleepDisabled == true)+ #expect(!monitor.isRequestInFlight)+ }+}++private final nonisolated class MonitorConnection: NSXPCConnection {+ let helper: MonitorHelper++ init(helper: MonitorHelper) {+ self.helper = helper+ super.init()+ }++ override func remoteObjectProxyWithErrorHandler(_: @escaping (any Error) -> Void) -> Any {+ helper+ }+}++@MainActor+private final class MonitorHelper: NSObject, CodexBarHelperProtocol {+ let statusRequested = MonitorCheckpoint()+ let wakeRequested = MonitorCheckpoint()+ var statusReply: (@Sendable (Int32, Int, Int, Bool) -> Void)?+ var wakeReply: (@Sendable (Int32) -> Void)?++ nonisolated func getSleepPreventionStatus(reply: @escaping @Sendable (Int32, Int, Int, Bool) -> Void) {+ MainActor.assumeIsolated {+ statusReply = reply+ statusRequested.signal()+ }+ }++ nonisolated func setAutoResetWakeSchedule(_: TimeInterval, reply: @escaping @Sendable (Int32) -> Void) {+ MainActor.assumeIsolated {+ wakeReply = reply+ wakeRequested.signal()+ }+ }++ nonisolated func setSleepPreventionRequested(+ _: Bool,+ clientSessionID _: String,+ generation _: UInt64,+ reply: @escaping @Sendable (Int32, Int, Bool) -> Void+ ) {+ Issue.record("Unexpected sleep prevention request")+ reply(-1, 0, false)+ }++ nonisolated func resetSleepAfterUpdate(_: String, reply: @escaping @Sendable (Int32) -> Void) {+ Issue.record("Unexpected update reset request")+ reply(-1)+ }+}++private final class MonitorCheckpoint {+ private var isSignaled = false+ private var waiter: CheckedContinuation<Void, Never>?++ func wait() async {+ guard !isSignaled else { return }+ await withCheckedContinuation { waiter = $0 }+ }++ func signal() {+ isSignaled = true+ waiter?.resume()+ waiter = nil+ }+}diff --git a/Config/Version.xcconfig b/Config/Version.xcconfigindex 7436192..dd19f11 100644--- a/Config/Version.xcconfig+++ b/Config/Version.xcconfig@@ -1,2 +1,2 @@-MARKETING_VERSION = 4.0.3-CURRENT_PROJECT_VERSION = 103+MARKETING_VERSION = 4.0.4+CURRENT_PROJECT_VERSION = 104diff --git a/Docs/DeveloperGuide/notifications.md b/Docs/DeveloperGuide/notifications.mdindex c90b716..8dbba6e 100644--- a/Docs/DeveloperGuide/notifications.md+++ b/Docs/DeveloperGuide/notifications.md@@ -180,7 +180,7 @@ app-server 连接重建后,同一窗口的 `resetsAt` 可能出现秒级修正低电量或最长时长导致防睡眠停止时,`KeepAliveController` 先撤销 CodexBarHelper 租约。只有回复确认来源为 `.codexBar` 且 `SleepDisabled=0` 时,才提交对应通知;其他结果会清除本轮待发通知。-App idle assertion 保留到通知提交结束,随后释放,并按需补发合盖睡眠。+App idle assertion 保留到通知提交结束,随后释放,由 macOS 按系统电源策略决定睡眠时机。## 声音diff --git a/Docs/DeveloperGuide/sleep-prevention.md b/Docs/DeveloperGuide/sleep-prevention.mdindex 24bdc19..61e928e 100644--- a/Docs/DeveloperGuide/sleep-prevention.md+++ b/Docs/DeveloperGuide/sleep-prevention.md@@ -74,12 +74,11 @@ App 侧 assertion 会在 XPC 获取流程开始前建立。这样 helper 切换-> 停止时长累计-> 提交低电量或时长上限通知-> 释放 App idle assertion- -> 必要时补发合盖睡眠```低电量和时长上限通知仅在 helper 回复来源为 `.codexBar` 且 `SleepDisabled=0` 后提交。-App idle assertion 保留到通知提交结束,避免系统在提交前睡下。随后释放 assertion 并按需执行合盖睡眠补偿。+App idle assertion 保留到通知提交结束,避免系统在提交前进入空闲睡眠。随后释放 assertion,由 macOS 按系统电源策略决定睡眠时机。## 不确定的租约状态@@ -375,17 +374,11 @@ helper 会分别检查 lease、ownership 记录和实测 `SleepDisabled`assertion 名称使用 ASCII。某些系统版本中带中文的名称会在 `pmset -g assertions` 中显示为空,使诊断信息失去标识。-## 合盖恢复的边沿补偿+## 恢复系统电源管理-合盖睡眠是一个边沿事件。如果合盖时 `SleepDisabled=1`,系统错过该边沿后不会仅因为稍后恢复为 `0` 就再次自动评估。+任务结束、关闭功能、低电量或达到时长上限时,CodexBar 释放租约和 App assertion。Helper 仅在持有恢复责任且无其他租约时恢复系统睡眠设置,外部来源的设置保持原样。-CodexBar 在确认自己拥有的系统设置已恢复后读取 clamshell 状态。当盖子仍闭合且该硬件模式应因合盖睡眠时,主动请求一次系统睡眠。--补偿只用于 `.codexBar` 来源:--- external 状态不是 CodexBar 改写的,不能替外部所有者决定何时睡眠-- `SleepDisabled` 仍为 `1` 时不能请求-- 无法读取合盖状态时不猜测+解除防睡眠不主动请求系统睡眠。合盖和外接显示器场景均由 macOS 按系统电源策略决定是否睡眠,任务结束不保证立即进入睡眠。## 失败与重试策略@@ -422,6 +415,10 @@ App 更新可能改变内嵌 CodexBarHelper 的签名或内容。App 会记录 C## 手动验证- 运行任务开始和结束时,App assertion 与 CodexBarHelper 租约同步切换+- 合盖、接电并使用外接显示器时,任务结束仅解除保活,不主动熄屏或锁屏+- 开盖时,任务结束后恢复系统设定的闲置睡眠+- 无外接显示器且合盖运行任务时,记录任务结束后系统实际进入睡眠的时机+- 关闭防睡眠、低电量和时长上限触发时,租约与 assertion 正确释放且不发起软件睡眠- 等待批准设置关闭和开启时,有效任务判断正确- 外部先设置 `disablesleep 1` 时,CodexBar 不声明所有权也不恢复为 `0`- App 正常退出时恢复 owned 状态diff --git a/Docs/en/DeveloperGuide/notifications.md b/Docs/en/DeveloperGuide/notifications.mdindex b697013..a76e0ec 100644--- a/Docs/en/DeveloperGuide/notifications.md+++ b/Docs/en/DeveloperGuide/notifications.md@@ -180,7 +180,7 @@ Protection notifications use the system default sound and a `retryCount` of `0`When low battery or the duration limit stops sleep prevention, `KeepAliveController` first releases its helper lease. It submits the notification only if the reply reports source `.codexBar` and `SleepDisabled=0`; other results clear the pending notice for that cycle.-The app idle assertion remains until notification submission finishes, then is released before any compensating lid-close sleep.+The app idle assertion remains until notification submission finishes, then is released, leaving sleep timing to macOS power management.## Soundsdiff --git a/Docs/en/DeveloperGuide/sleep-prevention.md b/Docs/en/DeveloperGuide/sleep-prevention.mdindex feb0be7..52632af 100644--- a/Docs/en/DeveloperGuide/sleep-prevention.md+++ b/Docs/en/DeveloperGuide/sleep-prevention.md@@ -74,12 +74,11 @@ Conditions block activation-> Stop duration accumulation-> Submit low-battery or duration-limit notification-> Release app idle assertion- -> Compensate for lid-close sleep if needed```Low-battery and duration-limit notices are submitted only when the helper replies with source `.codexBar` and `SleepDisabled=0`.-The app retains its idle assertion until notification submission finishes so the system does not sleep before submission. It then releases the assertion and applies lid-close sleep compensation if needed.+The app retains its idle assertion until notification submission finishes to prevent idle sleep before submission. It then releases the assertion, leaving sleep timing to macOS power management.## Uncertain Lease State@@ -375,17 +374,11 @@ A failed display assertion records its own error without overriding primary sleeAssertion names use ASCII. On some system versions, Chinese names appear empty in `pmset -g assertions` and lose diagnostic identity.-## Lid-Close Edge Compensation+## Restoring System Power Management-Lid-close sleep is an edge event. If `SleepDisabled=1` at lid close, later restoring it to `0` does not necessarily make the system reevaluate the missed edge.+When tasks finish, the feature is disabled, the battery runs low, or the duration limit is reached, CodexBar releases its lease and app assertions. The helper restores system sleep settings only when it has restoration responsibility and no other leases remain. Settings owned by external sources remain unchanged.-After confirming restoration of CodexBar-owned state, CodexBar reads clamshell state. If the lid remains closed and that hardware mode should sleep on close, it explicitly requests system sleep once.--Compensation applies only to `.codexBar` source:--- External state was not changed by CodexBar, so it cannot decide sleep timing for its owner-- It must not request sleep while `SleepDisabled` remains `1`-- It does not guess when clamshell state is unreadable+Releasing sleep prevention does not explicitly request system sleep. macOS decides whether to sleep according to system power policy, including when the lid is closed or external displays are connected. Task completion does not guarantee immediate sleep.## Failure and Retry@@ -422,6 +415,10 @@ Validation must cover:## Manual Validation Matrix- App assertion and CodexBarHelper lease switch together when a running task starts and ends+- With the lid closed, AC power connected, and external displays in use, task completion releases sleep prevention without explicitly sleeping the displays or locking the screen+- With the lid open, task completion restores the configured system idle-sleep policy+- With the lid closed and no external displays, record when the system actually sleeps after task completion+- Disabling sleep prevention, low battery, and the duration limit release leases and assertions without requesting software sleep- Eligible-task decisions are correct with Keep Awake While Waiting off and on- If an external source sets `disablesleep 1` first, CodexBar neither claims ownership nor restores `0`- Normal app exit restores owned statediff --git a/appcast.xml b/appcast.xmlindex 8509824..1b363db 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 4.0.4</title>+ <sparkle:version>104</sparkle:version>+ <sparkle:shortVersionString>4.0.4</sparkle:shortVersionString>+ <sparkle:minimumSystemVersion>15.0</sparkle:minimumSystemVersion>+ <sparkle:releaseNotesLink>https://codexbar.zabrian.app/notes#4.0.4</sparkle:releaseNotesLink>+ <pubDate>Fri, 18 Sep 2026 18:00:21 +0800</pubDate>+ <enclosure url="https://codexbar.zabrian.app/download/CodexBar-v4.0.4.dmg" sparkle:edSignature="XzeqZMC+9wS/21VT1VA5d4z6lKiFRDpv1HL6Hb/vfSDidRv81/wTgYp+xHgm0/hu16bYRs6DgRpJiJcn/4vRAw==" length="8299008" type="application/octet-stream"/>+ </item><item><title>CodexBar.app 4.0.3</title><sparkle:version>103</sparkle:version>