Skip to content

feat(tui): prevent macOS idle sleep while turns run - #11711

Merged
yvolovich-cyber merged 18 commits into
mainfrom
codex/macos-sleep-inhibitor-turn-lifecycle
Feb 13, 2026
Merged

yvolovich-cyber merged 18 commits into
mainfrom
codex/macos-sleep-inhibitor-turn-lifecycle

Conversation

@yvolovich-cyber

@yvolovich-cyber yvolovich-cyber commented Feb 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • add a shared codex-core sleep inhibitor that uses native macOS IOKit assertions (IOPMAssertionCreateWithName / IOPMAssertionRelease) instead of spawning caffeinate
  • wire sleep inhibition to turn lifecycle in tui (TurnStarted enables; TurnComplete and abort/error finalization disable)
  • gate this behavior behind a /experimental feature toggle ([features].prevent_idle_sleep) instead of a dedicated [tui] config flag
  • expose the toggle in /experimental on macOS; keep it under development on other platforms
  • keep behavior no-op on non-macOS targets
image

Testing

  • cargo check -p codex-core -p codex-tui
  • cargo test -p codex-core sleep_inhibitor::tests -- --nocapture
  • cargo test -p codex-core tui_config_missing_notifications_field_defaults_to_enabled -- --nocapture
  • cargo test -p codex-core prevent_idle_sleep_is_ -- --nocapture

Semantics and API references

Codex Electron vs this PR (full stack path)

Why this PR uses a different macOS constant name

Future platform support

The architecture is intentionally set up for multi-platform extensions:

  • UI code (tui) only calls SleepInhibitor::set_turn_running(...) on turn lifecycle boundaries.
  • Platform-specific behavior is isolated in codex-rs/core/src/sleep_inhibitor.rs behind cfg(...) blocks.
  • Feature exposure is centralized in core/src/features.rs and surfaced via /experimental.
  • Adding new OS backends should not require additional TUI wiring; only the backend internals and feature stage metadata need to change.

Potential follow-up implementations:

  • Windows:
    • Add a backend using Win32 power APIs (SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED) as baseline).
    • Optionally move to PowerCreateRequest / PowerSetRequest / PowerClearRequest for richer assertion semantics.
  • Linux:
    • Add a backend using logind inhibitors over D-Bus (org.freedesktop.login1.Manager.Inhibit with what="sleep").
    • Keep a no-op fallback where logind/D-Bus is unavailable.

This PR keeps the cross-platform API surface minimal so future PRs can add Windows/Linux support incrementally with low churn.

@github-actions

github-actions Bot commented Feb 13, 2026 •

Copy link
Copy Markdown
Contributor

All contributors have signed the CLA ✍️ ✅
Posted by the CLA Assistant Lite bot.

@yvolovich-cyber

Copy link
Copy Markdown
Contributor Author

I have read the CLA Document and I hereby sign the CLA

@yvolovich-cyber

Copy link
Copy Markdown
Contributor Author

recheck

github-actions Bot added a commit that referenced this pull request Feb 13, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 SleepInhibitor module in codex-core with macOS-specific IOKit FFI bindings
  • Integrated sleep inhibition into both tui and tui2 turn lifecycle hooks (TurnStarted, TurnComplete, error/abort handlers)
  • Added opt-in config field tui.prevent_sleep_while_running (defaults to false)

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.

Comment thread codex-rs/core/src/sleep_inhibitor.rs Outdated
let mut inhibitor = SleepInhibitor::new(true);
inhibitor.set_turn_running(true);
inhibitor.set_turn_running(false);
}

Copilot AI Feb 13, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The test coverage should include additional test cases to ensure robustness:

  1. Test with enabled: false to verify no assertions are created
  2. Test multiple calls to set_turn_running(true) to ensure idempotency
  3. 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.

Suggested change
}
}
#[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);
}

Copilot uses AI. Check for mistakes.

@yvolovich-cyber yvolovich-cyber Feb 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread codex-rs/core/src/sleep_inhibitor.rs Outdated
Comment on lines +39 to +43
if !self.enabled || !turn_running {
self.release();
return;
}
self.acquire();

Copilot AI Feb 13, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
if !self.enabled || !turn_running {
self.release();
return;
}
self.acquire();
if !self.enabled {
return;
}
if turn_running {
self.acquire();
} else {
self.release();
}

Copilot uses AI. Check for mistakes.

@yvolovich-cyber yvolovich-cyber Feb 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@yvolovich-cyber

Copy link
Copy Markdown
Contributor Author

/codex please review this PR

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@jif-oai

jif-oai commented Feb 13, 2026

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread codex-rs/core/src/config/types.rs Outdated
Comment on lines +540 to +541
#[serde(default)]
pub prevent_sleep_while_running: bool,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@yvolovich-cyber

Copy link
Copy Markdown
Contributor Author

@codex review

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +183 to +187
let handle = unsafe {
libc::dlopen(
IOKIT_FRAMEWORK_BINARY.as_ptr().cast(),
libc::RTLD_LOCAL | libc::RTLD_LAZY,
)

Copilot AI Feb 13, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Copilot uses AI. Check for mistakes.

@yvolovich-cyber yvolovich-cyber Feb 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@chatgpt-codex-connector

Copy link
Copy Markdown
Contributor

Codex Review: Didn't find any major issues. Delightful!

ℹ️ 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".

@yvolovich-cyber

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown
Contributor

Codex Review: Didn't find any major issues. Chef's kiss.

ℹ️ 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".

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines 1279 to 1282
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;

Copilot AI Feb 13, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread codex-rs/core/src/features.rs Outdated
Comment on lines +614 to +616
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.",

Copilot AI Feb 13, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Suggested change
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.",

Copilot uses AI. Check for mistakes.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated in fe86c57d4.

I changed the /experimental copy to reflect the actual semantics and lifecycle:

  • 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 running
  • Keep your computer awake while Codex is running a thread.
  • NEW: Prevent sleep while running is now available in /experimental.

Comment thread codex-rs/core/src/features.rs Outdated
FeatureSpec {
id: Feature::PreventIdleSleep,
key: "prevent_idle_sleep",
#[cfg(target_os = "macos")]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of this, could you use a if cfg!(...). Check what is done for UnifiedExec
This is better because this allow full compilation locally.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread codex-rs/core/src/features.rs Outdated

#[cfg(target_os = "macos")]
#[test]
fn prevent_idle_sleep_is_experimental_on_macos() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice but not really useful and will just add effort when we land this. But it's personal opinion, feel free to ignore

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, I removed this test to keep the suite lean.

Comment thread codex-rs/core/src/sleep_inhibitor.rs Outdated
@@ -0,0 +1,280 @@
//! Cross-platform helper for preventing idle sleep while a turn is running.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we extract this in a small crate in codex-rs/utils/... ? I guess this can be re-used later

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread codex-rs/core/src/sleep_inhibitor.rs Outdated
//! 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")]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread codex-rs/tui/src/chatwidget.rs Outdated
self.on_task_started_with_source(false);
}

fn on_task_started_with_source(&mut self, from_replay: bool) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This sounds unrelated... how the from_replay can have an impact here if set_turn_running is idempotent?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@jif-oai jif-oai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@yvolovich-cyber
yvolovich-cyber merged commit 32da5eb into main Feb 13, 2026
37 of 39 checks passed
@yvolovich-cyber
yvolovich-cyber deleted the codex/macos-sleep-inhibitor-turn-lifecycle branch February 13, 2026 18:31
@github-actions github-actions Bot locked and limited conversation to collaborators Feb 13, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants