Repository navigation
feat(tui): prevent macOS idle sleep while turns run - #11711
Conversation
|
All contributors have signed the CLA ✍️ ✅ |
|
I have read the CLA Document and I hereby sign the CLA |
|
recheck |
There was a problem hiding this comment.
Pull request overview
This PR adds macOS idle sleep prevention to the TUI when a turn is actively running. The implementation uses native IOKit power assertions instead of spawning caffeinate, providing tighter lifecycle management tied to Rust objects.
Changes:
- Added a new
SleepInhibitormodule incodex-corewith macOS-specific IOKit FFI bindings - Integrated sleep inhibition into both
tuiandtui2turn lifecycle hooks (TurnStarted,TurnComplete, error/abort handlers) - Added opt-in config field
tui.prevent_sleep_while_running(defaults tofalse)
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| codex-rs/core/src/sleep_inhibitor.rs | New module implementing cross-platform sleep inhibitor with macOS IOKit power assertions |
| codex-rs/core/src/lib.rs | Exports the new sleep_inhibitor module |
| codex-rs/core/src/config/types.rs | Adds prevent_sleep_while_running field to Tui config struct |
| codex-rs/core/src/config/mod.rs | Plumbs tui_prevent_sleep_while_running through merged Config and updates test fixtures |
| codex-rs/tui/src/chatwidget.rs | Integrates SleepInhibitor into ChatWidget lifecycle (start, complete, finalize) |
| codex-rs/tui2/src/chatwidget.rs | Integrates SleepInhibitor into ChatWidget lifecycle (start, complete, finalize) |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| let mut inhibitor = SleepInhibitor::new(true); | ||
| inhibitor.set_turn_running(true); | ||
| inhibitor.set_turn_running(false); | ||
| } |
There was a problem hiding this comment.
The test coverage should include additional test cases to ensure robustness:
- Test with
enabled: falseto verify no assertions are created - Test multiple calls to
set_turn_running(true)to ensure idempotency - Test toggling multiple times (true -> false -> true) to ensure proper cleanup and re-acquisition
These cases are important edge cases for the sleep inhibitor functionality.
| } | |
| } | |
| #[test] | |
| fn sleep_inhibitor_disabled_does_not_panic() { | |
| // When disabled, toggling should not create or manage any assertions | |
| // and must not panic. | |
| let mut inhibitor = SleepInhibitor::new(false); | |
| inhibitor.set_turn_running(true); | |
| inhibitor.set_turn_running(false); | |
| } | |
| #[test] | |
| fn sleep_inhibitor_multiple_true_calls_are_idempotent() { | |
| // Multiple calls to set_turn_running(true) should be safe and | |
| // effectively idempotent (no double-acquisition issues or panics). | |
| let mut inhibitor = SleepInhibitor::new(true); | |
| inhibitor.set_turn_running(true); | |
| inhibitor.set_turn_running(true); | |
| inhibitor.set_turn_running(true); | |
| inhibitor.set_turn_running(false); | |
| } | |
| #[test] | |
| fn sleep_inhibitor_can_toggle_multiple_times() { | |
| // Ensure we can alternate between running and not running multiple | |
| // times without panicking, implying proper cleanup and re-acquisition. | |
| let mut inhibitor = SleepInhibitor::new(true); | |
| inhibitor.set_turn_running(true); | |
| inhibitor.set_turn_running(false); | |
| inhibitor.set_turn_running(true); | |
| inhibitor.set_turn_running(false); | |
| } |
There was a problem hiding this comment.
Added the three edge-case tests in codex-rs/core/src/sleep_inhibitor.rs:
- disabled mode
- repeated
set_turn_running(true)idempotency - multi-toggle reacquisition
| if !self.enabled || !turn_running { | ||
| self.release(); | ||
| return; | ||
| } | ||
| self.acquire(); |
There was a problem hiding this comment.
The logic in set_turn_running has a subtle issue. When turn_running is false, it always calls release(), even when the feature is disabled (!self.enabled). While this works correctly because release() only operates on macOS and checks if an assertion exists, it would be more clear and efficient to check self.enabled first before deciding whether to acquire or release.
Consider refactoring to:
pub fn set_turn_running(&mut self, turn_running: bool) {
if !self.enabled {
return;
}
if turn_running {
self.acquire();
} else {
self.release();
}
}This makes the logic clearer and avoids unnecessary function calls when the feature is disabled.
| if !self.enabled || !turn_running { | |
| self.release(); | |
| return; | |
| } | |
| self.acquire(); | |
| if !self.enabled { | |
| return; | |
| } | |
| if turn_running { | |
| self.acquire(); | |
| } else { | |
| self.release(); | |
| } |
There was a problem hiding this comment.
Refactored set_turn_running to make the control flow explicit (!enabled guard, then acquire/release by turn_running).
Behavior is unchanged, but the intent is clearer.
Add a shared sleep inhibitor in codex-core that uses native macOS IOKit assertions (IOPMAssertionCreateWithName/IOPMAssertionRelease) instead of spawning caffeinate. Wire the inhibitor to turn lifecycle events in both tui and tui2 so it is active during TurnStarted and released on TurnComplete/abort/error paths. Add a new opt-in config key [tui].prevent_sleep_while_running (default false) and plumb it through merged runtime Config. Tested with cargo check for codex-core/codex-tui/codex-tui2 and targeted codex-core unit tests.
7d906b3 to
b8682e1
Compare
|
/codex please review this PR |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 5 out of 5 changed files in this pull request and generated no new comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b8682e1eea
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| #[serde(default)] | ||
| pub prevent_sleep_while_running: bool, |
There was a problem hiding this comment.
Regenerate config schema fixture for new TUI field
Adding prevent_sleep_while_running here without updating codex-rs/core/config.schema.json leaves the checked-in schema stale; config_schema_matches_fixture in core/src/config/schema.rs compares generated schema to that fixture and will fail until just write-config-schema is run, and tooling that consumes the fixture will not recognize this new key.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Addressed. I regenerated codex-rs/core/config.schema.json in commit 0c4a61ce1 (just write-config-schema) and that commit is included in this branch. Also, the implementation was later migrated from tui.prevent_sleep_while_running to the experimental feature key features.prevent_idle_sleep, and the schema fixture reflects that current shape.
|
@codex review |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 6 out of 6 changed files in this pull request and generated 1 comment.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| let handle = unsafe { | ||
| libc::dlopen( | ||
| IOKIT_FRAMEWORK_BINARY.as_ptr().cast(), | ||
| libc::RTLD_LOCAL | libc::RTLD_LAZY, | ||
| ) |
There was a problem hiding this comment.
MacSleepApi::load calls dlopen but never closes the library handle on the success path, and the returned MacSleepApi doesn’t retain the handle. This effectively leaks the handle for the process lifetime and makes the required lifetime relationship between the handle and the function pointers implicit. Consider storing the dlopen handle inside MacSleepApi (and documenting whether it’s intentionally kept open) so the ownership/lifetime is explicit (and so a future refactor doesn’t accidentally dlclose while still using the function pointers).
There was a problem hiding this comment.
Good call; addressed now.
MacSleepApi now explicitly retains the dlopen handle (_iokit_handle) and MacSleepApi::get() returns Option<&'static MacSleepApi> from a OnceLock, so the symbol owner/lifetime is explicit and tied to process lifetime. I also added comments in the struct documenting why the handle is intentionally retained.
|
Codex Review: Didn't find any major issues. Delightful! ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 6 out of 6 changed files in this pull request and generated 2 comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| fn on_task_started(&mut self) { | ||
| self.agent_turn_running = true; | ||
| self.turn_sleep_inhibitor.set_turn_running(true); | ||
| self.saw_plan_update_this_turn = false; |
There was a problem hiding this comment.
on_task_started always enables the sleep inhibitor, but dispatch_event_msg calls this handler for both live and replayed events (from_replay is ignored here). If a TurnStarted event is replayed (e.g., resume/reconnect), this can create a macOS power assertion during replay and potentially leave it enabled if replay ends without a matching TurnComplete/finalization. Consider threading from_replay into on_task_started (and skipping sleep inhibition when replaying), or guarding the set_turn_running(true) call so it only runs for live events.
There was a problem hiding this comment.
Addressed in fe86c57d4.
I routed TurnStarted through a replay-aware path: dispatch_event_msg now calls on_task_started_with_source(from_replay), and sleep inhibition is only enabled for live events (!from_replay). This keeps replay from creating macOS power assertions while preserving normal turn lifecycle behavior for live runs.
| name: "Prevent sleep while running", | ||
| menu_description: "Keep your computer awake while Codex is running a thread.", | ||
| announcement: "NEW: Prevent sleep while running is now available in /experimental.", |
There was a problem hiding this comment.
The /experimental text for this feature suggests it generally "prevents sleep" / "keeps your computer awake while Codex is running a thread", but the implementation targets caffeinate -i semantics: prevent idle system sleep only, and only while an active turn is running. Updating name/menu_description/announcement to reflect the narrower behavior would avoid user confusion about display sleep and the exact lifecycle being tied to turns.
| name: "Prevent sleep while running", | |
| menu_description: "Keep your computer awake while Codex is running a thread.", | |
| announcement: "NEW: Prevent sleep while running is now available in /experimental.", | |
| name: "Prevent idle system sleep during active turns", | |
| menu_description: "On macOS, prevent idle system sleep while Codex is actively running a turn.", | |
| announcement: "NEW: Prevent idle system sleep during active turns is now available in /experimental.", |
There was a problem hiding this comment.
Updated in fe86c57d4.
I changed the /experimental copy to reflect the actual semantics and lifecycle:
name:Prevent idle system sleep during active turnsmenu_description:On macOS, prevent idle system sleep while Codex is actively running a turn.announcement:NEW: Prevent idle system sleep during active turns is now available in /experimental.
There was a problem hiding this comment.
Follow-up: I adjusted this copy again in 90f7346e6 to align with the existing Mac app wording and avoid introducing new jargon. Current strings are:
Prevent sleep while runningKeep your computer awake while Codex is running a thread.NEW: Prevent sleep while running is now available in /experimental.
| FeatureSpec { | ||
| id: Feature::PreventIdleSleep, | ||
| key: "prevent_idle_sleep", | ||
| #[cfg(target_os = "macos")] |
There was a problem hiding this comment.
Instead of this, could you use a if cfg!(...). Check what is done for UnifiedExec
This is better because this allow full compilation locally.
There was a problem hiding this comment.
Good call. Updated this to use if cfg!(target_os = "macos") for the feature stage (matching the UnifiedExec pattern), so it compiles cleanly across targets.
|
|
||
| #[cfg(target_os = "macos")] | ||
| #[test] | ||
| fn prevent_idle_sleep_is_experimental_on_macos() { |
There was a problem hiding this comment.
Nice but not really useful and will just add effort when we land this. But it's personal opinion, feel free to ignore
There was a problem hiding this comment.
Agreed, I removed this test to keep the suite lean.
| @@ -0,0 +1,280 @@ | |||
| //! Cross-platform helper for preventing idle sleep while a turn is running. | |||
There was a problem hiding this comment.
Could we extract this in a small crate in codex-rs/utils/... ? I guess this can be re-used later
There was a problem hiding this comment.
Done. I extracted the implementation into a reusable crate at codex-rs/utils/sleep-inhibitor (codex-utils-sleep-inhibitor) and moved the sleep inhibition logic there.
| //! On macOS this uses native IOKit power assertions instead of spawning | ||
| //! `caffeinate`, so assertion lifecycle is tied directly to Rust object lifetime. | ||
|
|
||
| #[cfg(target_os = "macos")] |
There was a problem hiding this comment.
If everything is just for MacOS, it would be even easier if you move everything into a crate. You can put this in a file named something like macos_inhibitor and then in the lib.rs you do something like
#[cfg(target_os = "macos")]
pub mod macos_inhibitor;
(I let you adapt the names)
There was a problem hiding this comment.
Implemented this structure in the new crate: macOS-specific internals now live in a dedicated macos_inhibitor module, and the cross-platform SleepInhibitor API is exposed from crate lib.rs.
| self.on_task_started_with_source(false); | ||
| } | ||
|
|
||
| fn on_task_started_with_source(&mut self, from_replay: bool) { |
There was a problem hiding this comment.
This sounds unrelated... how the from_replay can have an impact here if set_turn_running is idempotent?
There was a problem hiding this comment.
Good point. I removed the from_replay gate and now always call set_turn_running(true) on TurnStarted; since it is idempotent, replay no longer changes behavior here.
Summary
codex-coresleep inhibitor that uses native macOS IOKit assertions (IOPMAssertionCreateWithName/IOPMAssertionRelease) instead of spawningcaffeinatetui(TurnStartedenables;TurnCompleteand abort/error finalization disable)/experimentalfeature toggle ([features].prevent_idle_sleep) instead of a dedicated[tui]config flag/experimentalon macOS; keep it under development on other platformsTesting
cargo check -p codex-core -p codex-tuicargo test -p codex-core sleep_inhibitor::tests -- --nocapturecargo test -p codex-core tui_config_missing_notifications_field_defaults_to_enabled -- --nocapturecargo test -p codex-core prevent_idle_sleep_is_ -- --nocaptureSemantics and API references
caffeinate -isemantics: prevent idle system sleep while allowing display idle sleep.caffeinate -imapping in Apple open source (assertionMap):kIdleAssertionFlag -> kIOPMAssertionTypePreventUserIdleSystemSleepCodex Electron vs this PR (full stack path)
powerSaveBlocker.start("prevent-app-suspension"):kPreventAppSuspension:kPreventAppSuspension -> kIOPMAssertionTypeNoIdleSleepkPreventDisplaySleep / kPreventDisplaySleepAllowDimming -> kIOPMAssertionTypeNoDisplaySleepWhy this PR uses a different macOS constant name
"PreventUserIdleSystemSleep"directly, viaIOPMAssertionCreateWithName, incodex-rs/core/src/sleep_inhibitor.rs.kIOPMAssertionTypeNoIdleSleepas deprecated and recommendskIOPMAssertPreventUserIdleSystemSleep/kIOPMAssertionTypePreventUserIdleSystemSleep:Future platform support
The architecture is intentionally set up for multi-platform extensions:
tui) only callsSleepInhibitor::set_turn_running(...)on turn lifecycle boundaries.codex-rs/core/src/sleep_inhibitor.rsbehindcfg(...)blocks.core/src/features.rsand surfaced via/experimental.Potential follow-up implementations:
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED)as baseline).PowerCreateRequest/PowerSetRequest/PowerClearRequestfor richer assertion semantics.org.freedesktop.login1.Manager.Inhibitwithwhat="sleep").This PR keeps the cross-platform API surface minimal so future PRs can add Windows/Linux support incrementally with low churn.