# Vorssaint-utils Bluetooth Sleep Toggle Logic: Power-State-Aware Energy Management

> Discover how Vorssaint-utils's Bluetooth sleep toggle intelligently manages power. Learn about its logic for turning Bluetooth off on Mac sleep and restoring it on wake.

- Repository: [vorssaint/vorssaint-utils](https://github.com/vorssaint/vorssaint-utils)
- Tags: internals
- Published: 2026-09-12

---

**Vorssaint-utils implements a power-state-aware Bluetooth sleep feature that turns Bluetooth off when your Mac sleeps and conditionally restores it on wake, respecting both the current power state and user preferences through an idempotent decision engine.**

The Bluetooth sleep toggle logic in Vorssaint-utils provides intelligent energy management for macOS devices by coordinating system sleep events with Bluetooth radio state. This open-source utility uses a decoupled architecture where `BluetoothSleepSupport` encapsulates the pure logic for determining when to power down and restore Bluetooth, intentionally remaining free of AppKit or IOKit dependencies to ensure complete unit-testability.

## The Sleep Planning Algorithm

When the system initiates sleep, `BluetoothSleepService` queries `BluetoothSleepSupport` for a deterministic `SleepPlan`. According to the implementation in [`Sources/Vorssaint/Services/Bluetooth/BluetoothSleepSupport.swift`](https://github.com/vorssaint/vorssaint-utils/blob/main/Sources/Vorssaint/Services/Bluetooth/BluetoothSleepSupport.swift), the `sleepPlan(isPoweredOn:restoresOnWake:)` function evaluates the current power state and user preferences to generate the plan:

- **If Bluetooth is already off** (`isPoweredOn == false`), the function returns `SleepPlan(powersOff: false, owesRestore: false)`. The feature makes no changes because the user has already disabled Bluetooth, and no restoration obligation is recorded.

- **If Bluetooth is currently on** (`isPoweredOn == true`), the function returns `SleepPlan(powersOff: true, owesRestore: restoresOnWake)`. This instructs the service to power down Bluetooth immediately, with the restoration flag set conditionally based on the user's "restore on wake" preference stored under `DefaultsKey.bluetoothSleepRestoreOnWake`.

This conditional logic ensures the feature only acts when necessary, avoiding redundant state changes and respecting the user's pre-sleep configuration.

## Wake Restoration and User Intent Preservation

Upon wake, the system evaluates whether to re-enable Bluetooth using the `restores(owesRestore:isPoweredOn:)` method. The function returns `true` only when two specific conditions are met simultaneously:

1. A restore is pending (`owesRestore == true`), indicating the feature previously powered off Bluetooth with the intent to restore it.
2. Bluetooth remains off (`isPoweredOn == false`), confirming the user has not manually intervened.

If the user manually enabled Bluetooth while the Mac was asleep, `isPoweredOn` becomes `true` and the function returns `false`, clearing the pending restore flag in `UserDefaults` without modifying the state. This design guarantees the feature never overrides a user-initiated change, preserving manual overrides across sleep/wake cycles and preventing "fighting" with the user's explicit actions.

## Idempotent State Management

The implementation stores the pending restore flag in `UserDefaults` using the key `DefaultsKey.bluetoothSleepRestorePending`, ensuring the obligation survives app restarts or unexpected shutdowns. The architecture maintains **idempotence**: the feature only undoes actions it performed itself.

When `BluetoothSleepService` detects a wake event or launches to find a pending restore, it synchronizes with preferences and executes the restoration only if the power state matches the expected "off" condition. This prevents the utility from re-enabling Bluetooth that was explicitly disabled by the user or another system process during sleep.

## Implementation Example

Developers integrating this logic or debugging the feature can examine the decision flow directly using the pure functions provided by `BluetoothSleepSupport`:

```swift
import Vorssaint

// Simulate pre-sleep state: Bluetooth is on, user wants restore on wake
let plan = BluetoothSleepSupport.sleepPlan(
    isPoweredOn: true,
    restoresOnWake: true
)

// plan.powersOff == true, plan.owesRestore == true
print("Should power off: \(plan.powersOff)")
print("Owes restore: \(plan.owesRestore)")

```

For wake evaluation, verify the restoration guard:

```swift
// Check if we should restore (owed and still off)
let shouldRestore = BluetoothSleepSupport.restores(
    owesRestore: true,
    isPoweredOn: false
)

// Returns true only when restore is owed and Bluetooth is still off
if shouldRestore {
    // Execute Bluetooth power on
}

```

The `BluetoothSleepService` orchestrates these calls automatically, persisting the `owesRestore` flag to `UserDefaults` via `syncWithPreferences()` and clearing it after successful restoration or when manual intervention is detected.

## Summary

- The `BluetoothSleepSupport` class in [`Sources/Vorssaint/Services/Bluetooth/BluetoothSleepSupport.swift`](https://github.com/vorssaint/vorssaint-utils/blob/main/Sources/Vorssaint/Services/Bluetooth/BluetoothSleepSupport.swift) provides pure, testable logic for determining Bluetooth state changes during sleep/wake cycles.
- The `sleepPlan(isPoweredOn:restoresOnWake:)` function only powers off Bluetooth when it is currently on, recording whether restoration is required based on the `restoresOnWake` parameter.
- Wake restoration via `restores(owesRestore:isPoweredOn:)` occurs only if Bluetooth remains off and a restore flag is pending, preventing conflicts with manual user toggles.
- State persistence through `UserDefaults` ensures reliable behavior across system shutdowns and app restarts while maintaining idempotent operations.

## Frequently Asked Questions

### How does Vorssaint-utils prevent restoring Bluetooth if I turned it back on manually?

The `restores(owesRestore:isPoweredOn:)` function checks the current power state before executing any wake restoration. If `isPoweredOn` is `true` when the Mac wakes, the function returns `false` and clears the pending flag without changing Bluetooth state, respecting your manual intervention even if it occurred while the system was asleep.

### Where is the "restore on wake" preference stored?

The preference is stored in `UserDefaults` under `DefaultsKey.bluetoothSleepRestoreOnWake`, accessible via the settings UI in [`Sources/Vorssaint/UI/Settings/SettingsView.swift`](https://github.com/vorssaint/vorssaint-utils/blob/main/Sources/Vorssaint/UI/Settings/SettingsView.swift). The corresponding pending restore flag uses `DefaultsKey.bluetoothSleepRestorePending` to track obligations across sleep cycles in `BluetoothSleepService`.

### What happens if my Mac shuts down while asleep with a pending restore?

Because `BluetoothSleepSupport` persists the `owesRestore` flag to `UserDefaults` via `BluetoothSleepService` before the system sleeps, the obligation survives shutdowns. When Vorssaint-utils launches after the next boot, the service checks for pending restores and evaluates the current Bluetooth state, restoring power only if appropriate according to the idempotent logic.

### Why is BluetoothSleepSupport separated from BluetoothSleepService?

The separation isolates decision logic from IOKit and AppKit dependencies, allowing `BluetoothSleepSupport` to remain a pure Swift type with 100% unit-testable logic. `BluetoothSleepService` handles the OS-specific sleep/wake notifications and `UserDefaults` persistence, while `BluetoothSleepSupport` provides deterministic state calculations without side effects.