Skip to content

CLI for SidePulse

Python

Handle closed-lid display sleep safely

Peter Kuhar48a04b86f33d
diff --git a/README.md b/README.md
index 0832d70..5d80e1e 100644
--- a/README.md
+++ b/README.md
@@ -643,6 +643,10 @@ and shows the path from provider hook event to interpreted SidePulse status.
The `Keep Awake With Lid Closed` menu section controls the stronger sleep
prevention policy:
+The intended closed-lid behavior, including the distinction between macOS
+clamshell mode and SidePulse's no-external-display fallback, is documented in
+[`docs/design/closed-lid-power.md`](docs/design/closed-lid-power.md).
+
| Choice | Behavior |
| --- | --- |
| Never | Do not use the closed-lid sleep override. |
diff --git a/docs/design/closed-lid-power.md b/docs/design/closed-lid-power.md
new file mode 100644
index 0000000..d6b141d
--- /dev/null
+++ b/docs/design/closed-lid-power.md
@@ -0,0 +1,74 @@
+# Closed-lid power management
+
+## Goal
+
+Keep active agent work running while a MacBook lid is closed without changing
+an attached external display. The built-in display is the only display that may
+be put to sleep by SidePulse.
+
+## Policy
+
+- **Clamshell eligible** — the lid is closed, an external display is in use,
+ the Mac has power, and its input accessories have been approved by macOS.
+ Let macOS run clamshell mode. SidePulse keeps its normal `caffeinate -ims`
+ assertion while agent work is active, but does not set `disablesleep` and
+ does not request display sleep.
+- **No external display, active agents** — pre-arm
+ `pmset -a disablesleep 1` while the awake request is active, so macOS cannot
+ sleep before the lid transition is observed. Once the lid is confirmed
+ closed, issue `pmset displaysleepnow`. The former keeps the Mac awake; the
+ latter lets the display sleep. Do not use `caffeinate -d` or `caffeinate -u`,
+ which prevent or wake display sleep.
+- **No external display, no active agents** — release the SidePulse
+ `disablesleep` override and allow macOS to sleep normally.
+
+`pmset displaysleepnow` is intentionally used only when no external display is
+active: it is a global display-sleep request and cannot target only the
+built-in panel.
+
+SidePulse must not directly change framebuffer or panel power state. Those
+private calls interfere with WindowServer's own lid-handling sequence.
+
+## Crash history
+
+A previous implementation called the private
+`IOMobileFramebufferRequestPowerChange` API when the lid closed. WindowServer
+then repeatedly failed its userspace watchdog check-in and was restarted. That
+implementation was removed. This design uses only `pmset` and normal macOS
+clamshell behavior.
+
+## State flow
+
+```mermaid
+flowchart TD
+ A[Lid closes] --> B{External display and power?}
+
+ B -- Yes --> C[macOS clamshell mode]
+ C --> D[caffeinate only]
+ D --> E[Agents run; external display stays on]
+
+ B -- No --> F{Agents active?}
+ F -- No --> G[Normal macOS sleep]
+ F -- Yes --> H[disablesleep = 1]
+ H --> I[displaysleepnow]
+ I --> J[Agents run; built-in display sleeps]
+
+ E --> K[Lid, display, power, or agent state changes]
+ J --> K
+ G --> K
+ K --> L[Re-evaluate]
+```
+
+## Detection and transitions
+
+Determine external-display presence from the CoreGraphics online display list,
+not from `system_profiler`. A display that is not `CGDisplayIsBuiltin` counts
+as external only when it is active. Re-evaluate after lid, power, and agent
+updates, as well as each periodic status refresh. Treat a display-query failure
+as unknown and do not issue `displaysleepnow` in that case.
+
+Keep the no-external-display override armed until the awake request ends; this
+avoids a race if the lid is closed again while agents are still working. Release
+it when the request ends, or when an external display is active and the Mac has
+power for clamshell mode. Do not explicitly wake a display; macOS handles that
+through normal user activity and clamshell transitions.
diff --git a/src/sidepulse/lid_sleep.py b/src/sidepulse/lid_sleep.py
index 8ae08af..2344ace 100644
--- a/src/sidepulse/lid_sleep.py
+++ b/src/sidepulse/lid_sleep.py
@@ -21,6 +21,7 @@ CAFFEINATE_CLOSED_LID_COMMAND = ("/usr/bin/caffeinate", "-ims")
IOREG_CLAMSHELL_COMMAND = ("/usr/sbin/ioreg", "-r", "-k", "AppleClamshellState", "-d", "4")
IOREG_SLEEP_DISABLED_COMMAND = ("/usr/sbin/ioreg", "-r", "-k", "SleepDisabled", "-d", "4")
PMSET_ASSERTIONS_COMMAND = ("/usr/bin/pmset", "-g", "assertions")
+PMSET_DISPLAY_SLEEP_NOW_COMMAND = ("/usr/bin/pmset", "displaysleepnow")
SUDO_PMSET_DISABLE_SLEEP_COMMAND = (
"/usr/bin/sudo",
"-n",
@@ -48,6 +49,10 @@ class SleepHelperRequiredError(RuntimeError):
pass
+class DisplaySleepRequestError(RuntimeError):
+ pass
+
+
@dataclass(frozen=True)
class MacSleepSnapshot:
sleep_disabled: bool | None = None
@@ -95,6 +100,32 @@ def read_lid_closed(
return parse_bool_ioreg_property(result.stdout, "AppleClamshellState")
+def external_display_is_active() -> bool | None:
+ """Return whether CoreGraphics has an active non-built-in display.
+
+ ``None`` means that macOS could not provide a trustworthy display list. A
+ caller must treat that as unknown rather than risk sleeping an external
+ display with the global ``pmset displaysleepnow`` request.
+ """
+ try:
+ from Quartz import (
+ CGDisplayIsActive,
+ CGDisplayIsBuiltin,
+ CGGetOnlineDisplayList,
+ )
+
+ error, display_ids, count = CGGetOnlineDisplayList(32, None, None)
+ except Exception:
+ return None
+ if error != 0:
+ return None
+ return any(
+ not bool(CGDisplayIsBuiltin(display_id))
+ and bool(CGDisplayIsActive(display_id))
+ for display_id in display_ids[:count]
+ )
+
+
def read_sleep_disabled(
*,
runner: CommandRunner = subprocess.run,
@@ -208,6 +239,26 @@ def run_sudo_pmset_disablesleep(
)
+def run_pmset_displaysleepnow(
+ *,
+ runner: CommandRunner = subprocess.run,
+) -> None:
+ """Request normal macOS display sleep without changing panel power state."""
+ result = runner(
+ list(PMSET_DISPLAY_SLEEP_NOW_COMMAND),
+ check=False,
+ capture_output=True,
+ text=True,
+ timeout=5,
+ )
+ if result.returncode == 0:
+ return
+ detail = (result.stderr or result.stdout or "").strip()
+ if detail:
+ detail = f" ({detail.splitlines()[0]})"
+ raise DisplaySleepRequestError(f"pmset displaysleepnow failed{detail}")
+
+
def run_privileged_pmset_disablesleep(
enabled: bool,
*,
@@ -349,6 +400,7 @@ class ClosedLidAwakeController:
sleep_disabled_setter: Callable[[bool], None] = run_sudo_pmset_disablesleep,
watch_current_process: bool = True,
use_system_disable: bool = False,
+ use_caffeinate: bool = True,
) -> None:
self.command = tuple(command)
self.process_factory = process_factory or subprocess.Popen
@@ -356,6 +408,7 @@ class ClosedLidAwakeController:
self.sleep_disabled_setter = sleep_disabled_setter
self.watch_current_process = watch_current_process
self.use_system_disable = use_system_disable
+ self.use_caffeinate = use_caffeinate
self.process = None
self.changed_system_disable = False
self.system_disable_attempted = False
@@ -402,7 +455,7 @@ class ClosedLidAwakeController:
except Exception as exc:
errors.append(f"disablesleep: {exc}")
- if not self.process_running():
+ if self.use_caffeinate and not self.process_running():
try:
self.process = self.process_factory(
self.caffeinate_command(),
@@ -458,6 +511,9 @@ class ClosedLidAwakeController:
def active(self) -> bool:
return self.process_running() or self.changed_system_disable
+ def system_disable_active(self) -> bool:
+ return self.last_system_disable_request is True
+
def process_running(self) -> bool:
return self.process is not None and self.process.poll() is None
diff --git a/src/sidepulse/status_bar.py b/src/sidepulse/status_bar.py
index adc2652..5894399 100644
--- a/src/sidepulse/status_bar.py
+++ b/src/sidepulse/status_bar.py
@@ -141,8 +141,10 @@ from .lid_sleep import (
LID_POLL_SECONDS,
ClosedLidAwakeController,
MacSleepSnapshot,
+ external_display_is_active,
read_lid_closed,
read_mac_sleep_snapshot,
+ run_pmset_displaysleepnow,
sleep_helper_install_command,
sleep_helper_installed,
)
@@ -508,6 +510,20 @@ def lid_close_animation_should_run(
return True
+def closed_lid_display_sleep_should_request(
+ *,
+ lid_closed: bool | None,
+ external_display_active: bool | None,
+ system_sleep_disabled: bool,
+) -> bool:
+ """Only sleep displays when it cannot affect an external monitor."""
+ return (
+ lid_closed is True
+ and external_display_active is False
+ and system_sleep_disabled
+ )
+
+
def sleep_prevention_battery_safeguard(
snapshot: BatterySnapshot | None,
threshold_percent: float,
@@ -609,6 +625,7 @@ class StatusBarController(NSObject):
self.keep_awake = KeepAwakeController()
self.closed_lid_awake = ClosedLidAwakeController(
use_system_disable=sleep_helper_installed(),
+ use_caffeinate=False,
)
self.last_keep_awake_error = None
self.last_closed_lid_awake_error = None
@@ -633,6 +650,7 @@ class StatusBarController(NSObject):
self.pending_lid_closed = None
self.pending_lid_error = None
self.lid_closed_led_hold_active = False
+ self.closed_lid_display_sleep_requested = False
self.led_animation_until_monotonic = 0.0
self.led_animation_token = 0
self.virtual_status_device = VirtualStatusDevice.alloc().init()
@@ -3416,11 +3434,13 @@ class StatusBarController(NSObject):
self.lid_poll_backoff_until_monotonic = 0.0
if self.last_lid_closed is None:
self.last_lid_closed = closed
+ self.sync_closed_lid_awake()
return
if closed == self.last_lid_closed:
return
self.last_lid_closed = closed
+ self.sync_closed_lid_awake()
kind = LID_ANIMATION_CLOSED if closed else LID_ANIMATION_OPEN
log_status_bar(f"lid_state={'closed' if closed else 'open'}")
if closed:
@@ -3529,9 +3549,18 @@ class StatusBarController(NSObject):
def sync_closed_lid_awake(self, *, agents_active: bool | None = None) -> None:
was_active = self.closed_lid_awake.active()
- self.closed_lid_awake.set_use_system_disable(sleep_helper_installed())
+ external_display_active = external_display_is_active()
+ battery_snapshot = getattr(self, "last_battery_snapshot", None)
+ clamshell_eligible = bool(
+ external_display_active is True
+ and battery_snapshot is not None
+ and battery_snapshot.is_plugged
+ )
+ self.closed_lid_awake.set_use_system_disable(
+ sleep_helper_installed() and not clamshell_eligible
+ )
policy = self.settings.sleep_prevention_policy
- if self.battery_sleep_safeguard_active:
+ if self.battery_sleep_safeguard_active or clamshell_eligible:
policy = SLEEP_PREVENTION_NEVER
self.closed_lid_awake.update(
policy,
@@ -3550,6 +3579,24 @@ class StatusBarController(NSObject):
f"closed_lid_awake error: {self.last_closed_lid_awake_error}"
)
+ should_sleep_display = closed_lid_display_sleep_should_request(
+ lid_closed=getattr(self, "last_lid_closed", None),
+ external_display_active=external_display_active,
+ system_sleep_disabled=self.closed_lid_awake.system_disable_active(),
+ )
+ if not should_sleep_display:
+ self.closed_lid_display_sleep_requested = False
+ return
+ if getattr(self, "closed_lid_display_sleep_requested", False):
+ return
+ try:
+ run_pmset_displaysleepnow()
+ self.closed_lid_display_sleep_requested = True
+ log_status_bar("lid_display_sleep=requested")
+ except Exception as exc:
+ self.closed_lid_display_sleep_requested = False
+ log_status_bar(f"lid_display_sleep error: {exc}")
+
def status_keepalive_targets(self) -> list[Path]:
targets = self.current_led_targets()
if targets:
diff --git a/tests/test_sidepulse.py b/tests/test_sidepulse.py
index b50205f..26c047a 100644
--- a/tests/test_sidepulse.py
+++ b/tests/test_sidepulse.py
@@ -76,14 +76,17 @@ from sidepulse.led_status import (
)
from sidepulse.lid_sleep import (
ClosedLidAwakeController,
+ DisplaySleepRequestError,
IOREG_SLEEP_DISABLED_COMMAND,
MacSleepSnapshot,
PMSET_ASSERTIONS_COMMAND,
SleepHelperRequiredError,
closed_lid_awake_should_hold,
+ external_display_is_active,
parse_bool_ioreg_property,
parse_pmset_assertions,
read_mac_sleep_snapshot,
+ run_pmset_displaysleepnow,
run_sudo_pmset_disablesleep,
sleep_helper_sudoers_rule,
)
@@ -5125,6 +5128,48 @@ class AgentMonitorTests(unittest.TestCase):
)
)
+ def test_lid_display_sleep_never_runs_with_an_external_or_unknown_display(self) -> None:
+ try:
+ from sidepulse import status_bar
+ except SystemExit as exc:
+ self.skipTest(str(exc))
+
+ self.assertTrue(
+ status_bar.closed_lid_display_sleep_should_request(
+ lid_closed=True,
+ external_display_active=False,
+ system_sleep_disabled=True,
+ )
+ )
+ self.assertFalse(
+ status_bar.closed_lid_display_sleep_should_request(
+ lid_closed=True,
+ external_display_active=True,
+ system_sleep_disabled=True,
+ )
+ )
+ self.assertFalse(
+ status_bar.closed_lid_display_sleep_should_request(
+ lid_closed=True,
+ external_display_active=None,
+ system_sleep_disabled=True,
+ )
+ )
+ self.assertFalse(
+ status_bar.closed_lid_display_sleep_should_request(
+ lid_closed=False,
+ external_display_active=False,
+ system_sleep_disabled=True,
+ )
+ )
+ self.assertFalse(
+ status_bar.closed_lid_display_sleep_should_request(
+ lid_closed=True,
+ external_display_active=False,
+ system_sleep_disabled=False,
+ )
+ )
+
def test_lid_poll_enables_hold_on_close_and_clears_it_on_open(self) -> None:
try:
from sidepulse import status_bar
@@ -5487,6 +5532,22 @@ class AgentMonitorTests(unittest.TestCase):
self.assertTrue(controller.process_running())
self.assertFalse(controller.changed_system_disable)
+ def test_closed_lid_awake_controller_can_skip_duplicate_caffeinate(self) -> None:
+ disabled_calls: list[bool] = []
+ controller = ClosedLidAwakeController(
+ process_factory=lambda *_args, **_kwargs: FakeProcess(),
+ sleep_disabled_setter=disabled_calls.append,
+ use_system_disable=True,
+ use_caffeinate=False,
+ )
+
+ self.assertTrue(
+ controller.update(CLOSED_LID_AWAKE_ALWAYS, agents_active=False)
+ )
+ self.assertEqual(disabled_calls, [True])
+ self.assertFalse(controller.process_running())
+ self.assertTrue(controller.system_disable_active())
+
def test_closed_lid_awake_controller_drives_existing_system_disable(self) -> None:
disabled_calls: list[bool] = []
controller = ClosedLidAwakeController(
@@ -5552,6 +5613,45 @@ class AgentMonitorTests(unittest.TestCase):
self.assertIn("install-sleep-helper", str(ctx.exception))
self.assertNotIn("/usr/bin/osascript", calls[0])
+ def test_display_sleep_request_uses_the_supported_pmset_command(self) -> None:
+ calls = []
+
+ def runner(command, **kwargs):
+ calls.append((command, kwargs))
+ return subprocess.CompletedProcess(command, 0, "", "")
+
+ run_pmset_displaysleepnow(runner=runner)
+
+ self.assertEqual(calls[0][0], ["/usr/bin/pmset", "displaysleepnow"])
+ self.assertEqual(calls[0][1]["check"], False)
+
+ def test_display_sleep_request_reports_failure(self) -> None:
+ def runner(command, **_kwargs):
+ return subprocess.CompletedProcess(command, 1, "", "not allowed")
+
+ with self.assertRaises(DisplaySleepRequestError) as ctx:
+ run_pmset_displaysleepnow(runner=runner)
+
+ self.assertIn("not allowed", str(ctx.exception))
+
+ def test_external_display_detector_requires_an_active_non_builtin_display(self) -> None:
+ quartz = SimpleNamespace(
+ CGGetOnlineDisplayList=lambda *_args: (0, (1, 2, 3), 3),
+ CGDisplayIsBuiltin=lambda display_id: display_id == 1,
+ CGDisplayIsActive=lambda display_id: display_id == 2,
+ )
+ with patch.dict(sys.modules, {"Quartz": quartz}):
+ self.assertTrue(external_display_is_active())
+
+ def test_external_display_detector_returns_unknown_on_failure(self) -> None:
+ quartz = SimpleNamespace(
+ CGGetOnlineDisplayList=lambda *_args: (1, (), 0),
+ CGDisplayIsBuiltin=lambda _display_id: False,
+ CGDisplayIsActive=lambda _display_id: True,
+ )
+ with patch.dict(sys.modules, {"Quartz": quartz}):
+ self.assertIsNone(external_display_is_active())
+
def test_sleep_helper_sudoers_rule_is_narrow(self) -> None:
self.assertEqual(
sleep_helper_sudoers_rule("pero"),