How KeepAwakeManager Handles Power Assertions and Lid-Closed State in vorssaint-utils
KeepAwakeManager prevents macOS sleep by creating IOKit power assertions for system and display idle prevention, while optionally managing clamshell mode through password-less sudo rules that execute pmset disablesleep.
The KeepAwakeManager class in the vorssaint-utils repository serves as the central coordination service for maintaining macOS wakefulness during user-requested sessions. It implements a dual-layered approach combining IOKit power assertions for standard sleep prevention with specialized handling for lid-closed scenarios through system-level power management commands.
Creating IOKit Power Assertions
The manager creates IOKit power assertions through the applyAssertions() method in Sources/Vorssaint/Services/KeepAwakeManager.swift. These assertions interface directly with macOS power management to block idle sleep triggers.
Preventing System Idle Sleep
To inhibit system-wide sleep, the manager creates an assertion of type PreventUserIdleSystemSleep using IOPMAssertionCreateWithName. The resulting IOPMAssertionID is stored in the systemAssertion property for later release. This mechanism is implemented in lines 15-27 of KeepAwakeManager.swift.
When the session ends, releaseAssertions() invokes IOPMAssertionRelease on the stored ID to restore normal sleep behavior (lines 45-56).
Preventing Display Sleep
Display sleep inhibition operates conditionally based on the DefaultsKey.keepAwakeAllowDisplaySleep preference. When the user disables display sleep, applyAssertions() creates a second assertion of type PreventUserIdleDisplaySleep, storing the ID in displayAssertion. If the user enables display sleep, any existing display assertion is immediately released.
This logic is handled within lines 27-44 of the same file, ensuring the display assertion state always reflects current user preferences.
Managing Lid-Closed (Clamshell) State
Beyond standard idle assertions, KeepAwakeManager implements clamshell mode handling to prevent sleep when the laptop lid is closed. This requires elevating privileges to modify system power settings.
Password-Less Sudo Configuration
The manager avoids repeated password prompts by utilizing a password-less sudoers rule defined in Sources/Vorssaint/Support/Sudoers.swift. When applyClamshellPreference() detects that clamshellPreferred is enabled (defined in Sources/Vorssaint/Core/Defaults.swift), it first checks for the existence of the passwordlessClamshell rule.
If the rule is missing, prepareClamshellPreference() installs it via Sudoers.install and sets a retry flag (clamshellSetupRetried) to attempt activation once after installation completes. This setup flow spans lines 58-107 in KeepAwakeManager.swift.
Enabling and Disabling Clamshell Mode
Once the sudoers infrastructure exists, enableClamshell() executes Sudoers.pmsetDisableSleep(true) to invoke pmset disablesleep 1, preventing the system from sleeping when the lid closes. The method updates the published properties clamshellActive, clamshellSetupInProgress, and clamshellSetupFailed to reflect the operation state.
Termination requires disableClamshell(_:), which accepts a synchronous parameter. When the app quits, it runs synchronously to guarantee cleanup; during normal operation, it runs asynchronously. This teardown logic is located in lines 124-148.
Session Lifecycle Coordination
Session state changes are orchestrated through activate(minutes:) and deactivate(reason:), defined in lines 50-63 and 92-107 respectively.
When activation occurs, the manager first checks sessionPausedForScreenLock to determine if the screen is currently locked. If not paused, it immediately invokes applyAssertions() and conditionally calls applyClamshellPreference() when clamshellPreferred is true.
Deactivation triggers a comprehensive teardown: releaseAssertions() clears both system and display IOKit assertions, while disableClamshell(synchronous:) restores normal lid-close behavior. This ensures no power assertions or system modifications persist beyond the intended session duration.
Practical Implementation Examples
The following patterns demonstrate typical usage of the KeepAwakeManager API:
import Vorssaint
// Initiate a 10-minute keep-awake session
KeepAwakeManager.shared.activate(minutes: 10)
// Enable clamshell mode to prevent sleep when closing the lid
UserDefaults.standard.set(true, forKey: DefaultsKey.clamshellPreferred)
// Manually terminate the current session and restore power settings
KeepAwakeManager.shared.deactivate(reason: .manual)
Summary
- KeepAwakeManager creates
PreventUserIdleSystemSleepand optionalPreventUserIdleDisplaySleepassertions viaapplyAssertions()to block macOS idle sleep. - Clamshell mode is managed through password-less sudo rules that execute
pmset disablesleep, with on-demand installation and retry logic inprepareClamshellPreference(). - State cleanup is guaranteed through
releaseAssertions()anddisableClamshell(), called duringdeactivate(reason:)to restore normal power management. - Session coordination respects screen-lock states and user preferences defined in
Defaults.swift, ensuring assertions only apply during active, unlocked sessions.
Frequently Asked Questions
What IOKit power assertion types does KeepAwakeManager use?
The manager utilizes two distinct assertion types: PreventUserIdleSystemSleep to block system-wide idle sleep, and PreventUserIdleDisplaySleep to inhibit display dimming and sleep. These are created via IOPMAssertionCreateWithName and stored as IOPMAssertionID values in systemAssertion and displayAssertion respectively.
How does KeepAwakeManager handle lid-closed sleep without requiring a password every time?
It installs a password-less sudoers rule via Sudoers.install that permits the specific pmset disablesleep command without authentication. The passwordlessClamshell property checks for this rule's existence; if missing, the manager installs it once and retries the operation using clamshellSetupRetried, avoiding interactive password prompts during normal usage.
What happens to power assertions when the session ends or the app quits?
The deactivate(reason:) method calls releaseAssertions(), which invokes IOPMAssertionRelease on both the system and display assertion IDs. For clamshell mode, disableClamshell(synchronous:) runs pmset disablesleep 0 to re-enable normal lid-close behavior, ensuring all power management restrictions are cleared synchronously during app termination.
Can KeepAwakeManager prevent display sleep independently of system sleep?
Yes. The manager checks DefaultsKey.keepAwakeAllowDisplaySleep to determine whether to create the PreventUserIdleDisplaySleep assertion. When this preference is false, it creates only the system sleep assertion, allowing the display to sleep while keeping the machine awake for background processing.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →