diff --git a/.gitignore b/.gitignore index 2f7896d..3e8e408 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ target/ +.claude/ diff --git a/AGENTS.md b/AGENTS.md index 25db846..78c4b96 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,16 +8,45 @@ behavior must stay output-compatible with it unless a deliberate difference is d ## Layout -- `src/bin/sidepulse-hook.rs` is the hook entry point. It must always exit 0 and print nothing. -- `src/hook.rs` handles payload formatting, routing and the main flow (`hook.py`). -- `src/origin.rs` detects which app launched the agent (`origin.py`), using native process +This is a Cargo workspace. `crates/sidepulse-core` holds the shared logic, `crates/sidepulse-hook` +the per-event hook binary, and `crates/sidepulse-bar` the AppKit menu-bar app. Keep AppKit out of +core and the hook, so the hook stays small and fast to start. + +Core modules (`crates/sidepulse-core/src/`): + +- `crates/sidepulse-hook/src/main.rs` is the hook entry point. It must always exit 0 and print nothing. +- `hook.rs` handles payload formatting, routing and the main flow (`hook.py`). +- `origin.rs` detects which app launched the agent (`origin.py`), using native process ancestry with no subprocesses. -- `src/providers.rs` holds event names, payload normalization and log-path detection (`providers.py`). -- `src/collector.rs` holds the per-event status rules (the matching parts of `collector.py`). -- `src/audit.rs`, `src/logrot.rs` and `src/ipc.rs` port the audit record, rotating JSONL appends +- `providers.rs` holds event names, payload normalization and log-path detection (`providers.py`). +- `collector.rs` holds the per-event status rules (the matching parts of `collector.py`). +- `audit.rs`, `logrot.rs` and `ipc.rs` port the audit record, rotating JSONL appends and the event-socket client. -- `src/pyjson.rs` reproduces Python's JSON and string semantics so records match byte for byte. -- `scripts/parity.py` is the differential harness against the Python hook. +- `pyjson.rs` reproduces Python's JSON and string semantics so records match byte for byte. +- `monitor.rs` holds the live agent state: ingest, snapshot, aggregate and a bounded `latest.json`. +- `devices.rs`, `battery.rs`, `lid.rs` and `power.rs` handle LED programs and writes, battery and + lid reads, and keep-awake and keepalive, all native with no subprocesses. + +Bar modules (`crates/sidepulse-bar/src/`): + +- `app.rs` holds the main-thread state and refresh logic. +- `ui.rs` covers the status item and menu. +- `led.rs` is the LED worker thread. +- `server.rs` is the event socket. +- `session.rs` handles session rows and open actions. +- `settings.rs` reads and writes `settings.json` and keeps keys this port doesn't use. + +`scripts/parity.py` is the differential harness against the Python hook. + +## Efficiency rules + +- Don't add polling where a notification or event exists. Every timer needs a reason and a + tolerance. +- Don't spawn subprocesses on hot or periodic paths. Use IOKit, IOPM or libc. +- Keep state bounded, and debounce writes to disk. +- Never do I/O to the SD card on the main thread. +- Measure the RSS/footprint and CPU of a release build before and after any change that claims a + performance gain, and update the README tables. ## Commands @@ -47,7 +76,8 @@ All four must pass before a commit. CI (`.github/workflows/ci.yml`) runs them on the PR. 5. **Privacy.** Hook payloads contain prompts, file paths and tool output. Never commit real hook logs, corpora, parity output or screenshots of them. Tests use synthetic data only. -6. **Unsafe code** is allowed only for libc system calls. Each block needs a `// SAFETY:` comment - explaining why the call is sound. +6. **Unsafe code** is allowed only for system interfaces: libc, IOKit, CoreFoundation and IOPM FFI + (`crates/sidepulse-core/src/power/iokit.rs`), and objc2/AppKit calls in `sidepulse-bar`. Each + block needs a `// SAFETY:` comment explaining why the call is sound. 7. **Scope.** Keep changes small and focused, and follow the phase plan in the README. Update the README's tables and commands whenever behavior, performance claims or setup steps change. diff --git a/Cargo.lock b/Cargo.lock index b54b49d..6a8a371 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -32,6 +32,15 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -71,6 +80,18 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags", + "block2", + "libc", + "objc2", +] + [[package]] name = "equivalent" version = "1.0.3" @@ -230,6 +251,158 @@ dependencies = [ "autocfg", ] +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags", + "block2", + "libc", + "objc2", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-core-image", + "objc2-core-text", + "objc2-core-video", + "objc2-foundation", + "objc2-quartz-core", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c" +dependencies = [ + "bitflags", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-data" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa" +dependencies = [ + "bitflags", + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags", + "dispatch2", + "objc2", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "bitflags", + "dispatch2", + "objc2", + "objc2-core-foundation", + "objc2-io-surface", +] + +[[package]] +name = "objc2-core-image" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006" +dependencies = [ + "objc2", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-text" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" +dependencies = [ + "bitflags", + "objc2", + "objc2-core-foundation", + "objc2-core-graphics", +] + +[[package]] +name = "objc2-core-video" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d425caf1df73233f29fd8a5c3e5edbc30d2d4307870f802d18f00d83dc5141a6" +dependencies = [ + "bitflags", + "objc2", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-io-surface", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags", + "block2", + "libc", + "objc2", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags", + "objc2", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags", + "objc2", + "objc2-foundation", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -371,8 +544,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" [[package]] -name = "sidepulse" -version = "0.1.0" +name = "sidepulse-bar" +version = "0.2.0" +dependencies = [ + "block2", + "chrono", + "dispatch2", + "libc", + "objc2", + "objc2-app-kit", + "objc2-foundation", + "regex", + "serde_json", + "sidepulse-core", + "tempfile", +] + +[[package]] +name = "sidepulse-core" +version = "0.2.0" dependencies = [ "chrono", "libc", @@ -383,6 +573,13 @@ dependencies = [ "tempfile", ] +[[package]] +name = "sidepulse-hook" +version = "0.2.0" +dependencies = [ + "sidepulse-core", +] + [[package]] name = "slab" version = "0.4.12" diff --git a/Cargo.toml b/Cargo.toml index 5922ebd..fd9931c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,32 +1,22 @@ -[package] -name = "sidepulse" -version = "0.1.0" +[workspace] +resolver = "2" +members = ["crates/sidepulse-core", "crates/sidepulse-hook", "crates/sidepulse-bar"] + +[workspace.package] +version = "0.2.0" edition = "2021" rust-version = "1.85" -description = "Unofficial native (Rust) port of SidePulse agent-status components, starting with the agent hook." license = "MIT" repository = "https://github.com/ckorhonen/sidepulse-rust" -readme = "README.md" -keywords = ["sidepulse", "claude-code", "codex", "hooks", "macos"] publish = false -[lib] -name = "sidepulse" -path = "src/lib.rs" - -[[bin]] -name = "sidepulse-hook" -path = "src/bin/sidepulse-hook.rs" - -[dependencies] +[workspace.dependencies] chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } libc = "0.2" regex = "1" serde_json = { version = "1", features = ["preserve_order"] } shlex = "1" socket2 = { version = "0.5", features = ["all"] } - -[dev-dependencies] tempfile = "3" [profile.release] diff --git a/README.md b/README.md index 5f5eec0..e80ac56 100644 --- a/README.md +++ b/README.md @@ -29,8 +29,90 @@ Measured on an M3 Max under heavy unrelated load. Expect lower absolute numbers | Phase | Component | Status | |---|---|---| | 1 | `sidepulse-hook`: drop-in replacement for `sidepulse/hook_entry.py` | Done | -| 2 | Status-bar core: event socket, bounded `latest.json`, lid and battery state via IOKit | Planned | -| 3 | Menu-bar UI and LED writer | Planned | +| 2 | Status-bar core: event socket, bounded `latest.json`, lid and battery state via IOKit | Done | +| 3 | `sidepulse-bar`: menu bar, LED output, battery display, keep-awake, lid animations | Done | +| 4 | Setup and Settings windows, Screen Bar, eject-guard installer | Not started (use the Python CLI) | + +## `sidepulse-bar` + +A native replacement for the Python menu-bar app (`python -m sidepulse status-bar`). It reads and +writes the same files, so you can switch back and forth: `settings.json`, `latest.json`, the hook logs +and `events.sock`. + +| Same workload, live on an M3 Max | Python app | Rust app | +|---|---|---| +| Memory footprint | 509 MB (grows over days) | **29 MB** (peak 31 MB) | +| CPU at idle | 3–21% | **~0%** | +| Child processes | `ioreg` every second, plus `caffeinate` and `touch` | none (only `sudo -n pmset` for the optional closed-lid helper) | + +Removing the polling timers (see "Event-driven, no polling" below) cut idle wakeups by 75–90%. These +are release builds on an M3 Max under unrelated load, idle for 120 s, with temporary state. The +wakeups are interrupt wakeups from `proc_pid_rusage`, because `top`'s IDLEW column reads 0 on a busy +machine. + +| Idle, 120 s window | Polling (phase 2) | Event-driven | +|---|---|---| +| Wakeups, `SIDEPULSE_VOLUMES` (5 s fallback rescan) | 1.08/s | **0.27/s** | +| Wakeups, real `/Volumes` with `SIDEPULSE_DRY_RUN=1` | not measured (would write to the device) | **0.13/s** (2 of them are keepalive touches) | +| CPU per minute | 21 ms | **2.5 ms** (real `/Volumes`), 5.7 ms (`SIDEPULSE_VOLUMES`) | +| Memory footprint | 13 MB | **13–14 MB** (24 MB in both after replaying 412 real hook records) | + +What makes the difference: + +- **Bounded state.** `latest.json` keeps statuses from the last 6 hours, at most 256. It's written as + compact JSON at most every 2 seconds instead of on every event. The Python app's file had grown to + 10k statuses and 12.6 MB, rewritten with indentation on every hook event. +- **Native system reads.** Battery and adapter data come from IOKit (about 0.4 ms) and the lid state + from `IOPMrootDomain` (about 16 µs), instead of spawning `ioreg` (about 50 ms each, 86,400 times a + day for the lid alone). +- **Native power control.** Keep-awake uses IOPM assertions instead of a `caffeinate` child, and + keepalive touches use `utimes` instead of `/usr/bin/touch`. +- **Event-driven, no polling.** The socket thread blocks in `accept`; Python woke every 0.5 s. Every + other input is a notification on the main run loop: the lid via `IOPMrootDomain` interest + messages (`kIOPMMessageClamshellStateChange`), plug, unplug and charge changes via + `IOPSNotificationCreateRunLoopSource`, volumes via `NSWorkspace` mount, unmount and rename + notifications, and SIGTERM/SIGINT via dispatch signal sources. Time-based changes (a finished + session hiding after 90 s, a post-tool status turning done at 120 s, staleness after an hour, the + end of the 5-minute keep-awake grace) are computed ahead and armed as a single one-shot timer. + `latest.json` is written once, 2 s after the first change of a burst, and on shutdown. The menu is + refilled when it opens (so session ages are current) and otherwise only when its contents change. +- **Exact LED worker sleeps.** The LED thread sleeps until the next keepalive touch is due (60 s + after each volume's last one) or the next charging-pulse rewrite, instead of waking every 20 s. +- **No blocking writes.** A single LED worker thread owns every SD-card write, so a sleeping card + never stalls the menu bar. The newest request always wins (Python dropped a sync that arrived while + one was in flight), and the charging pulse is rewritten at its intended wattage-based cadence + instead of every 15 s. + +Install it as the login agent in place of the Python app: + +```sh +scripts/install-bar.sh # builds, installs ~/.local/bin/sidepulse-bar, swaps the LaunchAgent +scripts/install-bar.sh --revert # back to the Python app +``` + +The script stops the Python app (`io.sidepulse.agentstatus`), because both apps own the same socket +and device. It backs up that app's plist and loads `io.sidepulse.bar`, which restarts after a crash +but stays stopped after Quit. Logs go to +`~/.local/state/sidepulse/agent-monitor/sidepulse-bar.out.log`. + +For a side-by-side test that doesn't touch your real device or state: + +```sh +XDG_STATE_HOME=/tmp/sp/state XDG_CONFIG_HOME=/tmp/sp/config SIDEPULSE_VOLUMES=/tmp/sp/vol \ + target/release/sidepulse-bar +``` + +`SIDEPULSE_VOLUMES` replaces `/Volumes` as the place to look for devices. Create +`/tmp/sp/vol/SidePulsePro/LEDS.LED` to get a fake 8-LED device. Fake mounts post no notifications, +so with `SIDEPULSE_VOLUMES` set the app rescans that folder every 5 s instead. + +`SIDEPULSE_DRY_RUN=1` makes the LED worker log each write and keepalive touch instead of doing it. +Use it to run against the real `/Volumes` (and its mount notifications) without writing to a device +another SidePulse app owns. + +Not ported yet: the Setup and Settings windows (hook install, transcript toggles, debug export, +animation editor), the notch Screen Bar, composited app icons in session rows, and the brightness +slider. Brightness is a 25/50/75/100% submenu, and other values set elsewhere are kept and shown. ## Requirements @@ -94,6 +176,17 @@ It always exits 0 and prints nothing, so a hook failure never blocks or clutters once timestamps stamped at run time are masked. The only known difference is the wording of `parse_error` messages when the input isn't valid JSON. +`sidepulse-bar` differences from the Python app, all deliberate: + +- It keeps state bounded (see above), so `latest.json` holds the last 6 hours instead of everything. +- It has no `system_profiler` fallback when detecting the model's full-charge wattage. +- LED writes and keepalive touches never create missing directories, so an unmounted volume can't + leave a stray folder under `/Volumes`. +- The charging pulse cadence and LED syncs work as described above. + +It keeps the Python app's behavior quirks, such as a finished tool call disappearing after about two +minutes and `include_stale` having no effect, so the menu shows the same sessions. + ```sh python3 scripts/parity.py \ --rust target/release/sidepulse-hook \ diff --git a/crates/sidepulse-bar/Cargo.toml b/crates/sidepulse-bar/Cargo.toml new file mode 100644 index 0000000..c18f379 --- /dev/null +++ b/crates/sidepulse-bar/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "sidepulse-bar" +description = "Native SidePulse menu-bar app: agent status, LED device output and battery display." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +publish.workspace = true + +[dependencies] +sidepulse-core = { path = "../sidepulse-core" } +chrono.workspace = true +libc.workspace = true +serde_json.workspace = true +regex.workspace = true + +[target.'cfg(target_os = "macos")'.dependencies] +objc2 = "0.6" +objc2-foundation = "0.3" +objc2-app-kit = "0.3" +dispatch2 = "0.3" +block2 = "0.6" + +[dev-dependencies] +tempfile.workspace = true diff --git a/crates/sidepulse-bar/src/app.rs b/crates/sidepulse-bar/src/app.rs new file mode 100644 index 0000000..597af20 --- /dev/null +++ b/crates/sidepulse-bar/src/app.rs @@ -0,0 +1,482 @@ +//! Main-thread app state: port of `StatusBarController` in `status_bar.py` (minus the Setup and +//! Settings windows and the Screen Bar, which stay in the Python CLI for now). + +use std::cell::RefCell; +use std::path::PathBuf; +use std::time::{Duration, Instant}; + +use block2::RcBlock; +use chrono::Utc; +use objc2::rc::Retained; +use objc2::MainThreadMarker; +use objc2_foundation::NSTimer; +use serde_json::Value; + +use sidepulse_core::battery::{self, BatterySnapshot, PowerChangePreview}; +use sidepulse_core::devices::{discover, discover_in, Device}; +use sidepulse_core::lid::{self, ClosedLidAwake}; +use sidepulse_core::models::{AgentMode, AgentStatus}; +use sidepulse_core::monitor::{LiveMonitor, MonitorConfig, Snapshot}; +use sidepulse_core::power::KeepAwake; +use sidepulse_core::providers::default_state_dir; + +use crate::led::{DeviceConfig, LedRequest, LedWorker, Message}; +use crate::session::{ + applescript_quote, format_age, menu_title, recent_statuses, resolve_open, OpenTarget, +}; +use crate::settings::Settings; +use crate::ui::{self, Action, DeviceRow, MenuModel, SessionRow, StatusUi}; + +/// Lines of each provider hook log replayed at startup (`STATUS_BAR_STARTUP_REPLAY_LINES`). +pub const STARTUP_REPLAY_LINES: usize = 200; + +thread_local! { + static APP: RefCell> = const { RefCell::new(None) }; +} + +/// Run `f` against the app on the main thread (no-op before startup or after quit). +pub fn with_app(f: impl FnOnce(&mut App)) { + APP.with(|cell| { + if let Ok(mut guard) = cell.try_borrow_mut() { + if let Some(app) = guard.as_mut() { + f(app); + } + } + }); +} + +pub fn install(app: App) { + APP.with(|cell| *cell.borrow_mut() = Some(app)); +} + +pub struct App { + mtm: MainThreadMarker, + monitor: LiveMonitor, + settings: Settings, + ui: StatusUi, + leds: LedWorker, + keep_awake: KeepAwake, + closed_lid: ClosedLidAwake, + preview: PowerChangePreview, + snapshot: Option, + devices: Vec, + device_signature: Vec<(PathBuf, u64, u64)>, + lid_closed: Option, + refresh_pending: bool, + flush_pending: bool, + /// One-shot timer for the next time-based refresh (see [`App::schedule_next_refresh`]). + refresh_timer: Option>, + keep_awake_detail: String, +} + +/// Slack added after a predicted transition, because the monitor's thresholds are strict. +const TRANSITION_MARGIN: f64 = 0.25; +/// Timer tolerance for a predicted transition: the menu may change up to a second late. +const TRANSITION_TOLERANCE: f64 = 1.0; +/// Safety refresh when nothing is predicted (battery details IOKit may not notify about, and +/// any clock change). Coarse, with a large tolerance so the system can batch it. +const SAFETY_REFRESH: f64 = 300.0; +const SAFETY_TOLERANCE: f64 = 60.0; +/// `latest.json` is written at most this long after the first change of a burst. +const FLUSH_DELAY: f64 = 2.0; + +/// Devices under `$SIDEPULSE_VOLUMES` when set (used for side-by-side testing), else `/Volumes`. +fn discover_devices() -> Vec { + match std::env::var_os("SIDEPULSE_VOLUMES") { + Some(root) => discover_in(std::path::Path::new(&root)), + None => discover(), + } +} + +fn device_signature(devices: &[Device]) -> Vec<(PathBuf, u64, u64)> { + use std::os::unix::fs::MetadataExt; + devices + .iter() + .map(|d| { + let (dev, ino) = std::fs::metadata(&d.root) + .map(|m| (m.dev(), m.ino())) + .unwrap_or((0, 0)); + (d.root.clone(), dev, ino) + }) + .collect() +} + +impl App { + pub fn new(mtm: MainThreadMarker) -> Self { + let state_dir = default_state_dir(); + let mut monitor = LiveMonitor::new(state_dir.join("latest.json"), MonitorConfig::default()); + let replayed = monitor.replay_logs(STARTUP_REPLAY_LINES); + crate::log(&format!( + "started; replayed {replayed} hook records, tracking {} sessions", + monitor.len() + )); + let handler: Box = Box::new(|action| with_app(|app| app.handle(action))); + let devices = discover_devices(); + Self { + mtm, + monitor, + settings: Settings::load_default(), + ui: StatusUi::new(mtm, handler), + leds: LedWorker::start(crate::led::dry_run_from_env()), + keep_awake: KeepAwake::default(), + closed_lid: ClosedLidAwake::default(), + preview: PowerChangePreview::default(), + snapshot: None, + device_signature: device_signature(&devices), + devices, + lid_closed: None, + refresh_pending: false, + flush_pending: false, + refresh_timer: None, + keep_awake_detail: String::new(), + } + } + + /// Hook event from the socket (`handle_hook_event_message`). + pub fn on_event(&mut self, provider: &str, line: &Value) { + if self.monitor.ingest_line(provider, line) && !self.refresh_pending { + // Coalesce bursts: refresh once after the queued events are processed. + self.refresh_pending = true; + dispatch2::DispatchQueue::main().exec_async(|| with_app(|app| app.refresh())); + } + self.schedule_flush(); + } + + /// Debounced `latest.json` write: one flush [`FLUSH_DELAY`] after state first became dirty, + /// replacing the 2 s flush timer. Shutdown flushes anything still pending. + pub fn schedule_flush(&mut self) { + if self.flush_pending || !self.monitor.is_dirty() { + return; + } + self.flush_pending = true; + dispatch2::DispatchQueue::main() + .after(dispatch_time(FLUSH_DELAY), || { + with_app(|app| { + app.flush_pending = false; + app.flush_state(); + // Still dirty only if the write failed: retry like the old 2 s timer did. + app.schedule_flush(); + }) + }) + .ok(); + } + + /// Arms a single one-shot timer for the next time-based change instead of refreshing every + /// 15 s: the next agent status transition (completed hiding, post-tool working turning + /// completed, staleness), the end of the keep-awake grace period, or else a coarse safety + /// refresh. Events, power-source and device notifications refresh on their own. + fn schedule_next_refresh(&mut self, now: Instant) { + let mut wait = SAFETY_REFRESH; + let mut tolerance = SAFETY_TOLERANCE; + let utc_now = Utc::now(); + let transition = self + .monitor + .next_transition_at(utc_now) + .map(|at| (at - utc_now).num_milliseconds() as f64 / 1000.0); + let grace = self + .keep_awake + .grace_deadline(now) + .map(|at| (at - now).as_secs_f64()); + for secs in transition.into_iter().chain(grace) { + let secs = secs.max(0.0) + TRANSITION_MARGIN; + if secs < wait { + wait = secs; + tolerance = TRANSITION_TOLERANCE; + } + } + if let Some(old) = self.refresh_timer.take() { + old.invalidate(); + } + let block = RcBlock::new(|_timer: std::ptr::NonNull| { + with_app(|app| { + app.refresh_timer = None; + app.refresh(); + }) + }); + // SAFETY: called on the main thread (the app lives there); the block is copied by the + // timer, and a non-repeating timer is scheduled on the current (main) run loop. + let timer = + unsafe { NSTimer::scheduledTimerWithTimeInterval_repeats_block(wait, false, &block) }; + timer.setTolerance(tolerance); + self.refresh_timer = Some(timer); + } + + /// `refresh_`: snapshot, status item, LEDs, keep-awake, menu. + pub fn refresh(&mut self) { + self.refresh_pending = false; + let now = Instant::now(); + let snapshot = self.monitor.snapshot(Utc::now()); + let mode = snapshot.aggregate.mode; + self.ui.set_mode(mode); + + let battery = battery::read_with(self.settings.full_charge_watts()); + if let Some(b) = &battery { + if self.preview.observe( + b.is_plugged, + self.settings.show_on_power_change(), + Duration::from_secs_f64(self.settings.power_change_preview_seconds()), + now, + ) { + crate::log("power source changed; previewing battery on LEDs"); + // Return to the agent display when the preview ends. + let secs = self.settings.power_change_preview_seconds() + 0.1; + dispatch2::DispatchQueue::main() + .after(dispatch_time(secs), || with_app(|app| app.refresh())) + .ok(); + } + } + self.sync_leds(mode, battery.as_ref(), now); + + self.keep_awake.update(mode, now); + // Log transitions only (refreshes are now per event, so logging every held refresh + // would repeat the same line). The grace countdown is not a transition. + let detail = self.keep_awake.detail(now); + let kind = detail.split(':').next().unwrap_or_default().to_string(); + if kind != self.keep_awake_detail { + crate::log(&format!("keep awake: {detail}")); + self.keep_awake_detail = kind; + } + let policy = lid::ClosedLidPolicy::parse(self.settings.closed_lid_policy().as_str()) + .unwrap_or(lid::ClosedLidPolicy::Never); + // `update` reports whether the hold is active, not whether it changed: log transitions only. + let was_active = self.closed_lid.active(); + let active = self + .closed_lid + .update(policy, self.keep_awake.holding_requested); + if active != was_active { + crate::log(&format!( + "closed-lid awake: {}", + if active { "holding" } else { "released" } + )); + } + + let model = self.menu_model(&snapshot); + self.ui.set_menu(&model); + self.snapshot = Some(snapshot); + self.schedule_next_refresh(now); + } + + fn sync_leds(&mut self, mode: AgentMode, battery: Option<&BatterySnapshot>, now: Instant) { + let mut changed = false; + for d in &self.devices { + changed |= self + .settings + .remember_device(&d.root.to_string_lossy(), &d.name); + } + if changed { + self.save_settings(); + } + let devices = self + .devices + .iter() + .map(|d| { + let path = d.root.to_string_lossy(); + DeviceConfig { + device: d.clone(), + display: self.settings.device_display(&path), + brightness: self.settings.device_brightness(&path), + } + }) + .collect(); + let full_charge_ratio = battery + .map(|b| b.charge_speed_ratio(self.settings.full_charge_watts())) + .unwrap_or(0.0); + self.leds.send(Message::Sync(Box::new(LedRequest { + devices, + mode, + battery: battery.cloned(), + battery_preview: self.preview.active(now), + full_charge_ratio, + }))); + } + + fn menu_model(&self, snapshot: &Snapshot) -> MenuModel { + let now = Utc::now(); + let sessions = recent_statuses(&snapshot.statuses) + .iter() + .map(|s| SessionRow { + title: menu_title(s), + mode: s.mode, + agent_id: s.agent_id.clone(), + tooltip: session_detail(s, now), + }) + .collect(); + let connected: Vec = self + .devices + .iter() + .map(|d| d.root.to_string_lossy().into_owned()) + .collect(); + let mut devices: Vec = self + .devices + .iter() + .map(|d| (d.root.to_string_lossy().into_owned(), d.name.clone())) + .chain( + self.settings + .remembered_devices() + .into_iter() + .filter(|(p, _)| !connected.contains(p)), + ) + .map(|(path, name)| DeviceRow { + connected: connected.contains(&path), + display: self.settings.device_display(&path), + brightness: self.settings.device_brightness(&path), + path, + name, + }) + .collect(); + devices.dedup_by(|a, b| a.path == b.path); + MenuModel { + sessions, + devices, + lid_policy: self.settings.closed_lid_policy(), + sleep_warning: self.closed_lid.last_error.clone(), + } + } + + /// `poll_devices_once`, run on volume mount/unmount/rename notifications instead of every + /// 2 s: refresh only when the set of volumes changed. + pub fn rescan_devices(&mut self) { + let devices = discover_devices(); + let signature = device_signature(&devices); + if signature != self.device_signature { + crate::log(&format!("devices changed: {} connected", devices.len())); + self.devices = devices; + self.device_signature = signature; + self.refresh(); + } + } + + /// `pollLid:`, run once at startup and then on each clamshell notification instead of every + /// second: the first reading is a baseline; changes play an animation. + pub fn poll_lid(&mut self) { + let Some(closed) = lid::clamshell_closed() else { + return; + }; + let previous = self.lid_closed.replace(closed); + if previous.is_none() || previous == Some(closed) || self.devices.is_empty() { + return; + } + let animation = if closed { + self.settings + .lid_closed_animation(&lid::default_closed_program(255)) + } else { + self.settings + .lid_open_animation(&lid::default_open_program(255)) + }; + crate::log(&format!("lid {}", if closed { "closed" } else { "opened" })); + self.leds.send(Message::Animate { + program: animation.program, + duration: Duration::from_secs_f64(animation.duration_seconds), + }); + } + + pub fn flush_state(&mut self) { + if let Err(e) = self.monitor.flush() { + crate::log(&format!("could not write latest.json: {e}")); + } + } + + fn save_settings(&mut self) { + if let Err(e) = self.settings.save() { + crate::log(&format!("could not save settings: {e}")); + } + } + + fn find_status(&self, agent_id: &str) -> Option { + let snapshot = self.snapshot.as_ref()?; + snapshot + .statuses + .iter() + .chain(snapshot.stale.iter()) + .find(|s| s.agent_id == agent_id) + .cloned() + } + + pub fn handle(&mut self, action: Action) { + match action { + Action::OpenSession(id) => { + let Some(status) = self.find_status(&id) else { + return; + }; + match resolve_open(&status, &self.settings) { + Some(OpenTarget::Url(url)) => ui::open_url(&url), + Some(OpenTarget::Terminal(command)) => open_terminal_command(&command), + None => crate::log(&format!("no open action for {}", status.display_name)), + } + return; + } + Action::SetDisplay(path, display) => { + let name = self.device_name(&path); + self.settings.set_device_display(&path, &name, display); + } + Action::SetBrightness(path, value) => { + let name = self.device_name(&path); + self.settings.set_device_brightness(&path, &name, value); + } + Action::RemoveDevice(path) => self.settings.forget_device(&path), + Action::SetLidPolicy(policy) => self.settings.set_closed_lid_policy(policy), + Action::Quit => { + self.shutdown(); + ui::terminate(self.mtm); + return; + } + Action::MenuOpening => { + // Session ages in tooltips are only refreshed when someone looks at them. + self.refresh(); + return; + } + } + self.save_settings(); + self.refresh(); + } + + fn device_name(&self, path: &str) -> String { + self.devices + .iter() + .find(|d| d.root.to_string_lossy() == path) + .map(|d| d.name.clone()) + .unwrap_or_else(|| { + std::path::Path::new(path) + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default() + }) + } + + /// Release power assertions and persist state (Quit releases both caffeinate holds in Python). + pub fn shutdown(&mut self) { + self.keep_awake.release(); + self.closed_lid.release(); + self.flush_state(); + crate::log("stopped"); + } +} + +fn session_detail(status: &AgentStatus, now: chrono::DateTime) -> String { + let age = (now - status.updated_at).num_milliseconds() as f64 / 1000.0; + let mut parts = vec![ + crate::session::state_for_mode(status.mode) + .label + .to_string(), + format_age(age), + ]; + parts.extend(status.origin.clone().filter(|s| !s.is_empty())); + parts.extend(status.tool_name.clone().filter(|s| !s.is_empty())); + parts.join(" · ") +} + +fn open_terminal_command(command: &str) { + let script = format!( + "tell application \"Terminal\"\n activate\n do script {}\nend tell", + applescript_quote(command) + ); + let _ = std::process::Command::new("/usr/bin/osascript") + .args(["-e", &script]) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn(); +} + +pub fn dispatch_time(seconds: f64) -> dispatch2::DispatchTime { + dispatch2::DispatchTime::NOW.time((seconds * 1e9) as i64) +} diff --git a/crates/sidepulse-bar/src/led.rs b/crates/sidepulse-bar/src/led.rs new file mode 100644 index 0000000..155db58 --- /dev/null +++ b/crates/sidepulse-bar/src/led.rs @@ -0,0 +1,307 @@ +//! LED worker thread: owns the per-device controllers and does every SD-card write, so a slow or +//! sleeping card never blocks the menu bar (Python used one worker per sync and *dropped* syncs +//! that arrived while one was in flight; here the latest request always wins and none are lost). +//! +//! Also handles what Python did on the 15 s refresh: keepalive touches (≤ once per 60 s per +//! volume) and the charging-pulse rewrite, which now follows the intended wattage-based cadence +//! (`max(0.9, 3.0 − 2.1·ratio)` s) instead of being capped by the refresh interval. The thread +//! sleeps exactly until the next of those is due (or a new request arrives), never on a fixed tick. +//! +//! With `SIDEPULSE_DRY_RUN=1` the worker logs each write and touch instead of doing it, so the app +//! can run against the real `/Volumes` without touching a device another app owns. + +use std::collections::HashMap; +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender}; +use std::time::{Duration, Instant}; + +use sidepulse_core::battery::{charging_update_interval, BatteryLedController, BatterySnapshot}; +use sidepulse_core::devices::{write_program_to, Device, LedController}; +use sidepulse_core::lid::lid_animation_program; +use sidepulse_core::models::AgentMode; +use sidepulse_core::power::{keepalive_targets, touch, KeepaliveToucher}; + +use crate::settings::LedDisplay; + +#[derive(Clone, Debug)] +pub struct DeviceConfig { + pub device: Device, + pub display: LedDisplay, + pub brightness: u8, +} + +#[derive(Clone, Debug)] +pub struct LedRequest { + pub devices: Vec, + pub mode: AgentMode, + pub battery: Option, + /// Plug/unplug preview: show battery on every device regardless of its display setting. + pub battery_preview: bool, + pub full_charge_ratio: f64, +} + +pub enum Message { + Sync(Box), + /// Lid open/close animation: program plus how long to suppress normal output. + Animate { + program: String, + duration: Duration, + }, +} + +#[derive(Default)] +struct DeviceState { + agent: Option, + battery: Option, + showing_battery: Option, +} + +type WriteFn = fn(&Path, &str) -> io::Result<()>; +type TouchFn = fn(&Path) -> io::Result<()>; + +/// How the worker reaches the card: real writes, or log-only for `SIDEPULSE_DRY_RUN`. +#[derive(Clone, Copy)] +struct Io { + write: WriteFn, + touch: TouchFn, +} + +impl Io { + fn new(dry_run: bool) -> Self { + if dry_run { + Self { + write: dry_write, + touch: dry_touch, + } + } else { + Self { + write: write_program_to, + touch, + } + } + } +} + +fn dry_write(target: &Path, text: &str) -> io::Result<()> { + let preview: String = text.chars().take(80).collect(); + crate::log(&format!( + "dry run: would write {} bytes to {}: {preview:?}", + text.len(), + target.display() + )); + Ok(()) +} + +fn dry_touch(path: &Path) -> io::Result<()> { + crate::log(&format!("dry run: would touch {}", path.display())); + Ok(()) +} + +/// `SIDEPULSE_DRY_RUN` set to anything but empty or `0`. +pub fn dry_run_from_env() -> bool { + std::env::var("SIDEPULSE_DRY_RUN").is_ok_and(|v| !v.is_empty() && v != "0") +} + +pub struct LedWorker { + tx: Sender, +} + +impl LedWorker { + pub fn start(dry_run: bool) -> Self { + let (tx, rx) = mpsc::channel(); + let io = Io::new(dry_run); + std::thread::Builder::new() + .name("sidepulse-leds".into()) + .spawn(move || run(rx, io)) + .expect("spawn LED worker"); + Self { tx } + } + + pub fn send(&self, message: Message) { + let _ = self.tx.send(message); + } +} + +fn run(rx: Receiver, io: Io) { + let mut states: HashMap = HashMap::new(); + let mut toucher = KeepaliveToucher::new(io.touch, false); + let mut latest: Option = None; + loop { + let message = match next_wake(latest.as_ref(), &toucher, Instant::now()) { + // Nothing scheduled: block until the next request. + None => match rx.recv() { + Ok(m) => Some(m), + Err(_) => return, + }, + Some(wait) => match rx.recv_timeout(wait) { + Ok(m) => Some(m), + Err(RecvTimeoutError::Timeout) => None, + Err(RecvTimeoutError::Disconnected) => return, + }, + }; + // Coalesce a burst: keep the newest sync, but never skip an animation. + let mut pending = message.into_iter().collect::>(); + pending.extend(rx.try_iter()); + for message in pending { + match message { + Message::Sync(request) => latest = Some(*request), + Message::Animate { program, duration } => { + if let Some(request) = &latest { + animate(request, &program, io.write); + } + std::thread::sleep(duration + Duration::from_millis(150)); + // `restore_led_display`: force a full rewrite after the animation. + states.clear(); + } + } + } + if let Some(request) = &latest { + apply(request, &mut states, &mut toucher, io.write); + } + } +} + +/// How long to sleep before the next keepalive touch or charging-pulse rewrite is due, or `None` +/// to wait for the next request. Keepalive is due exactly 60 s after each volume's last touch. +fn next_wake( + request: Option<&LedRequest>, + toucher: &KeepaliveToucher, + now: Instant, +) -> Option { + let request = request?; + let keepalive = toucher + .next_due(&request_keepalive_targets(request), now) + .map(|due| due.saturating_duration_since(now)); + match (keepalive, next_battery_rewrite(request)) { + (Some(a), Some(b)) => Some(a.min(b)), + (a, b) => a.or(b), + } +} + +fn request_keepalive_targets(request: &LedRequest) -> Vec { + let devices: Vec = request.devices.iter().map(|c| c.device.clone()).collect(); + keepalive_targets(&devices) +} + +fn animate(request: &LedRequest, program: &str, write: WriteFn) { + for cfg in &request.devices { + if let Ok(text) = lid_animation_program(program, cfg.brightness) { + let _ = write(&cfg.device.target(), &text); + } + } +} + +fn shows_battery(request: &LedRequest, cfg: &DeviceConfig) -> bool { + request.battery.is_some() && (cfg.display == LedDisplay::Battery || request.battery_preview) +} + +fn next_battery_rewrite(request: &LedRequest) -> Option { + let battery = request.battery.as_ref()?; + if !battery.is_charging + || !request + .devices + .iter() + .any(|cfg| shows_battery(request, cfg)) + { + return None; + } + Some(Duration::from_secs_f64(charging_update_interval( + request.full_charge_ratio, + ))) +} + +fn apply( + request: &LedRequest, + states: &mut HashMap, + toucher: &mut KeepaliveToucher, + write: WriteFn, +) { + let now = Instant::now(); + states.retain(|root, _| request.devices.iter().any(|c| &c.device.root == root)); + for cfg in &request.devices { + let state = states.entry(cfg.device.root.clone()).or_default(); + let battery_mode = shows_battery(request, cfg); + if state.showing_battery != Some(battery_mode) { + // A change of display kind resets both controllers so the new program is written. + state.agent = None; + state.battery = None; + state.showing_battery = Some(battery_mode); + } + let result = match (&request.battery, battery_mode) { + (Some(snapshot), true) => state + .battery + .get_or_insert_with(|| BatteryLedController::new(cfg.device.clone())) + .sync_with(snapshot, cfg.brightness, now, write), + _ => state + .agent + .get_or_insert_with(|| LedController::new(cfg.device.clone())) + .sync_with(request.mode, cfg.brightness, now, write), + }; + match result { + Ok(Some(_)) => crate::log(&format!("LEDs updated on {}", cfg.device.root.display())), + Ok(None) => {} + Err(e) => crate::log(&format!( + "LED write failed on {}: {e}", + cfg.device.root.display() + )), + } + } + for target in request_keepalive_targets(request) { + toucher.poke(&target, now); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ok_touch(_: &Path) -> io::Result<()> { + Ok(()) + } + + fn request(root: &Path) -> LedRequest { + LedRequest { + devices: vec![DeviceConfig { + device: test_device(root), + display: LedDisplay::Agent, + brightness: 255, + }], + mode: AgentMode::IdleReady, + battery: None, + battery_preview: false, + full_charge_ratio: 0.0, + } + } + + fn test_device(root: &Path) -> Device { + let dir = tempfile::tempdir().unwrap(); + let dev = dir.path().join("SidePulsePro"); + std::fs::create_dir(&dev).unwrap(); + std::fs::write(dev.join("LEDS.LED"), b"").unwrap(); + let mut d = sidepulse_core::devices::discover_in(dir.path()) + .into_iter() + .next() + .expect("fake device"); + d.root = root.to_path_buf(); + d + } + + #[test] + fn sleeps_until_the_keepalive_is_due_and_blocks_without_requests() { + let t0 = Instant::now(); + let mut toucher = KeepaliveToucher::new(ok_touch, false); + assert_eq!(next_wake(None, &toucher, t0), None); + let req = request(Path::new("/tmp/fake/SidePulsePro")); + // Never touched: due now. + assert_eq!(next_wake(Some(&req), &toucher, t0), Some(Duration::ZERO)); + for target in request_keepalive_targets(&req) { + toucher.poke(&target, t0); + } + let later = t0 + Duration::from_secs(25); + assert_eq!( + next_wake(Some(&req), &toucher, later), + Some(Duration::from_secs(35)) + ); + } +} diff --git a/crates/sidepulse-bar/src/main.rs b/crates/sidepulse-bar/src/main.rs new file mode 100644 index 0000000..f8d57fd --- /dev/null +++ b/crates/sidepulse-bar/src/main.rs @@ -0,0 +1,186 @@ +//! `sidepulse-bar`: native SidePulse menu-bar app. +//! +//! Fully event-driven: hook events arrive on the socket thread, the lid and power source through +//! IOKit notifications, volumes through `NSWorkspace` notifications and signals through dispatch +//! sources. The only timers are one-shots for known deadlines (see `App::schedule_next_refresh`) +//! and a coarse safety refresh. + +mod app; +mod led; +mod server; +mod session; +mod settings; +mod ui; + +use std::ptr::NonNull; + +use block2::RcBlock; +use dispatch2::{DispatchObject, DispatchQueue, DispatchRetained, DispatchSource}; +use objc2::rc::Retained; +use objc2::runtime::ProtocolObject; +use objc2::MainThreadMarker; +use objc2_app_kit::{ + NSApplication, NSApplicationActivationPolicy, NSWorkspace, NSWorkspaceDidMountNotification, + NSWorkspaceDidRenameVolumeNotification, NSWorkspaceDidUnmountNotification, +}; +use objc2_foundation::{NSNotification, NSObjectProtocol, NSOperationQueue, NSTimer}; + +use sidepulse_core::battery::PowerSourceWatch; +use sidepulse_core::lid::{self, ClamshellWatch}; + +/// `log_status_bar`: `ISO-timestamp message` on stdout (launchd captures it). +pub fn log(message: &str) { + println!( + "{} {message}", + chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ") + ); +} + +/// A repeating fallback timer, used only where no notification is available. +fn repeat(seconds: f64, tolerance: f64, f: fn(&mut app::App)) -> Retained { + let block = RcBlock::new(move |_timer: NonNull| app::with_app(f)); + // SAFETY: called on the main thread; the timer copies the block and is scheduled on the main + // run loop. + let timer = + unsafe { NSTimer::scheduledTimerWithTimeInterval_repeats_block(seconds, true, &block) }; + timer.setTolerance(tolerance); + timer +} + +/// Fallback lid poll when clamshell notifications can't be registered (and a lid exists). +const LID_FALLBACK_POLL: f64 = 5.0; +/// Device poll under `SIDEPULSE_VOLUMES`, whose fake mounts post no notifications. +const VOLUMES_OVERRIDE_POLL: f64 = 5.0; +/// Second rescan after a mount notification, in case the device's files appear a moment later. +const MOUNT_RESCAN_DELAY: f64 = 2.0; + +/// Things that must live as long as the app: dropping them would unregister the notification. +#[derive(Default)] +struct Watches { + _lid: Option, + _power: Option, + _volume_observers: Vec>>, + _signals: Vec>, + _timers: Vec>, +} + +/// Lid changes via `kIOPMMessageClamshellStateChange` instead of the 1 s `pollLid:` timer. +fn watch_lid(watches: &mut Watches) { + app::with_app(app::App::poll_lid); // baseline reading + watches._lid = ClamshellWatch::new(|| app::with_app(app::App::poll_lid)); + if watches._lid.is_none() && lid::clamshell_closed().is_some() { + log("clamshell notifications unavailable; polling the lid"); + watches._timers.push(repeat( + LID_FALLBACK_POLL, + LID_FALLBACK_POLL * 0.2, + app::App::poll_lid, + )); + } +} + +/// Plug, unplug and charge changes refresh the battery display (was: the 15 s refresh). +fn watch_power(watches: &mut Watches) { + watches._power = PowerSourceWatch::new(|| app::with_app(app::App::refresh)); + if watches._power.is_none() { + log("power-source notifications unavailable; battery updates on the safety refresh"); + } +} + +/// Volume mount, unmount and rename notifications trigger a rescan (was: a 2 s `/Volumes` poll). +fn watch_volumes(watches: &mut Watches) { + if std::env::var_os("SIDEPULSE_VOLUMES").is_some() { + watches._timers.push(repeat( + VOLUMES_OVERRIDE_POLL, + VOLUMES_OVERRIDE_POLL * 0.2, + app::App::rescan_devices, + )); + return; + } + let center = NSWorkspace::sharedWorkspace().notificationCenter(); + let main_queue = NSOperationQueue::mainQueue(); + let block = RcBlock::new(|_note: NonNull| { + app::with_app(app::App::rescan_devices); + DispatchQueue::main() + .after(app::dispatch_time(MOUNT_RESCAN_DELAY), || { + app::with_app(app::App::rescan_devices) + }) + .ok(); + }); + // SAFETY: the notification names are AppKit's static constants; the block is copied by the + // center and runs on the main operation queue (main thread), where the app lives. + for name in unsafe { + [ + NSWorkspaceDidMountNotification, + NSWorkspaceDidUnmountNotification, + NSWorkspaceDidRenameVolumeNotification, + ] + } { + let observer = unsafe { + center.addObserverForName_object_queue_usingBlock( + Some(name), + None, + Some(&main_queue), + &block, + ) + }; + watches._volume_observers.push(observer); + } +} + +/// Release power assertions and flush state on SIGTERM/SIGINT (launchd bootout, Ctrl-C), via a +/// dispatch signal source on the main queue (was: a 1 s timer checking a flag). +fn watch_signals(watches: &mut Watches) { + for sig in [libc::SIGTERM, libc::SIGINT] { + // SAFETY: ignoring the default disposition is required for a dispatch signal source to + // receive the signal instead of the process terminating. The source type is libdispatch's + // static, the handle is a valid signal number and the target queue is the main queue. + let source = unsafe { + libc::signal(sig, libc::SIG_IGN); + DispatchSource::new( + &raw const dispatch2::_dispatch_source_type_signal as *mut _, + sig as usize, + 0, + Some(DispatchQueue::main()), + ) + }; + let handler = RcBlock::new(|| { + app::with_app(app::App::shutdown); + std::process::exit(0); + }); + // SAFETY: libdispatch copies the block; the source is retained in `watches`. + unsafe { source.set_event_handler_with_block(RcBlock::as_ptr(&handler)) }; + source.activate(); + watches._signals.push(source); + } +} + +fn main() { + let mtm = MainThreadMarker::new().expect("must run on the main thread"); + let application = NSApplication::sharedApplication(mtm); + application.setActivationPolicy(NSApplicationActivationPolicy::Accessory); + + app::install(app::App::new(mtm)); + let socket = sidepulse_core::ipc::default_event_socket_path(); + match server::start(&socket, |provider, line| { + DispatchQueue::main().exec_async(move || app::with_app(|a| a.on_event(&provider, &line))); + }) { + Ok((path, _)) => log(&format!("listening on {}", path.display())), + Err(e) => log(&format!( + "could not start event socket {}: {e}", + socket.display() + )), + } + + let mut watches = Watches::default(); + watch_signals(&mut watches); + app::with_app(|a| { + a.refresh(); + a.schedule_flush(); + }); + watch_lid(&mut watches); + watch_power(&mut watches); + watch_volumes(&mut watches); + + application.run(); + drop(watches); +} diff --git a/crates/sidepulse-bar/src/server.rs b/crates/sidepulse-bar/src/server.rs new file mode 100644 index 0000000..2827129 --- /dev/null +++ b/crates/sidepulse-bar/src/server.rs @@ -0,0 +1,108 @@ +//! Event socket server: port of `HookEventServer` in `sidepulse/ipc.py`. +//! One JSON message `{"provider", "line"}` per connection, read to EOF, at most 1 MiB. +//! Unlike the Python version it blocks in `accept` instead of waking every 0.5 s. + +use std::io::Read; +use std::os::unix::net::{UnixListener, UnixStream}; +use std::path::{Path, PathBuf}; +use std::thread::JoinHandle; +use std::time::Duration; + +use serde_json::Value; + +use sidepulse_core::ipc::MAX_EVENT_BYTES; + +pub fn parse_message(bytes: &[u8]) -> Option<(String, Value)> { + let Ok(Value::Object(mut msg)) = serde_json::from_slice::(bytes) else { + return None; + }; + let provider = match msg.remove("provider") { + Some(Value::String(p)) => p, + _ => return None, + }; + match msg.remove("line") { + Some(line @ Value::Object(_)) => Some((provider, line)), + _ => None, + } +} + +fn read_message(mut conn: UnixStream) -> Option<(String, Value)> { + // macOS returns EINVAL here when the peer already closed (the hook writes and closes at + // once); the data is still readable, so the error must not drop the message. + let _ = conn.set_read_timeout(Some(Duration::from_secs(2))); + let mut buf = Vec::with_capacity(4096); + let read = (&mut conn) + .take(MAX_EVENT_BYTES as u64 + 1) + .read_to_end(&mut buf) + .ok()?; + if read > MAX_EVENT_BYTES { + return None; + } + parse_message(&buf) +} + +/// Bind `socket_path` (replacing a stale socket) and deliver each message to `on_event` +/// from a background thread. +pub fn start(socket_path: &Path, on_event: F) -> std::io::Result<(PathBuf, JoinHandle<()>)> +where + F: Fn(String, Value) + Send + 'static, +{ + if let Some(parent) = socket_path.parent() { + std::fs::create_dir_all(parent)?; + } + match std::fs::remove_file(socket_path) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(e), + } + let listener = UnixListener::bind(socket_path)?; + let path = socket_path.to_path_buf(); + let handle = std::thread::Builder::new() + .name("sidepulse-events".into()) + .spawn(move || { + for conn in listener.incoming() { + match conn { + Ok(conn) => { + if let Some((provider, line)) = read_message(conn) { + on_event(provider, line); + } + } + Err(_) => std::thread::sleep(Duration::from_millis(50)), + } + } + })?; + Ok((path, handle)) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + use std::sync::mpsc; + + #[test] + fn receives_messages_from_the_hook_client() { + let dir = tempfile::tempdir().unwrap(); + let sock = dir.path().join("events.sock"); + std::fs::write(&sock, b"stale").unwrap(); + let (tx, rx) = mpsc::channel(); + start(&sock, move |p, l| tx.send((p, l)).unwrap()).unwrap(); + let line = json!({"hook_event_name": "Stop", "session_id": "s"}); + assert!(sidepulse_core::ipc::send_hook_event( + "claude", + &line, + &sock, + Duration::from_millis(500) + )); + let (provider, got) = rx.recv_timeout(Duration::from_secs(2)).unwrap(); + assert_eq!(provider, "claude"); + assert_eq!(got, line); + } + + #[test] + fn rejects_malformed_messages() { + assert!(parse_message(b"{bad").is_none()); + assert!(parse_message(br#"{"provider": 1, "line": {}}"#).is_none()); + assert!(parse_message(br#"{"provider": "claude", "line": []}"#).is_none()); + } +} diff --git a/crates/sidepulse-bar/src/session.rs b/crates/sidepulse-bar/src/session.rs new file mode 100644 index 0000000..578fa19 --- /dev/null +++ b/crates/sidepulse-bar/src/session.rs @@ -0,0 +1,353 @@ +//! Session rows and open actions: ports of `session_actions.py` and the menu helpers in +//! `status_bar.py` (`recent_statuses`, `menu_title_for_status`, `session_title_parts`, `format_age`). + +use sidepulse_core::collector::project_name; +use sidepulse_core::models::{AgentMode, AgentStatus}; + +use crate::settings::Settings; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum OpenAction { + App, + Terminal, + VsCode, +} + +impl OpenAction { + pub fn parse(s: &str) -> Option { + match s { + "app" => Some(Self::App), + "terminal" => Some(Self::Terminal), + "vscode" => Some(Self::VsCode), + _ => None, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum OpenTarget { + Url(String), + Terminal(String), +} + +/// Menu-bar presentation of a mode (`state_for_mode`). +pub struct StateInfo { + pub label: &'static str, + pub symbol: &'static str, +} + +pub fn state_for_mode(mode: AgentMode) -> StateInfo { + match mode { + AgentMode::Working | AgentMode::ToolRunning | AgentMode::LongTaskProgress => StateInfo { + label: "Working", + symbol: "arrow.triangle.2.circlepath", + }, + AgentMode::Completed => StateInfo { + label: "Done", + symbol: "checkmark.circle", + }, + AgentMode::WaitingForInput | AgentMode::BlockedError => StateInfo { + label: "Ask", + symbol: "questionmark.circle", + }, + AgentMode::IdleReady | AgentMode::Unknown => StateInfo { + label: "Idle", + symbol: "circle", + }, + } +} + +/// RFC 3986 percent-encoding of every byte outside the unreserved set (`quote(s, safe='')`). +fn quote(s: &str) -> String { + let mut out = String::new(); + for b in s.bytes() { + if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') { + out.push(b as char); + } else { + out.push_str(&format!("%{b:02X}")); + } + } + out +} + +fn shell_quote(s: &str) -> String { + if !s.is_empty() + && s.bytes() + .all(|b| b.is_ascii_alphanumeric() || b"@%+=:,./-_".contains(&b)) + { + return s.to_string(); + } + format!("'{}'", s.replace('\'', "'\"'\"'")) +} + +fn session_id(status: &AgentStatus) -> Option<&str> { + status.session_id.as_deref().filter(|s| !s.is_empty()) +} + +pub fn deep_link(status: &AgentStatus) -> Option { + match status.provider.to_lowercase().as_str() { + "codex" => session_id(status).map(|id| format!("codex://threads/{}", quote(id))), + "claude" => Some("claude://".into()), + _ => None, + } +} + +pub fn vscode_link(status: &AgentStatus) -> Option { + if status.provider.to_lowercase() != "claude" { + return None; + } + session_id(status) + .map(|id| format!("vscode://anthropic.claude-code/open?session={}", quote(id))) +} + +pub fn resume_command(status: &AgentStatus) -> Option { + let id = shell_quote(session_id(status)?); + let home = sidepulse_core::providers::home_dir(); + let cwd = shell_quote( + status + .cwd + .as_deref() + .filter(|s| !s.is_empty()) + .unwrap_or(&home.to_string_lossy()), + ); + match status.provider.to_lowercase().as_str() { + "codex" => Some(format!("cd {cwd} && codex resume {id}")), + "claude" => Some(format!("cd {cwd} && claude --resume {id}")), + "grok" => Some(format!("cd {cwd} && grok --resume {id}")), + _ => None, + } +} + +pub fn open_target(status: &AgentStatus, action: OpenAction) -> Option { + match action { + OpenAction::App => deep_link(status).map(OpenTarget::Url), + OpenAction::VsCode => vscode_link(status).map(OpenTarget::Url), + OpenAction::Terminal => resume_command(status).map(OpenTarget::Terminal), + } +} + +fn normalized_origin(origin: Option<&str>) -> String { + origin + .unwrap_or("") + .trim() + .to_lowercase() + .replace('-', " ") + .split_whitespace() + .collect::>() + .join(" ") +} + +pub fn preferred_actions(status: &AgentStatus) -> [OpenAction; 3] { + use OpenAction::*; + let origin = normalized_origin(status.origin.as_deref()); + if !origin.is_empty() { + let has = |list: &[&str]| list.iter().any(|s| origin.contains(s)); + if has(&["vscode", "vs code", "visual studio code"]) { + return [VsCode, App, Terminal]; + } + if has(&["cli", "terminal", "command line"]) { + return [Terminal, App, VsCode]; + } + if has(&["app", "ui", "transcript"]) { + return [App, VsCode, Terminal]; + } + if has(&["cursor", "windsurf"]) { + return [App, Terminal, VsCode]; + } + } + if status.provider.to_lowercase() == "claude" { + [VsCode, App, Terminal] + } else { + [App, Terminal, VsCode] + } +} + +pub fn default_action(status: &AgentStatus) -> OpenAction { + preferred_actions(status) + .into_iter() + .find(|a| open_target(status, *a).is_some()) + .unwrap_or(OpenAction::Terminal) +} + +/// `StatusBarController.open_session(status, None, remember=False)` target resolution. +pub fn resolve_open(status: &AgentStatus, settings: &Settings) -> Option { + let requested = settings + .session_open_action(&status.provider, status.origin.as_deref()) + .and_then(|a| OpenAction::parse(&a)) + .unwrap_or_else(|| default_action(status)); + open_target(status, requested).or_else(|| open_target(status, default_action(status))) +} + +pub fn applescript_quote(value: &str) -> String { + format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\"")) +} + +pub fn recent_statuses(statuses: &[AgentStatus]) -> Vec { + let mut list = statuses.to_vec(); + list.sort_by(|a, b| { + a.mode + .priority() + .cmp(&b.mode.priority()) + .then(b.updated_at.cmp(&a.updated_at)) + }); + list.truncate(12); + list +} + +fn normalized_part(text: &str) -> String { + text.replace(['_', '-'], " ") + .split_whitespace() + .collect::>() + .join(" ") + .to_lowercase() +} + +pub fn strip_session_short_id(display_name: &str, session_id: Option<&str>) -> String { + let text = display_name.trim(); + if let Some(id) = session_id.filter(|s| !s.is_empty()) { + let short: String = id.chars().take(8).collect(); + let suffix = format!(" ({short})"); + if let Some(stripped) = text.strip_suffix(&suffix) { + return stripped.trim().to_string(); + } + } + if text.ends_with(')') { + if let Some((prefix, suffix)) = text.rsplit_once(" (") { + let token = &suffix[..suffix.len() - 1]; + let n = token.chars().count(); + if (6..=12).contains(&n) && token.chars().all(|c| c.is_alphanumeric() || c == '-') { + return prefix.trim().to_string(); + } + } + } + text.to_string() +} + +pub fn session_title_parts(status: &AgentStatus) -> (String, Option) { + let mut project = project_name(status.cwd.as_deref()); + let mut title = strip_session_short_id(&status.display_name, status.session_id.as_deref()); + let prefixed = project.as_ref().map(|p| format!("{p}: ")); + if let Some(rest) = prefixed.as_deref().and_then(|p| title.strip_prefix(p)) { + title = rest.to_string(); + } else if let Some((maybe_project, maybe_title)) = title.clone().split_once(": ") { + if project.is_none() { + project = Some(maybe_project.to_string()); + } + title = maybe_title.to_string(); + } + if let Some(p) = &project { + if normalized_part(p) == normalized_part(&title) { + project = None; + } + } + if title.is_empty() { + title = status.display_name.clone(); + } + (title, project) +} + +pub fn menu_title(status: &AgentStatus) -> String { + let state = state_for_mode(status.mode); + let (title, project) = session_title_parts(status); + let first = match status.origin.as_deref().filter(|s| !s.is_empty()) { + Some(origin) => format!("{} {} {}", state.label, origin, title), + None => format!("{} {}", state.label, title), + }; + match project { + Some(p) => format!("{first}\n{p}"), + None => first, + } +} + +pub fn format_age(seconds: f64) -> String { + let s = seconds.max(0.0) as i64; + if s < 60 { + return format!("{s}s"); + } + let (m, rest) = (s / 60, s % 60); + if m < 60 { + return format!("{m}m{rest:02}s"); + } + format!("{}h{:02}m", m / 60, m % 60) +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::Utc; + + fn status( + provider: &str, + session: &str, + origin: Option<&str>, + display: &str, + cwd: Option<&str>, + ) -> AgentStatus { + AgentStatus { + provider: provider.into(), + agent_id: format!("{provider}:session:{session}"), + display_name: display.into(), + mode: AgentMode::Working, + updated_at: Utc::now(), + event_name: "PreToolUse".into(), + session_id: Some(session.into()), + cwd: cwd.map(Into::into), + tool_name: None, + message: None, + origin: origin.map(Into::into), + stale: false, + } + } + + #[test] + fn open_actions_follow_origin() { + let s = status( + "claude", + "abc 1", + Some("Claude Code CLI"), + "x", + Some("/tmp/my dir"), + ); + assert_eq!(default_action(&s), OpenAction::Terminal); + assert_eq!( + resume_command(&s).unwrap(), + "cd '/tmp/my dir' && claude --resume 'abc 1'" + ); + let s = status("claude", "abc", None, "x", None); + assert_eq!(default_action(&s), OpenAction::VsCode); + assert_eq!( + vscode_link(&s).unwrap(), + "vscode://anthropic.claude-code/open?session=abc" + ); + let s = status("codex", "a/b", Some("Codex UI"), "x", None); + assert_eq!( + open_target(&s, default_action(&s)), + Some(OpenTarget::Url("codex://threads/a%2Fb".into())) + ); + } + + #[test] + fn title_parts_strip_ids_and_projects() { + let s = status( + "claude", + "abcdef123", + None, + "sidepulse: Fix the hook (abcdef12)", + Some("/nonexistent/sidepulse"), + ); + assert_eq!( + session_title_parts(&s), + ("Fix the hook".into(), Some("sidepulse".into())) + ); + assert_eq!(menu_title(&s), "Working Fix the hook\nsidepulse"); + let s = status("codex", "zz", Some("Codex CLI"), "proj: proj (zz)", None); + assert_eq!(session_title_parts(&s).1, None); + } + + #[test] + fn ages() { + assert_eq!(format_age(5.0), "5s"); + assert_eq!(format_age(65.0), "1m05s"); + assert_eq!(format_age(3720.0), "1h02m"); + } +} diff --git a/crates/sidepulse-bar/src/settings.rs b/crates/sidepulse-bar/src/settings.rs new file mode 100644 index 0000000..f3f9628 --- /dev/null +++ b/crates/sidepulse-bar/src/settings.rs @@ -0,0 +1,378 @@ +//! `settings.json`, shared with the Python SidePulse app (`settings.py`). +//! +//! The file is kept as a JSON value so keys this port doesn't use (Setup window state, +//! transcript monitoring, hook preferences) survive a save. Saved like Python: +//! `json.dumps(data, indent=2, sort_keys=True)`. + +use std::path::{Path, PathBuf}; +use std::sync::LazyLock; + +use regex::Regex; +use serde_json::{json, Map, Value}; + +use sidepulse_core::providers::{expanduser, home_dir}; + +pub const SESSION_OPEN_CHOICES: [&str; 3] = ["app", "terminal", "vscode"]; + +pub fn default_config_dir() -> PathBuf { + if let Some(xdg) = std::env::var("XDG_CONFIG_HOME") + .ok() + .filter(|s| !s.is_empty()) + { + return expanduser(&xdg).join("sidepulse").join("agent-monitor"); + } + home_dir().join(".config/sidepulse/agent-monitor") +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LedDisplay { + Agent, + Battery, +} + +impl LedDisplay { + fn parse(v: Option<&Value>) -> Option { + match v.and_then(Value::as_str) { + Some("agent") => Some(Self::Agent), + Some("battery") => Some(Self::Battery), + _ => None, + } + } + pub fn as_str(self) -> &'static str { + match self { + Self::Agent => "agent", + Self::Battery => "battery", + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ClosedLidPolicy { + Never, + Agents, + Always, +} + +impl ClosedLidPolicy { + pub fn as_str(self) -> &'static str { + match self { + Self::Never => "never", + Self::Agents => "agents", + Self::Always => "always", + } + } + pub fn parse(s: &str) -> Option { + match s { + "never" => Some(Self::Never), + "agents" => Some(Self::Agents), + "always" => Some(Self::Always), + _ => None, + } + } +} + +#[derive(Clone, Debug)] +pub struct Animation { + pub program: String, + pub duration_seconds: f64, +} + +#[derive(Clone, Debug)] +pub struct Settings { + path: PathBuf, + data: Map, +} + +impl Settings { + pub fn load_default() -> Self { + Self::load(&default_config_dir().join("settings.json")) + } + + pub fn load(path: &Path) -> Self { + let data = std::fs::read_to_string(path) + .ok() + .and_then(|t| serde_json::from_str::(&t).ok()) + .and_then(|v| match v { + Value::Object(m) => Some(m), + _ => None, + }) + .unwrap_or_default(); + Self { + path: path.to_path_buf(), + data, + } + } + + pub fn save(&self) -> std::io::Result<()> { + if let Some(parent) = self.path.parent() { + std::fs::create_dir_all(parent)?; + } + let text = serde_json::to_string_pretty(&sorted(&Value::Object(self.data.clone()))) + .map_err(std::io::Error::other)?; + let tmp = self.path.with_extension("json.tmp"); + std::fs::write(&tmp, text + "\n")?; + std::fs::rename(tmp, &self.path) + } + + pub fn led_display(&self) -> LedDisplay { + LedDisplay::parse(self.data.get("led_display")).unwrap_or(LedDisplay::Agent) + } + + fn device_entry(&self, path: &str) -> Option<&Map> { + self.data + .get("devices")? + .as_array()? + .iter() + .filter_map(Value::as_object) + .find(|d| { + d.get("path").and_then(Value::as_str) == Some(path) + || d.get("id").and_then(Value::as_str) == Some(path) + }) + } + + pub fn device_display(&self, path: &str) -> LedDisplay { + self.device_entry(path) + .and_then(|d| LedDisplay::parse(d.get("led_display"))) + .unwrap_or_else(|| self.led_display()) + } + + pub fn device_brightness(&self, path: &str) -> u8 { + self.device_entry(path) + .and_then(|d| d.get("brightness")) + .and_then(Value::as_i64) + .map(|b| b.clamp(0, 255) as u8) + .unwrap_or(255) + } + + /// Remembered devices as (path, name). + pub fn remembered_devices(&self) -> Vec<(String, String)> { + let Some(list) = self.data.get("devices").and_then(Value::as_array) else { + return Vec::new(); + }; + list.iter() + .filter_map(Value::as_object) + .filter_map(|d| { + let path = d.get("path").and_then(Value::as_str)?; + if path.starts_with("virtual:") { + return None; + } + let name = d.get("name").and_then(Value::as_str).unwrap_or(path); + Some((path.to_string(), name.to_string())) + }) + .collect() + } + + fn devices_mut(&mut self) -> &mut Vec { + let entry = self + .data + .entry("devices") + .or_insert_with(|| Value::Array(Vec::new())); + if !entry.is_array() { + *entry = Value::Array(Vec::new()); + } + entry.as_array_mut().expect("array") + } + + fn device_entry_mut(&mut self, path: &str, name: &str) -> &mut Map { + let default_display = self.led_display().as_str(); + let devices = self.devices_mut(); + let index = devices + .iter() + .position(|d| d.get("path").and_then(Value::as_str) == Some(path)); + let index = index.unwrap_or_else(|| { + devices.push(json!({"id": path, "name": name, "path": path, "led_display": default_display, "brightness": 255})); + devices.len() - 1 + }); + devices[index].as_object_mut().expect("object") + } + + /// Auto-remember a connected device (Python saves connected devices into settings). + /// Returns true when the settings changed. + pub fn remember_device(&mut self, path: &str, name: &str) -> bool { + if self.device_entry(path).is_some() { + return false; + } + self.device_entry_mut(path, name); + true + } + + pub fn set_device_display(&mut self, path: &str, name: &str, display: LedDisplay) { + self.device_entry_mut(path, name) + .insert("led_display".into(), display.as_str().into()); + } + + pub fn set_device_brightness(&mut self, path: &str, name: &str, brightness: u8) { + self.device_entry_mut(path, name) + .insert("brightness".into(), brightness.into()); + } + + pub fn forget_device(&mut self, path: &str) { + self.devices_mut() + .retain(|d| d.get("path").and_then(Value::as_str) != Some(path)); + } + + pub fn closed_lid_policy(&self) -> ClosedLidPolicy { + self.data + .get("closed_lid_awake_policy") + .and_then(Value::as_str) + .and_then(ClosedLidPolicy::parse) + .unwrap_or(ClosedLidPolicy::Never) + } + + pub fn set_closed_lid_policy(&mut self, policy: ClosedLidPolicy) { + self.data + .insert("closed_lid_awake_policy".into(), policy.as_str().into()); + } + + fn animation(&self, key: &str, default_program: &str, default_duration: f64) -> Animation { + let obj = self.data.get(key).and_then(Value::as_object); + let program = obj + .and_then(|o| o.get("program")) + .and_then(Value::as_str) + .filter(|s| !s.trim().is_empty()) + .unwrap_or(default_program) + .to_string(); + let duration_seconds = obj + .and_then(|o| o.get("duration_seconds")) + .and_then(Value::as_f64) + .unwrap_or(default_duration) + .clamp(0.1, 10.0); + Animation { + program, + duration_seconds, + } + } + + pub fn lid_closed_animation(&self, default_program: &str) -> Animation { + self.animation("lid_closed_animation", default_program, 0.9) + } + + pub fn lid_open_animation(&self, default_program: &str) -> Animation { + self.animation("lid_open_animation", default_program, 1.0) + } + + fn battery_setting(&self, key: &str) -> Option<&Value> { + self.data.get("battery_monitoring")?.as_object()?.get(key) + } + + pub fn full_charge_watts(&self) -> Option { + self.battery_setting("full_charge_watts") + .and_then(Value::as_f64) + .filter(|w| *w > 0.0) + } + + pub fn show_on_power_change(&self) -> bool { + self.battery_setting("show_on_power_change") + .and_then(Value::as_bool) + .unwrap_or(true) + } + + pub fn power_change_preview_seconds(&self) -> f64 { + self.battery_setting("power_change_preview_seconds") + .and_then(Value::as_f64) + .filter(|s| *s > 0.0) + .unwrap_or(7.0) + } + + /// `Settings.session_open_action(provider, origin)`. + pub fn session_open_action(&self, provider: &str, origin: Option<&str>) -> Option { + let prefs = self.data.get("session_open_preferences")?.as_object()?; + let valid = |k: &str| { + prefs + .get(k) + .and_then(Value::as_str) + .filter(|a| SESSION_OPEN_CHOICES.contains(a)) + .map(str::to_string) + }; + let provider = provider.to_lowercase(); + if let Some(origin) = origin.filter(|o| !o.is_empty()) { + let key = normalize_origin_key(origin); + if let Some(a) = valid(&format!("origin:{provider}:{key}")) + .or_else(|| valid(&format!("origin:{key}"))) + { + return Some(a); + } + } + valid(&provider) + } +} + +pub fn normalize_origin_key(origin: &str) -> String { + static NON_ALNUM: LazyLock = LazyLock::new(|| Regex::new(r"[^a-z0-9]+").unwrap()); + let lowered = origin.trim().to_lowercase(); + let normalized = NON_ALNUM.replace_all(&lowered, "_"); + let normalized = normalized.trim_matches('_'); + if normalized.is_empty() { + "unknown".into() + } else { + normalized.into() + } +} + +fn sorted(value: &Value) -> Value { + match value { + Value::Object(map) => { + let mut keys: Vec<&String> = map.keys().collect(); + keys.sort(); + let mut out = Map::new(); + for k in keys { + out.insert(k.clone(), sorted(&map[k])); + } + Value::Object(out) + } + Value::Array(items) => Value::Array(items.iter().map(sorted).collect()), + other => other.clone(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const SAMPLE: &str = r#"{ + "closed_lid_awake_policy": "agents", + "devices": [{"brightness": 144, "id": "/Volumes/SidePulse", "led_display": "agent", "name": "SidePulse", "path": "/Volumes/SidePulse"}], + "led_display": "agent", + "session_open_preferences": {"claude": "terminal", "origin:codex:codex_ui": "app"}, + "setup_screen_completed": true, + "zzz_unknown": {"keep": [1, 2]} +}"#; + + #[test] + fn reads_python_settings_and_preserves_unknown_keys() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("settings.json"); + std::fs::write(&path, SAMPLE).unwrap(); + let mut s = Settings::load(&path); + assert_eq!(s.device_brightness("/Volumes/SidePulse"), 144); + assert_eq!(s.closed_lid_policy(), ClosedLidPolicy::Agents); + assert_eq!( + s.session_open_action("Claude", None).as_deref(), + Some("terminal") + ); + assert_eq!( + s.session_open_action("codex", Some("Codex UI")).as_deref(), + Some("app") + ); + assert_eq!(s.session_open_action("codex", None), None); + s.set_device_brightness("/Volumes/SidePulse", "SidePulse", 200); + s.set_device_display("/Volumes/Other", "Other", LedDisplay::Battery); + s.save().unwrap(); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.contains("\"zzz_unknown\": {\n \"keep\": [\n 1,\n 2\n ]\n }")); + let again = Settings::load(&path); + assert_eq!(again.device_brightness("/Volumes/SidePulse"), 200); + assert_eq!(again.device_display("/Volumes/Other"), LedDisplay::Battery); + assert_eq!(again.remembered_devices().len(), 2); + } + + #[test] + fn defaults_when_missing() { + let s = Settings::load(Path::new("/nonexistent/settings.json")); + assert_eq!(s.led_display(), LedDisplay::Agent); + assert_eq!(s.device_brightness("/Volumes/X"), 255); + assert!(s.show_on_power_change()); + assert_eq!(s.power_change_preview_seconds(), 7.0); + assert_eq!(s.lid_open_animation("p").duration_seconds, 1.0); + } +} diff --git a/crates/sidepulse-bar/src/ui.rs b/crates/sidepulse-bar/src/ui.rs new file mode 100644 index 0000000..e17e14e --- /dev/null +++ b/crates/sidepulse-bar/src/ui.rs @@ -0,0 +1,337 @@ +//! AppKit status item and menu (port of `build_menu` / `set_status` in `status_bar.py`). +//! The UI renders a plain [`MenuModel`] and reports clicks as [`Action`]s; it holds no app state. + +use std::cell::RefCell; + +use objc2::rc::Retained; +use objc2::runtime::{AnyObject, NSObject, ProtocolObject}; +use objc2::{define_class, msg_send, sel, MainThreadMarker, MainThreadOnly}; +use objc2_app_kit::{ + NSApplication, NSControlStateValueOff, NSControlStateValueOn, NSImage, NSMenu, NSMenuDelegate, + NSMenuItem, NSStatusBar, NSStatusItem, NSVariableStatusItemLength, +}; +use objc2_foundation::{NSObjectProtocol, NSString, NSURL}; + +use crate::session::state_for_mode; +use crate::settings::{ClosedLidPolicy, LedDisplay}; +use sidepulse_core::models::AgentMode; + +#[derive(Clone, Debug, PartialEq)] +pub enum Action { + OpenSession(String), + SetDisplay(String, LedDisplay), + SetBrightness(String, u8), + RemoveDevice(String), + SetLidPolicy(ClosedLidPolicy), + Quit, + /// The menu is about to open (`menuNeedsUpdate:`): refresh time-dependent rows. + MenuOpening, +} + +impl Action { + fn encode(&self) -> String { + match self { + Action::OpenSession(id) => format!("open\t{id}"), + Action::SetDisplay(p, d) => format!("display\t{p}\t{}", d.as_str()), + Action::SetBrightness(p, b) => format!("brightness\t{p}\t{b}"), + Action::RemoveDevice(p) => format!("remove\t{p}"), + Action::SetLidPolicy(l) => format!("lid\t{}", l.as_str()), + Action::Quit => "quit".into(), + Action::MenuOpening => "menu-opening".into(), + } + } + + fn decode(s: &str) -> Option { + let parts: Vec<&str> = s.split('\t').collect(); + Some(match parts.as_slice() { + ["open", id] => Action::OpenSession((*id).into()), + ["display", p, "agent"] => Action::SetDisplay((*p).into(), LedDisplay::Agent), + ["display", p, "battery"] => Action::SetDisplay((*p).into(), LedDisplay::Battery), + ["brightness", p, b] => Action::SetBrightness((*p).into(), b.parse().ok()?), + ["remove", p] => Action::RemoveDevice((*p).into()), + ["lid", l] => Action::SetLidPolicy(ClosedLidPolicy::parse(l)?), + ["quit"] => Action::Quit, + ["menu-opening"] => Action::MenuOpening, + _ => return None, + }) + } +} + +#[derive(Clone, Debug, PartialEq)] +pub struct SessionRow { + pub title: String, + pub mode: AgentMode, + pub agent_id: String, + pub tooltip: String, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct DeviceRow { + pub path: String, + pub name: String, + pub connected: bool, + pub display: LedDisplay, + pub brightness: u8, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct MenuModel { + pub sessions: Vec, + pub devices: Vec, + pub lid_policy: ClosedLidPolicy, + pub sleep_warning: Option, +} + +type Handler = Box; + +thread_local! { + static HANDLER: RefCell> = const { RefCell::new(None) }; +} + +define_class!( + #[unsafe(super(NSObject))] + #[thread_kind = MainThreadOnly] + #[name = "SidePulseMenuTarget"] + struct MenuTarget; + + impl MenuTarget { + #[unsafe(method(perform:))] + fn perform(&self, sender: &NSMenuItem) { + let Some(obj) = sender.representedObject() else { return }; + let Ok(text) = obj.downcast::() else { return }; + if let Some(action) = Action::decode(&text.to_string()) { + dispatch(action); + } + } + } + + unsafe impl NSObjectProtocol for MenuTarget {} + + unsafe impl NSMenuDelegate for MenuTarget { + /// Called just before the menu is shown; items may be replaced here. + #[unsafe(method(menuNeedsUpdate:))] + fn menu_needs_update(&self, _menu: &NSMenu) { + dispatch(Action::MenuOpening); + } + } +); + +fn dispatch(action: Action) { + HANDLER.with(|h| { + if let Some(handler) = h.borrow().as_ref() { + handler(action); + } + }); +} + +impl MenuTarget { + fn new(mtm: MainThreadMarker) -> Retained { + let this = mtm.alloc::().set_ivars(()); + unsafe { msg_send![super(this), init] } + } +} + +pub struct StatusUi { + mtm: MainThreadMarker, + item: Retained, + target: Retained, + /// One menu for the app's lifetime, refilled in place so it can be updated while opening. + menu: Retained, + last_mode: Option, + last_model: Option, +} + +fn symbol(name: &str, description: &str) -> Option> { + let img = NSImage::imageWithSystemSymbolName_accessibilityDescription( + &NSString::from_str(name), + Some(&NSString::from_str(description)), + )?; + img.setTemplate(true); + Some(img) +} + +impl StatusUi { + pub fn new(mtm: MainThreadMarker, handler: Box) -> Self { + HANDLER.with(|h| *h.borrow_mut() = Some(handler)); + let item = NSStatusBar::systemStatusBar().statusItemWithLength(NSVariableStatusItemLength); + let target = MenuTarget::new(mtm); + let menu = NSMenu::new(mtm); + menu.setAutoenablesItems(false); + // The delegate is weak; `target` is kept alive by `StatusUi`. + menu.setDelegate(Some(ProtocolObject::from_ref(&*target))); + item.setMenu(Some(&menu)); + Self { + mtm, + item, + target, + menu, + last_mode: None, + last_model: None, + } + } + + /// `set_status`: title, template symbol and tooltip; no-op when unchanged. + pub fn set_mode(&mut self, mode: AgentMode) { + let state = state_for_mode(mode); + if self.last_mode.map(|m| state_for_mode(m).label) == Some(state.label) { + return; + } + self.last_mode = Some(mode); + if let Some(button) = self.item.button(self.mtm) { + button.setTitle(&NSString::from_str(&format!(" {}", state.label))); + button.setImage(symbol(state.symbol, state.label).as_deref()); + button.setToolTip(Some(&NSString::from_str(&format!( + "SidePulse Agent Monitor: {}", + state.label + )))); + } + } + + fn item(&self, title: &str, action: Option<&Action>) -> Retained { + let item = NSMenuItem::new(self.mtm); + item.setTitle(&NSString::from_str(title)); + match action { + Some(a) => unsafe { + item.setTarget(Some(&self.target)); + item.setAction(Some(sel!(perform:))); + let payload = NSString::from_str(&a.encode()); + item.setRepresentedObject(Some(&payload as &AnyObject)); + }, + None => item.setEnabled(false), + } + item + } + + fn checked(&self, title: &str, action: &Action, on: bool) -> Retained { + let item = self.item(title, Some(action)); + item.setState(if on { + NSControlStateValueOn + } else { + NSControlStateValueOff + }); + item + } + + /// `build_menu`: refilled only when the model changed. + pub fn set_menu(&mut self, model: &MenuModel) { + if self.last_model.as_ref() == Some(model) { + return; + } + let menu = &self.menu; + menu.removeAllItems(); + let add = |i: &NSMenuItem| menu.addItem(i); + add(&self.item("SidePulse", None)); + add(&NSMenuItem::separatorItem(self.mtm)); + add(&self.item("Agents", None)); + if model.sessions.is_empty() { + add(&self.item("No recent sessions", None)); + } + for row in &model.sessions { + let item = self.item(&row.title, Some(&Action::OpenSession(row.agent_id.clone()))); + let state = state_for_mode(row.mode); + item.setImage(symbol(state.symbol, state.label).as_deref()); + item.setToolTip(Some(&NSString::from_str(&row.tooltip))); + add(&item); + } + + add(&NSMenuItem::separatorItem(self.mtm)); + add(&self.item("Devices", None)); + if model.devices.is_empty() { + add(&self.item("No SidePulse device found", None)); + } + for dev in &model.devices { + let item = self.item( + &dev.name, + Some(&Action::SetDisplay(dev.path.clone(), dev.display)), + ); + item.setState(if dev.connected { + NSControlStateValueOn + } else { + NSControlStateValueOff + }); + let sub = NSMenu::new(self.mtm); + sub.setAutoenablesItems(false); + sub.addItem(&self.checked( + "Agent Status", + &Action::SetDisplay(dev.path.clone(), LedDisplay::Agent), + dev.display == LedDisplay::Agent, + )); + sub.addItem(&self.checked( + "Battery Level", + &Action::SetDisplay(dev.path.clone(), LedDisplay::Battery), + dev.display == LedDisplay::Battery, + )); + sub.addItem(&NSMenuItem::separatorItem(self.mtm)); + let pct = (f64::from(dev.brightness) * 100.0 / 255.0).round() as u32; + sub.addItem(&self.item(&format!("Brightness {pct}%"), None)); + for level in [25u32, 50, 75, 100] { + let value = ((level as f64) * 255.0 / 100.0).round() as u8; + sub.addItem(&self.checked( + &format!(" {level}%"), + &Action::SetBrightness(dev.path.clone(), value), + dev.brightness == value, + )); + } + if !dev.connected { + sub.addItem(&NSMenuItem::separatorItem(self.mtm)); + sub.addItem(&self.item("Not connected", None)); + sub.addItem(&self.item("Remove", Some(&Action::RemoveDevice(dev.path.clone())))); + } + item.setSubmenu(Some(&sub)); + add(&item); + } + + add(&NSMenuItem::separatorItem(self.mtm)); + add(&self.item("Keep Awake With Lid Closed", None)); + for (title, policy) in [ + ("Never", ClosedLidPolicy::Never), + ("When Agents Work", ClosedLidPolicy::Agents), + ("Always", ClosedLidPolicy::Always), + ] { + add(&self.checked( + title, + &Action::SetLidPolicy(policy), + model.lid_policy == policy, + )); + } + if let Some(warning) = &model.sleep_warning { + add(&self.item(&format!("Sleep warning: {warning}"), None)); + } + + add(&NSMenuItem::separatorItem(self.mtm)); + let quit = self.item("Quit SidePulse", Some(&Action::Quit)); + quit.setKeyEquivalent(&NSString::from_str("q")); + add(&quit); + self.last_model = Some(model.clone()); + } +} + +pub fn open_url(url: &str) { + if let Some(url) = NSURL::URLWithString(&NSString::from_str(url)) { + objc2_app_kit::NSWorkspace::sharedWorkspace().openURL(&url); + } +} + +pub fn terminate(mtm: MainThreadMarker) { + NSApplication::sharedApplication(mtm).terminate(None); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn actions_round_trip() { + for a in [ + Action::OpenSession("claude:session:abc".into()), + Action::SetDisplay("/Volumes/Side Pulse".into(), LedDisplay::Battery), + Action::SetBrightness("/Volumes/SidePulse".into(), 191), + Action::RemoveDevice("/Volumes/X".into()), + Action::SetLidPolicy(ClosedLidPolicy::Agents), + Action::Quit, + Action::MenuOpening, + ] { + assert_eq!(Action::decode(&a.encode()), Some(a)); + } + } +} diff --git a/crates/sidepulse-core/Cargo.toml b/crates/sidepulse-core/Cargo.toml new file mode 100644 index 0000000..c9bcd8d --- /dev/null +++ b/crates/sidepulse-core/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "sidepulse-core" +description = "Shared SidePulse logic: event parsing, agent status rules, state, logs and IPC." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +publish.workspace = true + +[dependencies] +chrono.workspace = true +libc.workspace = true +regex.workspace = true +serde_json.workspace = true +shlex.workspace = true +socket2.workspace = true + +[dev-dependencies] +tempfile.workspace = true diff --git a/crates/sidepulse-core/examples/hwprobe.rs b/crates/sidepulse-core/examples/hwprobe.rs new file mode 100644 index 0000000..faf8dde --- /dev/null +++ b/crates/sidepulse-core/examples/hwprobe.rs @@ -0,0 +1,81 @@ +//! Read-only hardware probe: battery, lid, mounted devices and model watts, with per-read timing. +//! Writes nothing. Run with `cargo run -p sidepulse-core --example hwprobe`. + +use std::time::Instant; + +use sidepulse_core::{battery, devices, lid}; + +fn timed(label: &str, f: impl FnOnce() -> T) -> T { + let start = Instant::now(); + let value = f(); + println!("[{label}: {} us]", start.elapsed().as_micros()); + value +} + +fn main() { + let watts = timed( + "default_full_charge_watts (first)", + battery::default_full_charge_watts, + ); + println!("model full-charge watts: {watts}"); + timed( + "default_full_charge_watts (cached)", + battery::default_full_charge_watts, + ); + + let snapshot = timed("battery::read (first)", battery::read); + timed("battery::read (warm)", battery::read); + match &snapshot { + Some(s) => { + println!( + "battery: {}% {} plugged={} charged={} {:.2}V {:.3}A ({:+.1}W) cycles={} health={}%", + s.percent, + s.state_label(), + s.is_plugged, + s.is_charged, + s.voltage, + s.amperage, + s.battery_watts, + s.cycle_count, + s.health_percent + ); + println!( + "adapter: {:.1}W (rated {}W, {:.1}V x {:.2}A, {} PD profiles) ratio={:.3}", + s.adapter_power(), + s.adapter_watts, + s.adapter_voltage, + s.adapter_current, + s.pd_profiles.len(), + s.charge_speed_ratio(None) + ); + println!( + "battery program (8 LEDs):\n{}", + battery::battery_program(s, 8, None, 255) + ); + } + None => println!("battery: none"), + } + + let closed = timed("lid::clamshell_closed (first)", lid::clamshell_closed); + timed("lid::clamshell_closed (warm)", lid::clamshell_closed); + println!("lid closed: {closed:?}"); + let disabled = timed("lid::sleep_disabled", lid::sleep_disabled); + println!( + "sleep disabled: {disabled:?}; helper installed: {}", + lid::sleep_helper_installed() + ); + + let found = timed("devices::discover", devices::discover); + if found.is_empty() { + println!("devices: none"); + } + for d in &found { + println!( + "device: {} ({} LEDs, {:?}) -> {}", + d.name, + d.led_count, + d.reason, + d.target().display() + ); + } +} diff --git a/src/audit.rs b/crates/sidepulse-core/src/audit.rs similarity index 100% rename from src/audit.rs rename to crates/sidepulse-core/src/audit.rs diff --git a/crates/sidepulse-core/src/battery.rs b/crates/sidepulse-core/src/battery.rs new file mode 100644 index 0000000..164aa66 --- /dev/null +++ b/crates/sidepulse-core/src/battery.rs @@ -0,0 +1,1003 @@ +//! Battery state and battery LED programs (`battery.py`). +//! +//! API: +//! - [`BatterySnapshot`], [`PdProfile`]; [`read`] / [`read_with`] read `AppleSmartBattery` +//! natively via IOKit (`None` on a Mac without a battery or off macOS). +//! - [`snapshot_from_props`]: `snapshot_from_ioreg_props` over a JSON object, so parsing is +//! testable without hardware. +//! - [`battery_program`] / [`battery_program_with`]: `program_for_battery`; [`battery_fill`], +//! [`battery_color`], [`scale_hex_color`], [`charging_pulse_length_ms`]. +//! - [`should_rewrite`], [`charging_update_interval`]: charging re-animation cadence. +//! - [`BatteryLedController`]: Python's `BatteryLedController.sync_snapshot`. +//! - [`PowerChangePreview`]: `update_battery_power_preview` / `active_led_display_kind` timing. +//! - [`default_full_charge_watts`], [`full_charge_watts_for_product`], [`adapter_family_name`]. +//! +//! Differences from Python: no `ioreg -a` subprocess (properties come straight from +//! `IORegistryEntryCreateCFProperties`), and model detection reads the `IODeviceTree:/product` +//! entry directly without the `system_profiler` fallback (which never matched a 14/16-inch +//! model string that the device tree lacked). + +use std::path::Path; +use std::sync::OnceLock; +use std::time::{Duration, Instant}; + +use serde_json::{Map, Value}; + +use crate::devices::{ + apply_brightness, py_round, write_program_to, Device, SyncResult, ERROR_RETRY, +}; +use crate::pyjson::truthy; + +pub const BATTERY_LOW_RED: &str = "#FF2600"; +pub const BATTERY_MID_AMBER: &str = "#FFB000"; +pub const BATTERY_HIGH_GREEN: &str = "#00FF66"; +pub const BATTERY_CHARGING_MINT: &str = "#80FFC8"; +pub const BATTERY_OFF: &str = "#000000"; +/// `program_for_battery(transition_ms=360)`. +pub const DEFAULT_TRANSITION_MS: i64 = 360; +/// `DEFAULT_POWER_CHANGE_PREVIEW_SECONDS`. +pub const DEFAULT_POWER_CHANGE_PREVIEW: Duration = Duration::from_secs(7); + +/// `PDProfile`: one USB-PD source capability. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct PdProfile { + pub voltage: f64, + pub current: f64, +} + +impl PdProfile { + pub fn watts(&self) -> f64 { + self.voltage * self.current + } +} + +/// `BatterySnapshot`; field defaults match the Python dataclass. +#[derive(Clone, Debug, PartialEq)] +pub struct BatterySnapshot { + pub percent: i64, + pub is_charging: bool, + pub is_charged: bool, + pub is_plugged: bool, + pub battery_present: bool, + pub voltage: f64, + pub amperage: f64, + pub battery_watts: f64, + pub time_to_full: i64, + pub time_to_empty: i64, + pub cycle_count: i64, + pub temperature_c: Option, + pub design_capacity_mah: i64, + pub max_capacity_mah: i64, + pub current_capacity_mah: i64, + pub health_percent: i64, + pub condition: String, + pub adapter_connected: bool, + pub adapter_watts: i64, + pub adapter_voltage: f64, + pub adapter_current: f64, + pub adapter_name: String, + pub adapter_manufacturer: String, + pub adapter_model: String, + pub adapter_serial: String, + pub adapter_family: String, + pub pd_profiles: Vec, + pub full_charge_watts: f64, +} + +impl Default for BatterySnapshot { + fn default() -> Self { + Self { + percent: 0, + is_charging: false, + is_charged: false, + is_plugged: false, + battery_present: true, + voltage: 0.0, + amperage: 0.0, + battery_watts: 0.0, + time_to_full: -1, + time_to_empty: -1, + cycle_count: -1, + temperature_c: None, + design_capacity_mah: -1, + max_capacity_mah: -1, + current_capacity_mah: -1, + health_percent: -1, + condition: String::new(), + adapter_connected: false, + adapter_watts: -1, + adapter_voltage: 0.0, + adapter_current: 0.0, + adapter_name: String::new(), + adapter_manufacturer: String::new(), + adapter_model: String::new(), + adapter_serial: String::new(), + adapter_family: String::new(), + pd_profiles: Vec::new(), + full_charge_watts: 100.0, + } + } +} + +impl BatterySnapshot { + /// `adapter_power`: rated watts, else negotiated V x I, else the best PD profile. + pub fn adapter_power(&self) -> f64 { + if self.adapter_watts > 0 { + return self.adapter_watts as f64; + } + let negotiated = self.adapter_voltage * self.adapter_current; + if negotiated > 0.0 { + return negotiated; + } + self.pd_profiles + .iter() + .map(PdProfile::watts) + .fold(None, |best: Option, w| { + Some(best.map_or(w, |b| b.max(w))) + }) + .unwrap_or(0.0) + } + + /// `charge_speed_ratio(full_charge_watts)`; `None` or `0` fall back to the snapshot's value + /// (Python `full_charge_watts or self.full_charge_watts`). + pub fn charge_speed_ratio(&self, full_charge_watts: Option) -> f64 { + let baseline = full_charge_watts + .filter(|w| *w != 0.0) + .unwrap_or(self.full_charge_watts); + if baseline <= 0.0 { + return 0.0; + } + clamp(self.adapter_power() / baseline) + } + + /// `battery_state_label`. + pub fn state_label(&self) -> &'static str { + if self.is_charged { + "charged" + } else if self.is_charging { + "charging" + } else if self.is_plugged { + "plugged in" + } else { + "on battery" + } + } +} + +/// The top-level `AppleSmartBattery` keys `snapshot_from_ioreg_props` uses. +pub const BATTERY_KEYS: [&str; 19] = [ + "Voltage", + "Amperage", + "InstantAmperage", + "AppleRawMaxCapacity", + "AppleRawCurrentCapacity", + "DesignCapacity", + "MaxCapacity", + "CurrentCapacity", + "AdapterDetails", + "StateOfCharge", + "PermanentFailureStatus", + "BatteryInstalled", + "IsCharging", + "FullyCharged", + "ExternalConnected", + "AvgTimeToFull", + "AvgTimeToEmpty", + "CycleCount", + "Temperature", +]; + +/// Power-source change notifications (`IOPSNotificationCreateRunLoopSource`): plug, unplug, +/// charge level and time-remaining changes, delivered on the main run loop. Replaces re-reading +/// the battery on a fixed refresh timer. Removed on drop. +pub struct PowerSourceWatch { + #[cfg(target_os = "macos")] + _inner: crate::power::iokit::PowerSourceWatch, +} + +impl PowerSourceWatch { + /// Calls `on_change` on the main thread after each power-source change. `None` when + /// notifications are unavailable. Must be called on the main thread. + #[cfg(target_os = "macos")] + pub fn new(on_change: impl FnMut() + 'static) -> Option { + let inner = crate::power::iokit::PowerSourceWatch::new(Box::new(on_change))?; + Some(Self { _inner: inner }) + } + + #[cfg(not(target_os = "macos"))] + pub fn new(_on_change: impl FnMut() + 'static) -> Option { + None + } +} + +/// `read_battery_snapshot()` with the model's default full-charge watts. +pub fn read() -> Option { + read_with(None) +} + +/// `read_battery_snapshot(full_charge_watts=...)`: reads only [`BATTERY_KEYS`] from the +/// `AppleSmartBattery` service's property dictionary. +pub fn read_with(full_charge_watts: Option) -> Option { + let props = read_props()?; + let mut snapshot = snapshot_from_props(&props); + snapshot.full_charge_watts = full_charge_watts + .unwrap_or_else(default_full_charge_watts) + .max(1.0); + Some(snapshot) +} + +#[cfg(target_os = "macos")] +fn read_props() -> Option> { + use crate::power::iokit::{dict_get, IoObject}; + let service = IoObject::matching_service("AppleSmartBattery")?; + let dict = service.properties()?; + let mut props = Map::new(); + for key in BATTERY_KEYS { + if let Some(value) = dict_get(&dict, key) { + props.insert(key.to_string(), value); + } + } + Some(props) +} + +#[cfg(not(target_os = "macos"))] +fn read_props() -> Option> { + None +} + +/// `int_value(value, default)`: bools and ints as-is, floats truncated, anything else `default`. +fn int_value(value: Option<&Value>, default: i64) -> i64 { + match value { + Some(Value::Bool(b)) => i64::from(*b), + Some(Value::Number(n)) => n + .as_i64() + .or_else(|| n.as_u64().map(|u| u as i64)) + .or_else(|| n.as_f64().map(|f| f.trunc() as i64)) + .unwrap_or(default), + _ => default, + } +} + +fn str_value(value: Option<&Value>) -> String { + match value { + Some(Value::String(s)) => s.clone(), + _ => String::new(), + } +} + +/// `bool(props.get(key, default))`. +fn bool_or(props: &Map, key: &str, default: bool) -> bool { + props.get(key).map_or(default, |v| truthy(Some(v))) +} + +/// `temperature_celsius`. +fn temperature_celsius(value: Option<&Value>) -> Option { + let raw = int_value(value, -1); + (raw >= 0).then(|| raw as f64 / 100.0) +} + +/// `snapshot_from_ioreg_props`. `full_charge_watts` is left at the default 100; [`read_with`] +/// fills it in (Python sets it in `snapshot_with_full_charge_watts`). +pub fn snapshot_from_props(props: &Map) -> BatterySnapshot { + let voltage = int_value(props.get("Voltage"), 0) as f64 / 1000.0; + let mut amperage_ma = int_value(props.get("Amperage"), 0); + if amperage_ma == 0 { + amperage_ma = int_value(props.get("InstantAmperage"), 0); + } + let amperage = amperage_ma as f64 / 1000.0; + + let raw_max = int_value(props.get("AppleRawMaxCapacity"), -1); + let raw_current = int_value(props.get("AppleRawCurrentCapacity"), -1); + let design = int_value(props.get("DesignCapacity"), -1); + let max_capacity = if raw_max > 0 { + raw_max + } else { + int_value(props.get("MaxCapacity"), -1) + }; + let current_capacity = if raw_current >= 0 { + raw_current + } else { + int_value(props.get("CurrentCapacity"), -1) + }; + let health_percent = if raw_max > 0 && design > 0 { + py_round(raw_max as f64 / design as f64 * 100.0) + } else { + -1 + }; + + let empty = Map::new(); + let details = match props.get("AdapterDetails") { + Some(Value::Object(map)) => map, + _ => &empty, + }; + let adapter = parse_adapter_details(details); + + let mut percent = int_value(props.get("CurrentCapacity"), 0); + if !(0..=100).contains(&percent) { + percent = int_value(props.get("StateOfCharge"), 0); + } + + let condition = if int_value(props.get("PermanentFailureStatus"), 0) != 0 { + "Service Recommended" + } else if props.get("BatteryInstalled") != Some(&Value::Bool(false)) { + "Normal" + } else { + "" + }; + + BatterySnapshot { + percent: percent.clamp(0, 100), + is_charging: bool_or(props, "IsCharging", false), + is_charged: bool_or(props, "FullyCharged", false), + is_plugged: bool_or(props, "ExternalConnected", false), + battery_present: bool_or(props, "BatteryInstalled", true), + voltage, + amperage, + battery_watts: voltage * amperage, + time_to_full: int_value(props.get("AvgTimeToFull"), -1), + time_to_empty: int_value(props.get("AvgTimeToEmpty"), -1), + cycle_count: int_value(props.get("CycleCount"), -1), + temperature_c: temperature_celsius(props.get("Temperature")), + design_capacity_mah: design, + max_capacity_mah: max_capacity, + current_capacity_mah: current_capacity, + health_percent, + condition: condition.to_string(), + ..adapter + } +} + +/// `parse_adapter_details`, returned as a snapshot carrying only the adapter fields. +fn parse_adapter_details(details: &Map) -> BatterySnapshot { + let mut profiles: Vec = match details.get("UsbHvcMenu") { + Some(Value::Array(menu)) => menu + .iter() + .filter_map(Value::as_object) + .map(|entry| PdProfile { + voltage: int_value(entry.get("MaxVoltage"), 0) as f64 / 1000.0, + current: int_value(entry.get("MaxCurrent"), 0) as f64 / 1000.0, + }) + .filter(|p| p.voltage > 0.0 && p.current > 0.0) + .collect(), + _ => Vec::new(), + }; + // `list.sort` is stable, like `sort_by`. + profiles.sort_by(|a, b| a.watts().total_cmp(&b.watts())); + let voltage_mv = int_value(details.get("AdapterVoltage").or(details.get("Voltage")), 0); + BatterySnapshot { + adapter_connected: !details.is_empty(), + adapter_watts: int_value(details.get("Watts"), -1), + adapter_voltage: voltage_mv as f64 / 1000.0, + adapter_current: int_value(details.get("Current"), 0) as f64 / 1000.0, + adapter_name: str_value(details.get("Name")), + adapter_manufacturer: str_value(details.get("Manufacturer")), + adapter_model: str_value(details.get("Model")), + adapter_serial: str_value(details.get("SerialString").or(details.get("SerialNumber"))), + adapter_family: adapter_family_name(int_value(details.get("FamilyCode"), -1)), + pd_profiles: profiles, + ..BatterySnapshot::default() + } +} + +/// `adapter_family_name(code)`. +pub fn adapter_family_name(code: i64) -> String { + match code { + 0xE000_4000..=0xE000_4FFF => "USB-C Power Delivery".into(), + 0x0000_0003 => "MagSafe".into(), + 0x0000_0004 => "MagSafe 2".into(), + 0x0000_FF00 => "USB-C".into(), + c if c >= 0 => format!("0x{c:08x}"), + _ => String::new(), + } +} + +/// `clamp(value)` to 0..=1. +fn clamp(value: f64) -> f64 { + value.clamp(0.0, 1.0) +} + +/// `BatteryFill`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct BatteryFill { + pub full: usize, + pub partial: f64, + pub count: usize, +} + +/// `battery_fill(percent, led_count)`. +pub fn battery_fill(percent: i64, led_count: u8) -> BatteryFill { + let count = led_count.clamp(1, 8) as usize; + let clamped = percent.clamp(0, 100); + let raw = count as f64 * (clamped as f64 / 100.0); + let full = count.min(raw.floor() as usize); + let partial = if full >= count { + 0.0 + } else { + raw - full as f64 + }; + BatteryFill { + full, + partial, + count, + } +} + +/// `battery_fill_color`. +pub fn battery_fill_color(index: usize, fill: &BatteryFill, color: &str) -> String { + if index < fill.full { + color.to_string() + } else if index == fill.full && fill.partial > 0.0 { + scale_hex_color(color, fill.partial) + } else { + BATTERY_OFF.to_string() + } +} + +/// `scale_hex_color`: scales each channel of `#RRGGBB`; other strings pass through. +pub fn scale_hex_color(color: &str, ratio: f64) -> String { + let bytes = color.as_bytes(); + if bytes.len() != 7 || bytes[0] != b'#' || !bytes[1..].iter().all(u8::is_ascii_hexdigit) { + return color.to_string(); + } + let amount = ratio.clamp(0.0, 1.0); + let mut out = String::from("#"); + for i in [1, 3, 5] { + let channel = u8::from_str_radix(&color[i..i + 2], 16).unwrap_or(0); + out.push_str(&format!("{:02X}", py_round(f64::from(channel) * amount))); + } + out +} + +/// `battery_segment`. +fn battery_segment(index: usize, color: &str, transition_ms: i64) -> String { + if transition_ms <= 0 { + format!("{index}:{color}") + } else { + format!("{index}:{color} {transition_ms}ms ease") + } +} + +/// `battery_color(percent)`. +pub fn battery_color(percent: i64) -> &'static str { + if percent <= 20 { + BATTERY_LOW_RED + } else if percent <= 50 { + BATTERY_MID_AMBER + } else { + BATTERY_HIGH_GREEN + } +} + +/// `charging_pulse_length_ms(ratio)`: `round(180 + 1220 * ratio)`. +pub fn charging_pulse_length_ms(ratio: f64) -> i64 { + py_round(180.0 + 1220.0 * clamp(ratio)) +} + +/// `charging_update_interval_seconds(ratio)`: `max(0.9, 3.0 - 2.1 * ratio)` seconds. +pub fn charging_update_interval(ratio: f64) -> f64 { + (3.0 - 2.1 * clamp(ratio)).max(0.9) +} + +/// `should_rewrite_battery_program(snapshot, elapsed_seconds)`. +pub fn should_rewrite(snapshot: &BatterySnapshot, elapsed_seconds: f64) -> bool { + if !snapshot.is_plugged || snapshot.is_charged { + return false; + } + elapsed_seconds >= charging_update_interval(snapshot.charge_speed_ratio(None)) +} + +/// `program_for_battery(snapshot, led_count=..., full_charge_watts=..., brightness=...)`. +pub fn battery_program( + snapshot: &BatterySnapshot, + led_count: u8, + full_charge_watts: Option, + brightness: u8, +) -> String { + battery_program_with( + snapshot, + led_count, + full_charge_watts, + DEFAULT_TRANSITION_MS, + brightness, + ) +} + +/// [`battery_program`] with an explicit `transition_ms`. +pub fn battery_program_with( + snapshot: &BatterySnapshot, + led_count: u8, + full_charge_watts: Option, + transition_ms: i64, + brightness: u8, +) -> String { + let count = led_count.clamp(1, 8) as usize; + let percent = snapshot.percent.clamp(0, 100); + let fill = battery_fill(percent, count as u8); + let pulse_index = fill.full.min(count - 1); + let transition = transition_ms.max(0); + let row = |color_for: &dyn Fn(usize) -> String| { + (0..count) + .map(|i| battery_segment(i, &color_for(i), transition)) + .collect::>() + .join(";") + }; + + if !snapshot.is_plugged || snapshot.is_charged { + if snapshot.is_charged || percent >= 100 { + return apply_brightness(&row(&|_| BATTERY_HIGH_GREEN.to_string()), brightness); + } + let color = battery_color(percent); + return apply_brightness(&row(&|i| battery_fill_color(i, &fill, color)), brightness); + } + + let color = BATTERY_CHARGING_MINT; + let pulse_ms = charging_pulse_length_ms(snapshot.charge_speed_ratio(full_charge_watts)); + let program = format!( + "{}\n{pulse_index}:{color} {pulse_ms}ms pulse", + row(&|i| battery_fill_color(i, &fill, color)) + ); + apply_brightness(&program, brightness) +} + +/// `BatteryLedController` for one device: rewrites when the program changes, re-animates the +/// charging pulse on the [`should_rewrite`] cadence, and backs off for [`ERROR_RETRY`] after a +/// failed write of the same program. +#[derive(Debug)] +pub struct BatteryLedController { + pub device: Device, + pub error_retry: Duration, + last_program: Option, + last_error: Option, + last_attempt: Option, + last_write: Option, +} + +impl BatteryLedController { + pub fn new(device: Device) -> Self { + Self { + device, + error_retry: ERROR_RETRY, + last_program: None, + last_error: None, + last_attempt: None, + last_write: None, + } + } + + /// `reset()`. + pub fn reset(&mut self) { + self.last_program = None; + self.last_error = None; + self.last_attempt = None; + self.last_write = None; + } + + pub fn last_error(&self) -> Option<&str> { + self.last_error.as_deref() + } + + /// `sync_snapshot(snapshot)`. Like Python, the program uses the snapshot's own + /// `full_charge_watts`. + pub fn sync(&mut self, snapshot: &BatterySnapshot, brightness: u8, now: Instant) -> SyncResult { + self.sync_with(snapshot, brightness, now, write_program_to) + } + + /// [`BatteryLedController::sync`] with an injected writer (tests, dry runs). + pub fn sync_with( + &mut self, + snapshot: &BatterySnapshot, + brightness: u8, + now: Instant, + write: impl FnOnce(&Path, &str) -> std::io::Result<()>, + ) -> SyncResult { + let program = battery_program(snapshot, self.device.led_count, None, brightness); + let same = self.last_program.as_deref() == Some(program.as_str()); + if same && self.last_error.is_none() { + let elapsed = self.last_write.map_or(f64::INFINITY, |t| { + now.saturating_duration_since(t).as_secs_f64() + }); + if !should_rewrite(snapshot, elapsed) { + return Ok(None); + } + } + if same { + if let Some(error) = &self.last_error { + let recent = self + .last_attempt + .is_some_and(|t| now.saturating_duration_since(t) < self.error_retry); + if recent { + return Err(error.clone()); + } + } + } + self.last_attempt = Some(now); + self.last_program = Some(program.clone()); + match write(&self.device.target(), &program) { + Ok(()) => { + self.last_error = None; + self.last_write = Some(now); + Ok(Some(program)) + } + Err(e) => { + let message = e.to_string(); + self.last_error = Some(message.clone()); + Err(message) + } + } + } +} + +/// `update_battery_power_preview` + the preview half of `active_led_display_kind` +/// (status_bar.py): show the battery for a few seconds after the charger is (un)plugged. +#[derive(Debug, Default)] +pub struct PowerChangePreview { + last_connected: Option, + until: Option, +} + +impl PowerChangePreview { + /// Records the current plug state; starts a preview of `duration` when it flipped and + /// `enabled`. Returns whether a preview started. + pub fn observe( + &mut self, + plugged: bool, + enabled: bool, + duration: Duration, + now: Instant, + ) -> bool { + let flipped = self.last_connected.is_some_and(|last| last != plugged); + self.last_connected = Some(plugged); + if flipped && enabled { + self.until = Some(now + duration); + return true; + } + false + } + + /// Whether the battery display should currently override the agent display. + pub fn active(&self, now: Instant) -> bool { + self.until.is_some_and(|until| now < until) + } +} + +/// `default_full_charge_watts()`, cached for the process lifetime. +pub fn default_full_charge_watts() -> f64 { + static CACHE: OnceLock = OnceLock::new(); + *CACHE.get_or_init(|| { + let (product, chip) = read_product_tree(); + full_charge_watts_for_product(&product, &chip) + }) +} + +/// The model rule in `default_full_charge_watts`: 16-inch MacBook Pro 140 W, 14-inch with a Pro +/// or Max chip 96 W, other 14-inch 70 W, anything else 100 W. +pub fn full_charge_watts_for_product(product: &str, chip: &str) -> f64 { + let product = product.to_lowercase(); + let chip = chip.to_lowercase(); + if product.contains("macbook pro") { + if product.contains("16-inch") { + return 140.0; + } + if product.contains("14-inch") { + return if chip.contains("pro") || chip.contains("max") { + 96.0 + } else { + 70.0 + }; + } + } + 100.0 +} + +/// Reads `product-name`, `product-description` and `product-soc-name` from +/// `IODeviceTree:/product` (Python greps `ioreg -p IODeviceTree -n product` text). +#[cfg(target_os = "macos")] +fn read_product_tree() -> (String, String) { + use crate::power::iokit::{data_bytes, IoObject}; + let Some(entry) = IoObject::from_path("IODeviceTree:/product") else { + return (String::new(), String::new()); + }; + let text = |key: &str| -> String { + entry + .property(key) + .and_then(|v| data_bytes(&v)) + .map(|bytes| { + let end = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len()); + String::from_utf8_lossy(&bytes[..end]).into_owned() + }) + .unwrap_or_default() + }; + let product = format!("{} {}", text("product-name"), text("product-description")); + (product, text("product-soc-name")) +} + +#[cfg(not(target_os = "macos"))] +fn read_product_tree() -> (String, String) { + (String::new(), String::new()) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + use std::cell::Cell; + + fn props(value: Value) -> Map { + value.as_object().unwrap().clone() + } + + fn charging(percent: i64, adapter_watts: i64, full: f64) -> BatterySnapshot { + BatterySnapshot { + percent, + is_plugged: true, + is_charging: true, + adapter_watts, + full_charge_watts: full, + ..Default::default() + } + } + + fn unplugged(percent: i64) -> BatterySnapshot { + BatterySnapshot { + percent, + ..Default::default() + } + } + + /// `test_battery_parser_uses_adapter_watts_and_raw_capacity`. + #[test] + fn parser_uses_adapter_watts_and_raw_capacity() { + let s = snapshot_from_props(&props(json!({ + "CurrentCapacity": 50, "ExternalConnected": true, "IsCharging": true, + "FullyCharged": false, "Voltage": 12000, "Amperage": 1000, + "AppleRawCurrentCapacity": 4000, "AppleRawMaxCapacity": 8000, + "DesignCapacity": 10000, "CycleCount": 12, + "AdapterDetails": { + "Watts": 96, "AdapterVoltage": 20000, "Current": 4800, + "UsbHvcMenu": [ + {"MaxVoltage": 20000, "MaxCurrent": 4800}, + {"MaxVoltage": 5000, "MaxCurrent": 3000} + ] + } + }))); + assert_eq!(s.percent, 50); + assert!(s.is_plugged && s.is_charging && !s.is_charged); + assert_eq!(s.adapter_power(), 96.0); + assert_eq!(s.health_percent, 80); + assert_eq!(s.current_capacity_mah, 4000); + assert_eq!(s.max_capacity_mah, 8000); + assert_eq!(s.pd_profiles.len(), 2); + assert_eq!(s.pd_profiles[0].voltage, 5.0, "sorted by watts"); + assert_eq!(s.battery_watts, 12.0); + assert_eq!(s.cycle_count, 12); + assert_eq!(s.condition, "Normal"); + assert!(s.adapter_connected); + assert_eq!(s.temperature_c, None); + } + + #[test] + fn parser_fallbacks() { + let s = snapshot_from_props(&props(json!({ + "CurrentCapacity": 150, "StateOfCharge": 42, "Amperage": 0, + "InstantAmperage": -1500, "Voltage": 12000, "MaxCapacity": 90, + "PermanentFailureStatus": 1, "Temperature": 3012, "IsCharging": 1, + "AdapterDetails": {"Voltage": 9000, "Current": 2000, "FamilyCode": -536854518, + "SerialNumber": "abc"} + }))); + assert_eq!(s.percent, 42); + assert_eq!(s.amperage, -1.5); + assert_eq!(s.battery_watts, -18.0); + assert_eq!(s.max_capacity_mah, 90); + assert_eq!(s.current_capacity_mah, 150); + assert_eq!(s.health_percent, -1); + assert_eq!(s.condition, "Service Recommended"); + assert_eq!(s.temperature_c, Some(30.12)); + assert!(s.is_charging); + assert_eq!(s.adapter_watts, -1); + assert_eq!(s.adapter_power(), 18.0); + assert_eq!(s.adapter_serial, "abc"); + // Negative FamilyCode (as CF reports PD chargers) yields "" just like Python. + assert_eq!(s.adapter_family, ""); + + let none = snapshot_from_props(&props(json!({"BatteryInstalled": false}))); + assert_eq!(none.condition, ""); + assert!(!none.battery_present); + assert!(!none.adapter_connected); + assert_eq!(none.adapter_power(), 0.0); + } + + #[test] + fn adapter_power_falls_back_to_pd_profiles() { + let s = BatterySnapshot { + pd_profiles: vec![ + PdProfile { + voltage: 5.0, + current: 3.0, + }, + PdProfile { + voltage: 20.0, + current: 3.25, + }, + ], + ..Default::default() + }; + assert_eq!(s.adapter_power(), 65.0); + assert_eq!(s.charge_speed_ratio(Some(0.0)), 0.65); + assert_eq!(s.charge_speed_ratio(Some(50.0)), 1.0); + } + + #[test] + fn family_names() { + assert_eq!(adapter_family_name(0xE000_4005), "USB-C Power Delivery"); + assert_eq!(adapter_family_name(3), "MagSafe"); + assert_eq!(adapter_family_name(4), "MagSafe 2"); + assert_eq!(adapter_family_name(0xFF00), "USB-C"); + assert_eq!(adapter_family_name(0x12), "0x00000012"); + assert_eq!(adapter_family_name(-1), ""); + } + + /// Byte-exact against `program_for_battery` output captured from the Python source. + #[test] + fn programs_match_python() { + let mint_half = "0:#80FFC8 360ms ease;1:#80FFC8 360ms ease;2:#80FFC8 360ms ease;\ + 3:#80FFC8 360ms ease;4:#000000 360ms ease;5:#000000 360ms ease;6:#000000 360ms ease;\ + 7:#000000 360ms ease\n4:#80FFC8 790ms pulse"; + let cases: Vec<(BatterySnapshot, u8, &str)> = vec![ + (charging(50, 70, 140.0), 2, "0:#80FFC8 360ms ease;1:#000000 360ms ease\n1:#80FFC8 790ms pulse"), + (charging(50, 70, 140.0), 8, mint_half), + (unplugged(50), 2, "0:#FFB000 360ms ease;1:#000000 360ms ease"), + (unplugged(50), 8, "0:#FFB000 360ms ease;1:#FFB000 360ms ease;2:#FFB000 360ms ease;3:#FFB000 360ms ease;4:#000000 360ms ease;5:#000000 360ms ease;6:#000000 360ms ease;7:#000000 360ms ease"), + (unplugged(57), 2, "0:#00FF66 360ms ease;1:#00240E 360ms ease"), + (unplugged(57), 8, "0:#00FF66 360ms ease;1:#00FF66 360ms ease;2:#00FF66 360ms ease;3:#00FF66 360ms ease;4:#008F39 360ms ease;5:#000000 360ms ease;6:#000000 360ms ease;7:#000000 360ms ease"), + (charging(80, 140, 140.0), 2, "0:#80FFC8 360ms ease;1:#4D9978 360ms ease\n1:#80FFC8 1400ms pulse"), + (charging(80, 140, 140.0), 8, "0:#80FFC8 360ms ease;1:#80FFC8 360ms ease;2:#80FFC8 360ms ease;3:#80FFC8 360ms ease;4:#80FFC8 360ms ease;5:#80FFC8 360ms ease;6:#336650 360ms ease;7:#000000 360ms ease\n6:#80FFC8 1400ms pulse"), + (unplugged(100), 2, "0:#00FF66 360ms ease;1:#00FF66 360ms ease"), + (unplugged(15), 2, "0:#4C0B00 360ms ease;1:#000000 360ms ease"), + (unplugged(15), 8, "0:#FF2600 360ms ease;1:#330800 360ms ease;2:#000000 360ms ease;3:#000000 360ms ease;4:#000000 360ms ease;5:#000000 360ms ease;6:#000000 360ms ease;7:#000000 360ms ease"), + ( + BatterySnapshot { percent: 33, is_plugged: true, is_charging: true, adapter_voltage: 20.0, adapter_current: 3.34, full_charge_watts: 96.0, ..Default::default() }, + 8, + "0:#80FFC8 360ms ease;1:#80FFC8 360ms ease;2:#52A380 360ms ease;3:#000000 360ms ease;4:#000000 360ms ease;5:#000000 360ms ease;6:#000000 360ms ease;7:#000000 360ms ease\n2:#80FFC8 1029ms pulse", + ), + ( + BatterySnapshot { percent: 33, is_plugged: true, is_charging: true, adapter_voltage: 20.0, adapter_current: 3.34, full_charge_watts: 96.0, ..Default::default() }, + 2, + "0:#54A884 360ms ease;1:#000000 360ms ease\n0:#80FFC8 1029ms pulse", + ), + ( + BatterySnapshot { percent: 99, is_plugged: true, is_charged: true, ..Default::default() }, + 2, + "0:#00FF66 360ms ease;1:#00FF66 360ms ease", + ), + ( + BatterySnapshot { percent: 0, is_plugged: true, is_charging: true, ..Default::default() }, + 2, + "0:#000000 360ms ease;1:#000000 360ms ease\n0:#80FFC8 180ms pulse", + ), + ]; + for (snapshot, count, expected) in cases { + let program = battery_program(&snapshot, count, None, 255); + assert_eq!(program, expected, "{snapshot:?} x{count}"); + crate::devices::validate_program(&program).unwrap(); + assert!(!program.contains("repeat")); + } + assert_eq!( + battery_program(&unplugged(57), 8, None, 128), + "brightness 128\n0:#00FF66 360ms ease;1:#00FF66 360ms ease;2:#00FF66 360ms ease;3:#00FF66 360ms ease;4:#008F39 360ms ease;5:#000000 360ms ease;6:#000000 360ms ease;7:#000000 360ms ease" + ); + assert_eq!( + battery_program_with(&unplugged(57), 8, None, 0, 255), + "0:#00FF66;1:#00FF66;2:#00FF66;3:#00FF66;4:#008F39;5:#000000;6:#000000;7:#000000" + ); + } + + #[test] + fn pulse_length_and_cadence() { + for (ratio, ms, interval) in [ + (0.0, 180, 3.0), + (0.25, 485, 2.475), + (0.5, 790, 1.95), + (0.7, 1034, 1.53), + (1.0, 1400, 0.9), + ] { + assert_eq!(charging_pulse_length_ms(ratio), ms); + assert!((charging_update_interval(ratio) - interval).abs() < 1e-12); + } + assert_eq!(charging_pulse_length_ms(7.0), 1400); + let s = charging(50, 70, 140.0); + assert!(!should_rewrite(&s, 1.9)); + assert!(should_rewrite(&s, 1.95)); + assert!(!should_rewrite(&unplugged(50), 100.0)); + let charged = BatterySnapshot { + is_charged: true, + ..charging(100, 70, 140.0) + }; + assert!(!should_rewrite(&charged, 100.0)); + } + + #[test] + fn scale_hex_passthrough() { + assert_eq!(scale_hex_color("red", 0.5), "red"); + assert_eq!(scale_hex_color("#00ff66", 0.5), "#008033"); + assert_eq!(scale_hex_color("#FFFFFF", 2.0), "#FFFFFF"); + } + + #[test] + fn product_watts_rules() { + assert_eq!( + full_charge_watts_for_product("MacBook Pro (14-inch, Nov 2023)", "Apple M3 Max"), + 96.0 + ); + assert_eq!( + full_charge_watts_for_product("MacBook Pro (14-inch, Nov 2023)", "Apple M3"), + 70.0 + ); + assert_eq!( + full_charge_watts_for_product("MacBook Pro (16-inch, 2021)", "Apple M1 Pro"), + 140.0 + ); + assert_eq!( + full_charge_watts_for_product("MacBook Air (15-inch, M2, 2023)", "Apple M2"), + 100.0 + ); + assert_eq!(full_charge_watts_for_product("", ""), 100.0); + } + + /// `test_battery_led_controller_animates_charging_on_cadence` and + /// `test_battery_led_controller_skips_unchanged_static_level`. + #[test] + fn controller_cadence_and_static_dedupe() { + let ok = |_: &Path, _: &str| -> std::io::Result<()> { Ok(()) }; + let t0 = Instant::now(); + let at = |s: f64| t0 + Duration::from_secs_f64(s); + let dev = Device::from_path(Path::new("/tmp/fake/SidePulsePro")); + + let mut c = BatteryLedController::new(dev.clone()); + let s = charging(50, 70, 140.0); + assert!(c.sync_with(&s, 255, at(0.0), ok).unwrap().is_some()); + assert_eq!(c.sync_with(&s, 255, at(0.5), ok), Ok(None)); + assert!(c.sync_with(&s, 255, at(2.0), ok).unwrap().is_some()); + + let mut c = BatteryLedController::new(dev.clone()); + let s = unplugged(50); + assert!(c.sync_with(&s, 255, at(0.0), ok).unwrap().is_some()); + assert_eq!(c.sync_with(&s, 255, at(10.0), ok), Ok(None)); + assert!(c + .sync_with(&unplugged(51), 255, at(10.0), ok) + .unwrap() + .is_some()); + + let mut c = BatteryLedController::new(dev); + let calls = Cell::new(0); + let fail = |_: &Path, _: &str| -> std::io::Result<()> { + calls.set(calls.get() + 1); + Err(std::io::Error::other("busy")) + }; + assert!(c.sync_with(&s, 255, at(0.0), fail).is_err()); + assert_eq!(c.sync_with(&s, 255, at(5.0), fail), Err("busy".into())); + assert_eq!(calls.get(), 1); + assert!(c.sync_with(&s, 255, at(10.5), ok).unwrap().is_some()); + } + + #[test] + fn power_change_preview() { + let t0 = Instant::now(); + let mut p = PowerChangePreview::default(); + assert!(!p.observe(true, true, DEFAULT_POWER_CHANGE_PREVIEW, t0)); + assert!(!p.active(t0)); + assert!(p.observe(false, true, DEFAULT_POWER_CHANGE_PREVIEW, t0)); + assert!(p.active(t0 + Duration::from_secs(6))); + assert!(!p.active(t0 + Duration::from_secs(7))); + assert!(!p.observe(true, false, DEFAULT_POWER_CHANGE_PREVIEW, t0)); + } + + /// Non-destructive live read; run with `cargo test -p sidepulse-core -- --ignored --nocapture`. + #[test] + #[ignore] + fn live_battery_read() { + let t = Instant::now(); + let snapshot = read(); + println!("battery ({:?}): {snapshot:#?}", t.elapsed()); + println!("full-charge watts: {}", default_full_charge_watts()); + } +} diff --git a/src/collector.rs b/crates/sidepulse-core/src/collector.rs similarity index 100% rename from src/collector.rs rename to crates/sidepulse-core/src/collector.rs diff --git a/crates/sidepulse-core/src/devices.rs b/crates/sidepulse-core/src/devices.rs new file mode 100644 index 0000000..55bd05d --- /dev/null +++ b/crates/sidepulse-core/src/devices.rs @@ -0,0 +1,681 @@ +//! SidePulse device discovery, LED program writing and agent LED programs +//! (`device_writer.py` and `led_status.py`). +//! +//! API: +//! - [`Device`] (`root`, `name`, `led_count`, `reason`), [`Device::from_path`], [`Device::target`]. +//! - [`discover`] / [`discover_in`]: `discover_devices`. +//! - [`decode_simple_escapes`], [`validate_program`] ([`ProgramError`]), [`write_program`], +//! [`write_program_to`]. +//! - [`LedState`], [`led_state_for_mode`], [`agent_program`], [`rolling_program`], +//! [`apply_brightness`], [`normalize_brightness`], [`brightness_percent`], [`py_round`]. +//! - [`LedController`]: `AgentLedController` dedupe and error backoff, per device. +//! +//! Differences from Python: [`write_program_to`] does not create missing parent directories +//! (Python's `mkdir(parents=True)` could create a stray folder under `/Volumes` if a volume +//! unmounted between discovery and the write). + +use std::fmt; +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +use crate::models::AgentMode; +use crate::pyjson::splitlines; + +/// `DEFAULT_FILE_NAME`. +pub const LED_FILE_NAME: &str = "LEDS.LED"; +/// `KNOWN_LED_FILE_NAMES` (upper-cased). +pub const KNOWN_LED_FILE_NAMES: [&str; 1] = ["LEDS.LED"]; +/// `MAX_LED_BYTES`. +pub const MAX_LED_BYTES: usize = 512; +/// `MAX_LED_LINES`. +pub const MAX_LED_LINES: usize = 20; +/// `MOUNT_ROOT`. +pub const MOUNT_ROOT: &str = "/Volumes"; +/// `DEVICE_NAME_HINTS`. +pub const DEVICE_NAME_HINTS: [&str; 2] = ["sidepulsepro", "sidepulsedot"]; +/// `AgentLedController(error_retry_seconds=10.0)`. +pub const ERROR_RETRY: Duration = Duration::from_secs(10); + +pub const ASK_AMBER: &str = "#FF7A1A"; +pub const ERROR_RED: &str = "#FF2600"; +pub const WORKING_CYAN: &str = "#00E5FF"; +pub const DONE_GREEN: &str = "#00FF66"; +pub const IDLE_DIM: &str = "#020204"; + +/// Why a volume was treated as a device (`DeviceCandidate.reason`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DiscoveryReason { + /// `"contains LEDS.LED"`. + ContainsLedFile, + /// `"name matches device"`. + NameMatches, + /// Built from an explicit path. + Explicit, +} + +/// A mounted SidePulse Pro (8 LEDs) or SidePulse Dot (2 LEDs). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Device { + /// Volume root, e.g. `/Volumes/SidePulse`. + pub root: PathBuf, + /// Volume name. + pub name: String, + /// `led_count_for_target`: 2 for a Dot, otherwise 8. + pub led_count: u8, + pub reason: DiscoveryReason, +} + +impl Device { + /// `target_from_device_path`: accepts a volume root or a path to its `LEDS.LED`. + pub fn from_path(path: &Path) -> Self { + let root = if is_led_file(path) { + path.parent().unwrap_or(Path::new("")).to_path_buf() + } else { + path.to_path_buf() + }; + Self::with_reason(root, DiscoveryReason::Explicit) + } + + fn with_reason(root: PathBuf, reason: DiscoveryReason) -> Self { + let name = root + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let led_count = led_count_for_name(&name); + Self { + root, + name, + led_count, + reason, + } + } + + /// The `LEDS.LED` path. + pub fn target(&self) -> PathBuf { + self.root.join(LED_FILE_NAME) + } +} + +fn is_led_file(path: &Path) -> bool { + path.file_name() + .map(|n| KNOWN_LED_FILE_NAMES.contains(&n.to_string_lossy().to_uppercase().as_str())) + .unwrap_or(false) +} + +/// `normalized_device_name`: lower-cased alphanumerics only. +pub fn normalized_device_name(name: &str) -> String { + name.chars() + .flat_map(char::to_lowercase) + .filter(|c| c.is_alphanumeric()) + .collect() +} + +/// `is_device_name`. +pub fn is_device_name(name: &str) -> bool { + let normalized = normalized_device_name(name); + DEVICE_NAME_HINTS + .iter() + .any(|hint| normalized.contains(hint)) +} + +/// `led_count_for_target` applied to a volume name. +pub fn led_count_for_name(name: &str) -> u8 { + if normalized_device_name(name).contains("sidepulsedot") { + 2 + } else { + 8 + } +} + +/// `discover_devices()` under `/Volumes`. +pub fn discover() -> Vec { + discover_in(Path::new(MOUNT_ROOT)) +} + +/// `discover_devices(mount_root=...)`: volumes sorted by lower-cased name, skipping +/// `.timemachine` and `Macintosh HD`; a volume counts if it contains `LEDS.LED` or its name +/// matches a device hint. Unreadable entries are skipped. +pub fn discover_in(mount_root: &Path) -> Vec { + let Ok(entries) = fs::read_dir(mount_root) else { + return Vec::new(); + }; + let mut volumes: Vec<(String, PathBuf)> = entries + .filter_map(Result::ok) + .filter_map(|entry| { + let name = entry.file_name().to_string_lossy().into_owned(); + if name == ".timemachine" || name == "Macintosh HD" { + return None; + } + let path = entry.path(); + // `Path.is_dir()` follows symlinks; errors count as "not a directory". + fs::metadata(&path).ok().filter(|m| m.is_dir())?; + Some((name, path)) + }) + .collect(); + volumes.sort_by_key(|(name, _)| name.to_lowercase()); + volumes + .into_iter() + .filter_map(|(name, path)| { + if path.join(LED_FILE_NAME).exists() { + Some(Device::with_reason(path, DiscoveryReason::ContainsLedFile)) + } else if is_device_name(&name) { + Some(Device::with_reason(path, DiscoveryReason::NameMatches)) + } else { + None + } + }) + .collect() +} + +/// `decode_simple_escapes`: `\n`, `\r`, `\t` and `\\`; any other backslash is kept. +pub fn decode_simple_escapes(text: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut chars = text.chars().peekable(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + match chars.peek() { + Some('n') => out.push('\n'), + Some('r') => out.push('\r'), + Some('t') => out.push('\t'), + Some('\\') => out.push('\\'), + _ => { + out.push('\\'); + continue; + } + } + chars.next(); + } + out +} + +/// `DeviceWriteError` raised by `validate_led_text`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ProgramError { + Empty, + TooManyBytes(usize), + TooManyLines(usize), +} + +impl fmt::Display for ProgramError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Empty => write!(f, "LED program is empty."), + Self::TooManyBytes(n) => write!(f, "LED program is {n} bytes; max is {MAX_LED_BYTES}."), + Self::TooManyLines(n) => { + write!(f, "LED program has {n} lines; max is {MAX_LED_LINES}.") + } + } + } +} + +impl std::error::Error for ProgramError {} + +impl From for io::Error { + fn from(e: ProgramError) -> Self { + io::Error::new(io::ErrorKind::InvalidInput, e) + } +} + +/// `validate_led_text`: non-empty, at most 512 UTF-8 bytes and 20 lines (Python `splitlines`). +pub fn validate_program(text: &str) -> Result<(), ProgramError> { + if text.is_empty() { + return Err(ProgramError::Empty); + } + if text.len() > MAX_LED_BYTES { + return Err(ProgramError::TooManyBytes(text.len())); + } + let lines = splitlines(text).len().max(1); + if lines > MAX_LED_LINES { + return Err(ProgramError::TooManyLines(lines)); + } + Ok(()) +} + +/// `write_led_program(text, device_path=device)`. +pub fn write_program(device: &Device, text: &str) -> io::Result { + let target = device.target(); + write_program_to(&target, text)?; + Ok(target) +} + +/// Decodes escapes, validates and writes `text` to `target` (truncating, like `write_text`). +pub fn write_program_to(target: &Path, text: &str) -> io::Result<()> { + let program = decode_simple_escapes(text); + validate_program(&program)?; + fs::write(target, program.as_bytes()) +} + +/// `LedDisplayState`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum LedState { + Idle, + Working, + Done, + Ask, + Error, +} + +impl LedState { + pub fn value(self) -> &'static str { + match self { + Self::Idle => "idle", + Self::Working => "working", + Self::Done => "done", + Self::Ask => "ask", + Self::Error => "error", + } + } + + /// `LED_STATE_LABELS`. + pub fn label(self) -> &'static str { + match self { + Self::Idle => "Idle", + Self::Working => "Working", + Self::Done => "Done", + Self::Ask => "Ask", + Self::Error => "Error", + } + } +} + +/// `display_state_for_mode`. +pub fn led_state_for_mode(mode: AgentMode) -> LedState { + match mode { + AgentMode::BlockedError => LedState::Error, + AgentMode::WaitingForInput => LedState::Ask, + AgentMode::Working | AgentMode::ToolRunning | AgentMode::LongTaskProgress => { + LedState::Working + } + AgentMode::Completed => LedState::Done, + AgentMode::IdleReady | AgentMode::Unknown => LedState::Idle, + } +} + +/// `program_for_display_state(state, led_count=..., brightness=...)`. +pub fn agent_program(state: LedState, led_count: u8, brightness: u8) -> String { + let program = match state { + LedState::Idle => format!("off\n{IDLE_DIM} 7.2s pulse\nrepeat"), + LedState::Ask => format!("off\n{ASK_AMBER} 2.8s pulse\nrepeat"), + LedState::Error => format!( + "off 180ms cosine\n{ERROR_RED} 620ms pulse\noff 240ms ease-out\n\ + {ERROR_RED} 1.2s pulse\noff 1.1s ease-out\nrepeat" + ), + LedState::Done => format!("off 180ms cosine\n{DONE_GREEN} 3.6s pulse\nrepeat"), + LedState::Working => rolling_program(WORKING_CYAN, led_count), + }; + apply_brightness(&program, brightness) +} + +/// `rolling_program(color, led_count=...)`: a pulse walking across 2..=8 LEDs. +pub fn rolling_program(color: &str, led_count: u8) -> String { + let count = led_count.clamp(2, 8) as u32; + let delay_ms = if count == 2 { 360 } else { 150 }; + let segments: Vec = (0..count) + .map(|i| format!("{i}:{color} 1600ms pulse {}ms", i * delay_ms)) + .collect(); + format!("off 320ms cosine\n{}\nrepeat", segments.join("; ")) +} + +/// Python `round()` for floats (round half to even). +pub fn py_round(value: f64) -> i64 { + value.round_ties_even() as i64 +} + +/// `normalize_brightness`: round and clamp to 0..=255. +pub fn normalize_brightness(value: f64) -> u8 { + if value.is_nan() { + return 0; + } + py_round(value).clamp(0, 255) as u8 +} + +/// `brightness_percent`. +pub fn brightness_percent(value: u8) -> u8 { + py_round(f64::from(value) / 255.0 * 100.0) as u8 +} + +/// `apply_brightness`: prefixes `brightness N` below full brightness. +pub fn apply_brightness(program: &str, brightness: u8) -> String { + if brightness == 255 { + program.to_string() + } else { + format!("brightness {brightness}\n{program}") + } +} + +/// Outcome of a controller sync: `Ok(Some(program))` written, `Ok(None)` unchanged, `Err` when the +/// write failed now or is still inside the retry back-off. +pub type SyncResult = Result, String>; + +/// `AgentLedController` for one device: writes only when (state, brightness) changes, and after +/// a failed write retries the same state no sooner than [`ERROR_RETRY`]. +#[derive(Debug)] +pub struct LedController { + pub device: Device, + pub error_retry: Duration, + last: Option<(LedState, u8)>, + last_error: Option, + last_attempt: Option, +} + +impl LedController { + pub fn new(device: Device) -> Self { + Self { + device, + error_retry: ERROR_RETRY, + last: None, + last_error: None, + last_attempt: None, + } + } + + /// `reset()`: forces the next sync to write. + pub fn reset(&mut self) { + self.last = None; + self.last_error = None; + self.last_attempt = None; + } + + pub fn last_error(&self) -> Option<&str> { + self.last_error.as_deref() + } + + /// `sync_mode(mode)` with the controller's brightness passed in. + pub fn sync(&mut self, mode: AgentMode, brightness: u8, now: Instant) -> SyncResult { + self.sync_with(mode, brightness, now, write_program_to) + } + + /// [`LedController::sync`] with an injected writer (tests, dry runs). + pub fn sync_with( + &mut self, + mode: AgentMode, + brightness: u8, + now: Instant, + write: impl FnOnce(&Path, &str) -> io::Result<()>, + ) -> SyncResult { + let state = led_state_for_mode(mode); + let key = Some((state, brightness)); + if key == self.last { + match &self.last_error { + None => return Ok(None), + Some(error) => { + let recent = self + .last_attempt + .is_some_and(|t| now.saturating_duration_since(t) < self.error_retry); + if recent { + return Err(error.clone()); + } + } + } + } + self.last_attempt = Some(now); + self.last = key; + let program = agent_program(state, self.device.led_count, brightness); + match write(&self.device.target(), &program) { + Ok(()) => { + self.last_error = None; + Ok(Some(program)) + } + Err(e) => { + let message = e.to_string(); + self.last_error = Some(message.clone()); + Err(message) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + + fn working8() -> String { + "off 320ms cosine\n0:#00E5FF 1600ms pulse 0ms; 1:#00E5FF 1600ms pulse 150ms; \ + 2:#00E5FF 1600ms pulse 300ms; 3:#00E5FF 1600ms pulse 450ms; 4:#00E5FF 1600ms pulse 600ms; \ + 5:#00E5FF 1600ms pulse 750ms; 6:#00E5FF 1600ms pulse 900ms; 7:#00E5FF 1600ms pulse 1050ms\n\ + repeat" + .to_string() + } + + /// Byte-exact against `program_for_display_state` output captured from the Python source. + #[test] + fn agent_programs_match_python() { + let cases: [(LedState, u8, &str); 6] = [ + (LedState::Idle, 8, "off\n#020204 7.2s pulse\nrepeat"), + (LedState::Ask, 2, "off\n#FF7A1A 2.8s pulse\nrepeat"), + ( + LedState::Error, + 8, + "off 180ms cosine\n#FF2600 620ms pulse\noff 240ms ease-out\n#FF2600 1.2s pulse\noff 1.1s ease-out\nrepeat", + ), + (LedState::Done, 8, "off 180ms cosine\n#00FF66 3.6s pulse\nrepeat"), + ( + LedState::Working, + 2, + "off 320ms cosine\n0:#00E5FF 1600ms pulse 0ms; 1:#00E5FF 1600ms pulse 360ms\nrepeat", + ), + (LedState::Working, 8, ""), + ]; + for (state, count, expected) in cases { + let expected = if expected.is_empty() { + working8() + } else { + expected.to_string() + }; + assert_eq!( + agent_program(state, count, 255), + expected, + "{state:?}/{count}" + ); + assert_eq!( + agent_program(state, count, 128), + format!("brightness 128\n{expected}"), + "{state:?}/{count} dimmed" + ); + validate_program(&agent_program(state, count, 1)).unwrap(); + } + assert_eq!( + rolling_program(WORKING_CYAN, 0), + rolling_program(WORKING_CYAN, 2) + ); + assert_eq!(rolling_program(WORKING_CYAN, 20), working8()); + } + + #[test] + fn modes_map_to_states() { + assert_eq!( + led_state_for_mode(AgentMode::WaitingForInput), + LedState::Ask + ); + assert_eq!(led_state_for_mode(AgentMode::BlockedError), LedState::Error); + assert_eq!( + led_state_for_mode(AgentMode::ToolRunning), + LedState::Working + ); + assert_eq!( + led_state_for_mode(AgentMode::LongTaskProgress), + LedState::Working + ); + assert_eq!(led_state_for_mode(AgentMode::Completed), LedState::Done); + assert_eq!(led_state_for_mode(AgentMode::IdleReady), LedState::Idle); + assert_eq!(led_state_for_mode(AgentMode::Unknown), LedState::Idle); + } + + #[test] + fn brightness_rounds_like_python() { + assert_eq!(normalize_brightness(127.5), 128); + assert_eq!(normalize_brightness(128.5), 128); + assert_eq!(normalize_brightness(-3.0), 0); + assert_eq!(normalize_brightness(999.0), 255); + assert_eq!(brightness_percent(128), 50); + assert_eq!(apply_brightness("off", 255), "off"); + assert_eq!(apply_brightness("off", 0), "brightness 0\noff"); + } + + #[test] + fn escapes_and_limits() { + assert_eq!( + decode_simple_escapes(r"off\n#FF00FF pulse"), + "off\n#FF00FF pulse" + ); + assert_eq!(decode_simple_escapes(r"a\tb\rc\\d\xe\"), "a\tb\rc\\d\\xe\\"); + assert_eq!(validate_program(""), Err(ProgramError::Empty)); + assert_eq!( + validate_program(&"x".repeat(513)), + Err(ProgramError::TooManyBytes(513)) + ); + validate_program(&"x".repeat(512)).unwrap(); + validate_program(&vec!["off"; 20].join("\n")).unwrap(); + assert_eq!( + validate_program(&vec!["off"; 21].join("\n")), + Err(ProgramError::TooManyLines(21)) + ); + assert_eq!(validate_program("\n").map(|_| ()), Ok(())); + assert_eq!( + ProgramError::TooManyBytes(513).to_string(), + "LED program is 513 bytes; max is 512." + ); + } + + #[test] + fn device_names_and_counts() { + assert_eq!( + Device::from_path(Path::new("/Volumes/SidePulseDot/LEDS.LED")).led_count, + 2 + ); + assert_eq!( + Device::from_path(Path::new("/Volumes/SidePulsePro/LEDS.LED")).led_count, + 8 + ); + assert_eq!( + Device::from_path(Path::new("/Volumes/SidePulse")).led_count, + 8 + ); + assert!(is_device_name("SidePulse Pro")); + assert!(is_device_name("side-pulse_dot 2")); + assert!(!is_device_name("SidePulse")); + let d = Device::from_path(Path::new("/Volumes/SidePulseDot/leds.led")); + assert_eq!(d.root, PathBuf::from("/Volumes/SidePulseDot")); + assert_eq!(d.target(), PathBuf::from("/Volumes/SidePulseDot/LEDS.LED")); + } + + #[test] + fn discovery_in_temp_dir() { + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + fs::create_dir(root.join("SidePulseDot")).unwrap(); + fs::create_dir(root.join("SidePulse")).unwrap(); + fs::write(root.join("SidePulse").join("LEDS.LED"), "off").unwrap(); + fs::create_dir(root.join("USB Drive")).unwrap(); + fs::write(root.join("USB Drive").join("LEDS.TXT"), "off").unwrap(); + fs::create_dir(root.join(".timemachine")).unwrap(); + fs::write(root.join(".timemachine").join("LEDS.LED"), "off").unwrap(); + fs::write(root.join("sidepulsepro-file"), "not a dir").unwrap(); + fs::create_dir(root.join("Macintosh HD")).unwrap(); + fs::write(root.join("Macintosh HD").join("LEDS.LED"), "off").unwrap(); + + let found = discover_in(root); + let names: Vec<_> = found.iter().map(|d| d.name.as_str()).collect(); + assert_eq!(names, ["SidePulse", "SidePulseDot"]); + assert_eq!(found[0].reason, DiscoveryReason::ContainsLedFile); + assert_eq!(found[0].led_count, 8); + assert_eq!(found[1].reason, DiscoveryReason::NameMatches); + assert_eq!(found[1].led_count, 2); + assert_eq!( + found[1].target(), + root.join("SidePulseDot").join("LEDS.LED") + ); + assert!(discover_in(&root.join("missing")).is_empty()); + } + + #[test] + fn write_decodes_escapes_and_keeps_old_files() { + let tmp = tempfile::tempdir().unwrap(); + let dev_root = tmp.path().join("SidePulseDot"); + fs::create_dir(&dev_root).unwrap(); + fs::write(dev_root.join("LEDS.TXT"), "off").unwrap(); + let device = Device::from_path(&dev_root); + let target = write_program(&device, r"off\n#FF00FF pulse").unwrap(); + assert_eq!(target, dev_root.join("LEDS.LED")); + assert_eq!(fs::read_to_string(&target).unwrap(), "off\n#FF00FF pulse"); + assert_eq!( + fs::read_to_string(dev_root.join("LEDS.TXT")).unwrap(), + "off" + ); + assert!(write_program(&device, &"x".repeat(513)).is_err()); + // Missing volume: no directory is created. + let gone = Device::from_path(&tmp.path().join("SidePulsePro")); + assert!(write_program(&gone, "off").is_err()); + assert!(!tmp.path().join("SidePulsePro").exists()); + } + + /// `test_agent_led_controller_skips_unchanged_state` and `test_write_mode_to_leds_*`. + #[test] + fn controller_dedupes_by_state_and_brightness() { + let tmp = tempfile::tempdir().unwrap(); + let dev_root = tmp.path().join("SidePulseDot"); + fs::create_dir(&dev_root).unwrap(); + let mut c = LedController::new(Device::from_path(&dev_root)); + let now = Instant::now(); + assert!(c.sync(AgentMode::Completed, 255, now).unwrap().is_some()); + assert_eq!(c.sync(AgentMode::Completed, 255, now), Ok(None)); + let third = c + .sync(AgentMode::WaitingForInput, 255, now) + .unwrap() + .unwrap(); + assert!(third.contains("#FF7A1A 2.8s pulse")); + assert_eq!( + fs::read_to_string(dev_root.join("LEDS.LED")).unwrap(), + third + ); + assert_eq!( + c.sync(AgentMode::Working, 255, now).unwrap().unwrap(), + "off 320ms cosine\n0:#00E5FF 1600ms pulse 0ms; 1:#00E5FF 1600ms pulse 360ms\nrepeat" + ); + // Same LED state from a different mode is not rewritten. + assert_eq!(c.sync(AgentMode::ToolRunning, 255, now), Ok(None)); + assert_eq!( + c.sync(AgentMode::Completed, 64, now).unwrap().unwrap(), + "brightness 64\noff 180ms cosine\n#00FF66 3.6s pulse\nrepeat" + ); + c.reset(); + assert!(c.sync(AgentMode::Completed, 64, now).unwrap().is_some()); + } + + #[test] + fn controller_backs_off_after_error() { + let mut c = LedController::new(Device::from_path(Path::new("/nonexistent/SidePulsePro"))); + let t0 = Instant::now(); + let calls = Cell::new(0); + let failing = |_: &Path, _: &str| -> io::Result<()> { + calls.set(calls.get() + 1); + Err(io::Error::other("offline")) + }; + assert_eq!( + c.sync_with(AgentMode::Working, 255, t0, failing), + Err("offline".into()) + ); + let t5 = t0 + Duration::from_secs(5); + assert_eq!( + c.sync_with(AgentMode::Working, 255, t5, failing), + Err("offline".into()) + ); + assert_eq!(calls.get(), 1, "retry suppressed inside back-off"); + // A different state retries immediately. + assert!(c.sync_with(AgentMode::Completed, 255, t5, failing).is_err()); + assert_eq!(calls.get(), 2); + let t16 = t0 + Duration::from_secs(16); + let ok = |_: &Path, _: &str| -> io::Result<()> { Ok(()) }; + assert!(c + .sync_with(AgentMode::Completed, 255, t16, ok) + .unwrap() + .is_some()); + assert_eq!(c.sync_with(AgentMode::Completed, 255, t16, ok), Ok(None)); + } +} diff --git a/src/hook.rs b/crates/sidepulse-core/src/hook.rs similarity index 100% rename from src/hook.rs rename to crates/sidepulse-core/src/hook.rs diff --git a/src/ipc.rs b/crates/sidepulse-core/src/ipc.rs similarity index 100% rename from src/ipc.rs rename to crates/sidepulse-core/src/ipc.rs diff --git a/src/lib.rs b/crates/sidepulse-core/src/lib.rs similarity index 78% rename from src/lib.rs rename to crates/sidepulse-core/src/lib.rs index a0829c4..aeb34c8 100644 --- a/src/lib.rs +++ b/crates/sidepulse-core/src/lib.rs @@ -2,11 +2,16 @@ //! the modules are shared with the status-bar core in later phases. pub mod audit; +pub mod battery; pub mod collector; +pub mod devices; pub mod hook; pub mod ipc; +pub mod lid; pub mod logrot; pub mod models; +pub mod monitor; pub mod origin; +pub mod power; pub mod providers; pub mod pyjson; diff --git a/crates/sidepulse-core/src/lid.rs b/crates/sidepulse-core/src/lid.rs new file mode 100644 index 0000000..9b4c150 --- /dev/null +++ b/crates/sidepulse-core/src/lid.rs @@ -0,0 +1,563 @@ +//! Lid (clamshell) state, lid animations and the closed-lid awake policy (`lid_sleep.py`, plus the +//! default lid animations from `settings.py`). +//! +//! API: +//! - [`clamshell_closed`] / [`sleep_disabled`]: `AppleClamshellState` / `SleepDisabled` read from +//! `IOPMrootDomain` natively (`None` when unavailable, e.g. desktops or non-macOS). +//! - [`DEFAULT_CLOSED_PROGRAM`], [`DEFAULT_OPEN_PROGRAM`] (+ durations), [`default_closed_program`], +//! [`default_open_program`], [`lid_animation_program`] (`program_for_lid_animation`). +//! - [`ClosedLidPolicy`], [`closed_lid_awake_should_hold`]. +//! - [`ClosedLidAwake`]: `ClosedLidAwakeController`, generic over a [`Hold`] and a [`SleepControl`]; +//! [`PmsetSleepControl`] runs `sudo -n /usr/bin/pmset -a disablesleep 0|1`. +//! - [`sleep_helper_installed`], [`sleep_helper_sudoers_rule`], [`SLEEP_HELPER_SUDOERS_PATH`]. +//! +//! Differences from Python: the lid and `SleepDisabled` state are IOKit property reads instead of +//! `ioreg` subprocesses every second, and the user-mode hold is an in-process IOPM assertion +//! instead of `caffeinate -dimsu -w `. The install hint names `sidepulse` without resolving +//! it on `PATH`. + +use std::path::Path; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +use crate::devices::{apply_brightness, decode_simple_escapes, validate_program, ProgramError}; +use crate::power::{AssertionHold, Hold}; + +/// `SLEEP_HELPER_SUDOERS_PATH`. +pub const SLEEP_HELPER_SUDOERS_PATH: &str = "/etc/sudoers.d/sidepulse-disablesleep"; +/// `LID_POLL_SECONDS`. +pub const LID_POLL: Duration = Duration::from_secs(1); + +/// `DEFAULT_LID_CLOSED_ANIMATION_PROGRAM`. +pub const DEFAULT_CLOSED_PROGRAM: &str = "off 90ms cosine\n\ +0:#FF7A00 180ms ease; 7:#FF7A00 180ms ease; 1:#FF7A00 180ms ease 80ms; 6:#FF7A00 180ms ease 80ms\n\ +2:#FF4A00 180ms ease; 5:#FF4A00 180ms ease; 3:#FF3000 180ms ease 80ms; 4:#FF3000 180ms ease 80ms\n\ +off 360ms ease-out"; +/// `DEFAULT_LID_OPEN_ANIMATION_PROGRAM`. +pub const DEFAULT_OPEN_PROGRAM: &str = "off 90ms cosine\n\ +3:#00E5FF 180ms ease; 4:#00E5FF 180ms ease; 2:#00E5FF 180ms ease 80ms; 5:#00E5FF 180ms ease 80ms\n\ +1:#00FFB0 180ms ease; 6:#00FFB0 180ms ease; 0:#00FF66 180ms ease 80ms; 7:#00FF66 180ms ease 80ms\n\ +#00FF66 220ms ease\n\ +off 320ms ease-out"; +/// `DEFAULT_LID_CLOSED_ANIMATION_SECONDS`. +pub const DEFAULT_CLOSED_DURATION: Duration = Duration::from_millis(900); +/// `DEFAULT_LID_OPEN_ANIMATION_SECONDS`. +pub const DEFAULT_OPEN_DURATION: Duration = Duration::from_millis(1000); + +/// `True` when the lid is closed, `None` if the state cannot be read. +#[cfg(target_os = "macos")] +pub fn clamshell_closed() -> Option { + root_domain_bool("AppleClamshellState") +} + +/// `read_sleep_disabled()`: whether `pmset disablesleep` is in effect. +#[cfg(target_os = "macos")] +pub fn sleep_disabled() -> Option { + root_domain_bool("SleepDisabled") +} + +#[cfg(target_os = "macos")] +fn root_domain_bool(key: &str) -> Option { + use crate::power::iokit::{to_json, IoObject}; + let root = IoObject::matching_service("IOPMrootDomain")?; + let value = root.property(key)?; + match to_json(value.as_ptr()) { + serde_json::Value::Bool(b) => Some(b), + serde_json::Value::Number(n) => n.as_i64().map(|v| v != 0), + _ => None, + } +} + +#[cfg(not(target_os = "macos"))] +pub fn clamshell_closed() -> Option { + None +} + +/// `kIOPMMessageClamshellStateChange` = `iokit_family_msg(sub_iokit_powermanagement, 0x100)`: +/// `sys_iokit` (0x38 << 26) | `err_sub(13)` (13 << 14) | 0x100 = `0xE0034100`. `IOPMrootDomain` +/// sends it as a general-interest message when `AppleClamshellState` or +/// `AppleClamshellCausesSleep` changes. +pub const CLAMSHELL_STATE_CHANGE_MESSAGE: u32 = (0x38 << 26) | (13 << 14) | 0x100; + +/// A registration for clamshell change notifications on `IOPMrootDomain`, delivered on the main +/// run loop (replaces the Python app's 1 s `ioreg` poll). Unregistered on drop. +pub struct ClamshellWatch { + #[cfg(target_os = "macos")] + _inner: crate::power::iokit::InterestWatch, +} + +impl ClamshellWatch { + /// Calls `on_change` on the main thread whenever the clamshell state may have changed (read + /// it again with [`clamshell_closed`]). `None` when notifications are unavailable. Must be + /// called on the main thread, which must run its run loop. + #[cfg(target_os = "macos")] + pub fn new(mut on_change: impl FnMut() + 'static) -> Option { + let inner = crate::power::iokit::InterestWatch::new( + "IOPMrootDomain", + Box::new(move |message| { + if message == CLAMSHELL_STATE_CHANGE_MESSAGE { + on_change(); + } + }), + )?; + Some(Self { _inner: inner }) + } + + #[cfg(not(target_os = "macos"))] + pub fn new(_on_change: impl FnMut() + 'static) -> Option { + None + } +} + +#[cfg(not(target_os = "macos"))] +pub fn sleep_disabled() -> Option { + None +} + +/// `default_lid_animation(LID_ANIMATION_CLOSED).program` at the given brightness. +pub fn default_closed_program(brightness: u8) -> String { + apply_brightness(DEFAULT_CLOSED_PROGRAM, brightness) +} + +/// `default_lid_animation(LID_ANIMATION_OPEN).program` at the given brightness. +pub fn default_open_program(brightness: u8) -> String { + apply_brightness(DEFAULT_OPEN_PROGRAM, brightness) +} + +/// `program_for_lid_animation` (status_bar.py): decode escapes, validate both the program and its +/// dimmed form (`validate_lid_animation`), then apply brightness. +pub fn lid_animation_program(program: &str, brightness: u8) -> Result { + let decoded = decode_simple_escapes(program); + validate_program(&decoded)?; + validate_program(&apply_brightness(&decoded, 1))?; + Ok(apply_brightness(&decoded, brightness)) +} + +/// `CLOSED_LID_AWAKE_CHOICES`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum ClosedLidPolicy { + #[default] + Never, + Agents, + Always, +} + +impl ClosedLidPolicy { + pub fn value(self) -> &'static str { + match self { + Self::Never => "never", + Self::Agents => "agents", + Self::Always => "always", + } + } + + pub fn parse(text: &str) -> Option { + match text { + "never" => Some(Self::Never), + "agents" => Some(Self::Agents), + "always" => Some(Self::Always), + _ => None, + } + } +} + +/// `closed_lid_awake_should_hold`. +pub fn closed_lid_awake_should_hold(policy: ClosedLidPolicy, agents_active: bool) -> bool { + match policy { + ClosedLidPolicy::Always => true, + ClosedLidPolicy::Agents => agents_active, + ClosedLidPolicy::Never => false, + } +} + +/// The `pmset disablesleep` side of the closed-lid controller. +pub trait SleepControl { + /// `sleep_disabled_reader`. + fn read(&mut self) -> Result, String>; + /// `sleep_disabled_setter`. + fn set(&mut self, disabled: bool) -> Result<(), String>; +} + +/// Real [`SleepControl`]: IOKit read, non-interactive `sudo -n pmset` write. +#[derive(Debug, Default)] +pub struct PmsetSleepControl; + +impl SleepControl for PmsetSleepControl { + fn read(&mut self) -> Result, String> { + Ok(sleep_disabled()) + } + + fn set(&mut self, disabled: bool) -> Result<(), String> { + run_sudo_pmset_disablesleep(disabled) + } +} + +/// `sleep_helper_installed()`. +pub fn sleep_helper_installed() -> bool { + Path::new(SLEEP_HELPER_SUDOERS_PATH).exists() +} + +/// `sleep_helper_install_command()`. +pub fn sleep_helper_install_command() -> String { + "sudo sidepulse status-bar install-sleep-helper".into() +} + +/// `sleep_helper_sudoers_rule(user)`: `None` for a user name sudoers could misparse. +pub fn sleep_helper_sudoers_rule(user: &str) -> Option { + let valid = !user.is_empty() + && user + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')); + valid.then(|| { + format!( + "{user} ALL=(root) NOPASSWD: /usr/bin/pmset -a disablesleep 0, /usr/bin/pmset -a disablesleep 1\n" + ) + }) +} + +/// `run_sudo_pmset_disablesleep`: never prompts (`sudo -n`), gives up after 5 s. +pub fn run_sudo_pmset_disablesleep(disabled: bool) -> Result<(), String> { + let value = if disabled { "1" } else { "0" }; + let mut child = Command::new("/usr/bin/sudo") + .args(["-n", "/usr/bin/pmset", "-a", "disablesleep", value]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| { + format!( + "Lid-closed awake needs one-time setup: {} ({e})", + sleep_helper_install_command() + ) + })?; + let deadline = Instant::now() + Duration::from_secs(5); + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break Some(status), + Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(20)), + _ => { + let _ = child.kill(); + let _ = child.wait(); + break None; + } + } + }; + if status.is_some_and(|s| s.success()) { + return Ok(()); + } + let mut stderr = String::new(); + if let Some(mut pipe) = child.stderr.take() { + use std::io::Read; + let _ = pipe.read_to_string(&mut stderr); + } + let detail = stderr + .trim() + .lines() + .next() + .map(|l| format!(" ({l})")) + .unwrap_or_default(); + Err(format!( + "Lid-closed awake needs one-time setup: {}{detail}", + sleep_helper_install_command() + )) +} + +/// `ClosedLidAwakeController`. +pub struct ClosedLidAwake { + hold: H, + sleep: S, + /// `use_system_disable`; callers pass [`sleep_helper_installed`]. + use_system_disable: bool, + /// `changed_system_disable`: we turned `disablesleep` on and must turn it off again. + pub changed_system_disable: bool, + system_disable_attempted: bool, + pub last_error: Option, + pub last_policy: ClosedLidPolicy, + pub last_requested: bool, +} + +impl Default for ClosedLidAwake { + fn default() -> Self { + Self::new( + AssertionHold::new("SidePulse closed-lid awake"), + PmsetSleepControl, + sleep_helper_installed(), + ) + } +} + +impl ClosedLidAwake { + pub fn new(hold: H, sleep: S, use_system_disable: bool) -> Self { + Self { + hold, + sleep, + use_system_disable, + changed_system_disable: false, + system_disable_attempted: false, + last_error: None, + last_policy: ClosedLidPolicy::Never, + last_requested: false, + } + } + + pub fn hold(&self) -> &H { + &self.hold + } + + pub fn sleep_control(&self) -> &S { + &self.sleep + } + + /// `set_use_system_disable`. + pub fn set_use_system_disable(&mut self, enabled: bool) { + if self.use_system_disable == enabled { + return; + } + self.use_system_disable = enabled; + self.system_disable_attempted = false; + if !enabled { + let mut errors = Vec::new(); + self.release_system_disable(&mut errors); + self.last_error = join_errors(errors); + } + } + + /// `update(policy, agents_active=...)`: returns [`Self::active`]. + pub fn update(&mut self, policy: ClosedLidPolicy, agents_active: bool) -> bool { + let should_hold = closed_lid_awake_should_hold(policy, agents_active); + if policy != self.last_policy { + self.system_disable_attempted = false; + } + self.last_policy = policy; + self.last_requested = should_hold; + if should_hold { + self.ensure_awake(); + } else { + self.release(); + } + self.active() + } + + fn ensure_awake(&mut self) { + let mut errors = Vec::new(); + if self.use_system_disable && !self.changed_system_disable && !self.system_disable_attempted + { + self.system_disable_attempted = true; + // Only touch the setting when it is not already on, so we never revert someone + // else's `disablesleep 1`. + let result = self.sleep.read().and_then(|already| match already { + Some(true) => Ok(()), + _ => self + .sleep + .set(true) + .map(|()| self.changed_system_disable = true), + }); + if let Err(e) = result { + errors.push(format!("disablesleep: {e}")); + } + } + if !self.hold.is_held() { + if let Err(e) = self.hold.acquire() { + errors.push(format!("caffeinate: {e}")); + } + } + self.last_error = join_errors(errors); + } + + /// `release()`. + pub fn release(&mut self) { + self.hold.release(); + let mut errors = Vec::new(); + self.release_system_disable(&mut errors); + self.last_error = join_errors(errors); + } + + fn release_system_disable(&mut self, errors: &mut Vec) { + if self.changed_system_disable { + match self.sleep.set(false) { + Ok(()) => { + self.changed_system_disable = false; + self.system_disable_attempted = false; + } + Err(e) => errors.push(format!("disablesleep: {e}")), + } + } else { + self.system_disable_attempted = false; + } + } + + /// `active()`. + pub fn active(&self) -> bool { + self.hold.is_held() || self.changed_system_disable + } +} + +fn join_errors(errors: Vec) -> Option { + (!errors.is_empty()).then(|| errors.join("; ")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn clamshell_message_matches_the_iopm_header() { + // Value of kIOPMMessageClamshellStateChange from . + assert_eq!(CLAMSHELL_STATE_CHANGE_MESSAGE, 0xE003_4100); + } + + #[derive(Default)] + struct FakeHold { + held: bool, + acquires: usize, + releases: usize, + } + + impl Hold for FakeHold { + fn acquire(&mut self) -> Result<(), String> { + self.held = true; + self.acquires += 1; + Ok(()) + } + fn release(&mut self) { + if self.held { + self.releases += 1; + } + self.held = false; + } + fn is_held(&self) -> bool { + self.held + } + } + + struct FakeSleep { + current: Option, + calls: Vec, + } + + impl SleepControl for FakeSleep { + fn read(&mut self) -> Result, String> { + Ok(self.current) + } + fn set(&mut self, disabled: bool) -> Result<(), String> { + self.calls.push(disabled); + Ok(()) + } + } + + fn sleep(current: Option) -> FakeSleep { + FakeSleep { + current, + calls: Vec::new(), + } + } + + #[test] + fn default_programs_match_python() { + assert_eq!( + default_closed_program(128), + "brightness 128\noff 90ms cosine\n0:#FF7A00 180ms ease; 7:#FF7A00 180ms ease; 1:#FF7A00 180ms ease 80ms; 6:#FF7A00 180ms ease 80ms\n2:#FF4A00 180ms ease; 5:#FF4A00 180ms ease; 3:#FF3000 180ms ease 80ms; 4:#FF3000 180ms ease 80ms\noff 360ms ease-out" + ); + assert_eq!( + default_open_program(255), + "off 90ms cosine\n3:#00E5FF 180ms ease; 4:#00E5FF 180ms ease; 2:#00E5FF 180ms ease 80ms; 5:#00E5FF 180ms ease 80ms\n1:#00FFB0 180ms ease; 6:#00FFB0 180ms ease; 0:#00FF66 180ms ease 80ms; 7:#00FF66 180ms ease 80ms\n#00FF66 220ms ease\noff 320ms ease-out" + ); + /* `test_lid_animation_program_uses_device_brightness` */ + let p = lid_animation_program(DEFAULT_CLOSED_PROGRAM, 128).unwrap(); + assert!(p.starts_with("brightness 128\n")); + validate_program(&p).unwrap(); + assert_eq!( + lid_animation_program(r"off\nrepeat", 255).unwrap(), + "off\nrepeat" + ); + assert!( + lid_animation_program(&vec!["off"; 20].join("\n"), 255).is_err(), + "dimmed form is 21 lines" + ); + } + + #[test] + fn policy_decisions() { + assert!(!closed_lid_awake_should_hold(ClosedLidPolicy::Never, true)); + assert!(!closed_lid_awake_should_hold( + ClosedLidPolicy::Agents, + false + )); + assert!(closed_lid_awake_should_hold(ClosedLidPolicy::Agents, true)); + assert!(closed_lid_awake_should_hold(ClosedLidPolicy::Always, false)); + for p in [ + ClosedLidPolicy::Never, + ClosedLidPolicy::Agents, + ClosedLidPolicy::Always, + ] { + assert_eq!(ClosedLidPolicy::parse(p.value()), Some(p)); + } + assert_eq!(ClosedLidPolicy::parse("sometimes"), None); + } + + /// `test_closed_lid_awake_controller_sets_and_restores_system_disable`. + #[test] + fn sets_and_restores_system_disable() { + let mut c = ClosedLidAwake::new(FakeHold::default(), sleep(Some(false)), true); + assert!(c.update(ClosedLidPolicy::Always, false)); + assert_eq!(c.sleep_control().calls, [true]); + assert!(c.changed_system_disable); + assert_eq!(c.hold().acquires, 1); + c.update(ClosedLidPolicy::Always, false); + assert_eq!(c.sleep_control().calls, [true]); + assert_eq!(c.hold().acquires, 1); + assert!(!c.update(ClosedLidPolicy::Never, false)); + assert_eq!(c.sleep_control().calls, [true, false]); + assert_eq!(c.hold().releases, 1); + } + + /// `test_closed_lid_awake_controller_defaults_to_user_mode_only`. + #[test] + fn user_mode_only_without_helper() { + let mut c = ClosedLidAwake::new(FakeHold::default(), sleep(Some(false)), false); + assert!(c.update(ClosedLidPolicy::Always, false)); + assert!(c.sleep_control().calls.is_empty()); + assert!(c.hold().is_held()); + assert!(!c.changed_system_disable); + } + + /// `test_closed_lid_awake_controller_preserves_existing_system_disable`. + #[test] + fn preserves_existing_system_disable() { + let mut c = ClosedLidAwake::new(FakeHold::default(), sleep(Some(true)), true); + c.update(ClosedLidPolicy::Always, false); + c.update(ClosedLidPolicy::Never, false); + assert!(c.sleep_control().calls.is_empty()); + } + + #[test] + fn unknown_state_is_set_and_helper_removal_reverts() { + let mut c = ClosedLidAwake::new(FakeHold::default(), sleep(None), true); + c.update(ClosedLidPolicy::Agents, true); + assert_eq!(c.sleep_control().calls, [true]); + c.set_use_system_disable(false); + assert_eq!(c.sleep_control().calls, [true, false]); + assert!(c.active(), "user-mode hold remains"); + } + + #[test] + fn sudoers_rule_is_narrow() { + assert_eq!( + sleep_helper_sudoers_rule("pero").unwrap(), + "pero ALL=(root) NOPASSWD: /usr/bin/pmset -a disablesleep 0, /usr/bin/pmset -a disablesleep 1\n" + ); + assert_eq!(sleep_helper_sudoers_rule("bad user"), None); + assert_eq!(sleep_helper_sudoers_rule(""), None); + } + + /// Non-destructive live read; run with `cargo test -p sidepulse-core -- --ignored --nocapture`. + #[test] + #[ignore] + fn live_lid_read() { + let t = Instant::now(); + let closed = clamshell_closed(); + println!("clamshell closed: {closed:?} ({:?})", t.elapsed()); + println!("sleep disabled: {:?}", sleep_disabled()); + println!("sleep helper installed: {}", sleep_helper_installed()); + } +} diff --git a/src/logrot.rs b/crates/sidepulse-core/src/logrot.rs similarity index 100% rename from src/logrot.rs rename to crates/sidepulse-core/src/logrot.rs diff --git a/src/models.rs b/crates/sidepulse-core/src/models.rs similarity index 91% rename from src/models.rs rename to crates/sidepulse-core/src/models.rs index 08f7667..4b49237 100644 --- a/src/models.rs +++ b/crates/sidepulse-core/src/models.rs @@ -31,6 +31,21 @@ impl AgentMode { } } + /// `AgentMode(value)`: the inverse of [`AgentMode::value`]. + pub fn from_value(value: &str) -> Option { + Some(match value { + "idle_ready" => Self::IdleReady, + "working" => Self::Working, + "tool_running" => Self::ToolRunning, + "waiting_for_input" => Self::WaitingForInput, + "long_task_progress" => Self::LongTaskProgress, + "blocked_error" => Self::BlockedError, + "completed" => Self::Completed, + "unknown" => Self::Unknown, + _ => return None, + }) + } + pub fn label(self) -> &'static str { match self { Self::IdleReady => "Idle / Ready", diff --git a/crates/sidepulse-core/src/monitor.rs b/crates/sidepulse-core/src/monitor.rs new file mode 100644 index 0000000..5e6bbe4 --- /dev/null +++ b/crates/sidepulse-core/src/monitor.rs @@ -0,0 +1,1098 @@ +//! Port of `LiveAgentMonitor` and the snapshot logic in `sidepulse/collector.py`. +//! +//! Differences from Python, all deliberate: +//! +//! - State is bounded. Statuses, per-session/per-status metadata and pending permission +//! signatures older than [`MonitorConfig::retain_for`] are dropped, and at most +//! [`MonitorConfig::max_statuses`] of each are kept (newest first). Python keeps everything, +//! which grew `latest.json` to ~10k statuses. +//! - [`LiveMonitor::ingest`] never touches the disk. It marks the monitor dirty and the caller +//! debounces [`LiveMonitor::flush`], which writes compact JSON (Python reads it with +//! `json.loads`, so this stays compatible). Python rewrote the file with `indent=2` per event. +//! - Metadata maps start empty after a reload, as in Python (they are not persisted). +//! - Python quirk kept for parity: a `PostToolUse` `WORKING` status older than +//! [`POST_TOOL_WORKING_VISIBLE_SECONDS`] is shown as `COMPLETED`, and because that is already +//! past [`COMPLETED_VISIBLE_SECONDS`] it is immediately stale (see `status_for_snapshot`). + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; + +use chrono::{DateTime, Duration, Utc}; +use serde_json::{json, Value}; + +use crate::collector::{ + display_name_from_parts, project_name, read_recent_lines, status_from_event, title_from_event, + StatusMetadata, +}; +use crate::models::{isoformat, parse_datetime, AgentMode, AgentStatus, HookEvent}; +use crate::origin::origin_label_from_payload; +use crate::providers::{detect_log_path, parse_log_object}; +use crate::pyjson::{py_str, truthy, Object}; + +/// `COMPLETED_VISIBLE_SECONDS`. +pub const COMPLETED_VISIBLE_SECONDS: i64 = 90; +/// `IDLE_VISIBLE_SECONDS`: idle statuses are stale as soon as they have any age. +pub const IDLE_VISIBLE_SECONDS: i64 = 0; +/// `POST_TOOL_WORKING_VISIBLE_SECONDS`. +pub const POST_TOOL_WORKING_VISIBLE_SECONDS: i64 = 120; +/// Providers replayed at start-up (`replay_recent_debug_logs`). +pub const REPLAY_PROVIDERS: [&str; 3] = ["codex", "claude", "grok"]; +/// Cap on pending permission signatures per status key (unbounded in Python). +const MAX_PENDING_PER_KEY: usize = 32; + +/// `AggregateStatus`. +#[derive(Clone, Debug)] +pub struct Aggregate { + pub mode: AgentMode, + pub active_count: usize, + pub stale_count: usize, + pub representative: Option, +} + +/// `MonitorSnapshot` without `sources`/`collected_at`. +#[derive(Clone, Debug)] +pub struct Snapshot { + /// Fresh statuses, sorted by (priority, newest first). + pub statuses: Vec, + /// Stale statuses, same order. Always populated (`include_stale` is a no-op in Python). + pub stale: Vec, + pub aggregate: Aggregate, +} + +#[derive(Clone, Debug)] +pub struct MonitorConfig { + /// `stale_after_seconds` for modes other than completed/idle. + pub stale_after: Duration, + /// Drop stored statuses and metadata older than this. + pub retain_for: Duration, + /// Keep at most this many statuses (and metadata entries per map). + pub max_statuses: usize, +} + +impl Default for MonitorConfig { + fn default() -> Self { + Self { + stale_after: Duration::seconds(3600), + retain_for: Duration::hours(6), + max_statuses: 256, + } + } +} + +#[derive(Clone, Debug)] +struct MetadataEntry { + metadata: StatusMetadata, + last_seen: DateTime, +} + +/// `LiveAgentMonitor`, with bounded state and debounced persistence. +#[derive(Debug)] +pub struct LiveMonitor { + state_path: PathBuf, + config: MonitorConfig, + statuses: HashMap, + metadata_by_session: HashMap, + metadata_by_status: HashMap, + pending_permissions: HashMap>, + dirty: bool, +} + +impl LiveMonitor { + /// `LiveAgentMonitor.__init__` + `load_latest_state`. Load errors are ignored. + pub fn new(state_path: PathBuf, config: MonitorConfig) -> Self { + Self::new_at(state_path, config, Utc::now()) + } + + /// [`LiveMonitor::new`] with an explicit clock for retention pruning. + pub fn new_at(state_path: PathBuf, config: MonitorConfig, now: DateTime) -> Self { + let mut monitor = Self { + state_path, + config, + statuses: HashMap::new(), + metadata_by_session: HashMap::new(), + metadata_by_status: HashMap::new(), + pending_permissions: HashMap::new(), + dirty: false, + }; + monitor.load_latest_state(now); + monitor + } + + pub fn state_path(&self) -> &Path { + &self.state_path + } + + pub fn config(&self) -> &MonitorConfig { + &self.config + } + + /// Number of stored (bounded) statuses. + pub fn len(&self) -> usize { + self.statuses.len() + } + + pub fn is_empty(&self) -> bool { + self.statuses.is_empty() + } + + /// `LiveAgentMonitor.ingest_record`, minus the file write. Returns true when a status + /// was stored (and the monitor marked dirty). + pub fn ingest(&mut self, record: HookEvent) -> bool { + self.ingest_at(record, Utc::now()) + } + + /// [`LiveMonitor::ingest`] with an explicit clock for retention pruning. + pub fn ingest_at(&mut self, record: HookEvent, now: DateTime) -> bool { + let metadata = self.metadata_for_record(&record); + let stored = self.store_status(&record, &metadata, now); + self.prune(now); + stored + } + + fn store_status( + &mut self, + record: &HookEvent, + metadata: &StatusMetadata, + now: DateTime, + ) -> bool { + let Some(status) = status_from_event(record, metadata) else { + return false; + }; + track_pending_permissions(record, &mut self.pending_permissions); + if status.updated_at < now - self.config.retain_for { + return false; + } + let previous = self.statuses.get(&status.agent_id); + let pending = self + .pending_permissions + .get(&status.agent_id) + .is_some_and(|p| !p.is_empty()); + if should_ignore_status_transition(previous, &status, pending) { + return false; + } + self.statuses.insert(status.agent_id.clone(), status); + self.dirty = true; + true + } + + /// `parse_log_line` on an already-decoded JSON line, then [`LiveMonitor::ingest`]. + pub fn ingest_line(&mut self, provider: &str, line: &Value) -> bool { + match line + .as_object() + .and_then(|obj| parse_log_object(provider, obj)) + { + Some(record) => self.ingest(record), + None => false, + } + } + + /// `replay_recent_debug_logs`: last `max_lines_per_provider` lines of each provider's hook + /// log (from `detect_log_path`). Returns the number of records parsed and ingested. + pub fn replay_logs(&mut self, max_lines_per_provider: usize) -> usize { + let sources: Vec<(&str, PathBuf)> = REPLAY_PROVIDERS + .iter() + .map(|p| (*p, detect_log_path(p))) + .collect(); + self.replay_paths(&sources, max_lines_per_provider) + } + + /// Replay explicit `(provider, log path)` pairs. Missing or unreadable logs are skipped. + pub fn replay_paths(&mut self, sources: &[(&str, PathBuf)], max_lines: usize) -> usize { + let mut replayed = 0; + for (provider, path) in sources { + let Ok(lines) = read_recent_lines(path, max_lines) else { + continue; + }; + for line in lines { + let line = line.trim(); + if line.is_empty() { + continue; + } + let Ok(Value::Object(obj)) = serde_json::from_str::(line) else { + continue; + }; + if let Some(record) = parse_log_object(provider, &obj) { + self.ingest(record); + replayed += 1; + } + } + } + replayed + } + + /// `LiveAgentMonitor.snapshot` / `snapshot_from_statuses`. No I/O. + pub fn snapshot(&self, now: DateTime) -> Snapshot { + snapshot_from_statuses(self.statuses.values(), now, self.config.stale_after) + } + + /// The earliest time after `now` at which [`LiveMonitor::snapshot`] can change without a new + /// event: a completed status hiding ([`COMPLETED_VISIBLE_SECONDS`]), an idle one expiring, a + /// post-tool `WORKING` turning `COMPLETED` ([`POST_TOOL_WORKING_VISIBLE_SECONDS`]) or any + /// other status going stale (`stale_after`). The thresholds are strict (`age > limit`), so a + /// snapshot taken exactly at the returned time may still show the old state; callers should + /// add a small margin. `None` when no transition is pending. + pub fn next_transition_at(&self, now: DateTime) -> Option> { + next_transition_at(self.statuses.values(), now, self.config.stale_after) + } + + pub fn is_dirty(&self) -> bool { + self.dirty + } + + /// `write_latest_state`, only when dirty. Atomic via `latest.json.tmp` + rename, compact + /// JSON. Returns whether the file was written; on error the monitor stays dirty. + pub fn flush(&mut self) -> std::io::Result { + if !self.dirty { + return Ok(false); + } + self.write_latest_state(Utc::now())?; + self.dirty = false; + Ok(true) + } + + fn write_latest_state(&self, now: DateTime) -> std::io::Result<()> { + let mut statuses: Vec<&AgentStatus> = self.statuses.values().collect(); + statuses.sort_by(|a, b| { + b.updated_at + .cmp(&a.updated_at) + .then_with(|| a.agent_id.cmp(&b.agent_id)) + }); + let payload = json!({ + "updated_at": isoformat(&now), + "statuses": statuses.iter().map(|s| status_to_value(s, now)).collect::>(), + }); + let mut text = serde_json::to_string(&payload).map_err(std::io::Error::other)?; + text.push('\n'); + if let Some(parent) = self.state_path.parent() { + if !parent.as_os_str().is_empty() { + std::fs::create_dir_all(parent)?; + } + } + let temp = self.state_path.with_extension("json.tmp"); + std::fs::write(&temp, text)?; + std::fs::rename(&temp, &self.state_path) + } + + /// `load_latest_state`, followed by bounding. + fn load_latest_state(&mut self, now: DateTime) { + let Ok(text) = std::fs::read_to_string(&self.state_path) else { + return; + }; + let Ok(data) = serde_json::from_str::(&text) else { + return; + }; + let Some(Value::Array(items)) = data.get("statuses") else { + return; + }; + for item in items { + if let Some(status) = status_from_value(item) { + self.statuses.insert(status.agent_id.clone(), status); + } + } + let before = self.statuses.len(); + self.prune(now); + // A pruned file should be rewritten in its bounded form. + if self.statuses.len() < before { + self.dirty = true; + } + self.refresh_codex_titles(); + } + + /// The Codex title refresh in `agent_status_from_dict`, done after bounding so the session + /// index is read at most once per kept Codex session. + fn refresh_codex_titles(&mut self) { + let mut titles: HashMap> = HashMap::new(); + for status in self.statuses.values_mut() { + if status.provider != "codex" { + continue; + } + let Some(session_id) = status.session_id.clone().filter(|s| !s.is_empty()) else { + continue; + }; + let title = titles + .entry(session_id.clone()) + .or_insert_with(|| codex_title(&session_id)) + .clone(); + if let Some(title) = title { + let short: String = session_id.chars().take(8).collect(); + status.display_name = display_name_from_parts( + project_name(status.cwd.as_deref()).as_deref(), + Some(&title), + &short, + &status.display_name, + ); + } + } + } + + /// `metadata_for_record` + `update_metadata`. The title is computed once per record. + fn metadata_for_record(&mut self, record: &HookEvent) -> StatusMetadata { + let title = title_from_event(record); + let origin = record + .origin + .clone() + .filter(|s| !s.is_empty()) + .or_else(|| origin_label_from_payload(&record.provider, &record.raw)); + let update = |map: &mut HashMap, key: String| -> StatusMetadata { + let entry = map.entry(key).or_insert_with(|| MetadataEntry { + metadata: StatusMetadata::default(), + last_seen: record.logged_at, + }); + if entry.last_seen < record.logged_at { + entry.last_seen = record.logged_at; + } + if let Some(cwd) = record.cwd.as_ref().filter(|s| !s.is_empty()) { + entry.metadata.cwd = Some(cwd.clone()); + } + if let Some(title) = &title { + entry.metadata.title = Some(title.clone()); + } + if let Some(origin) = &origin { + entry.metadata.origin = Some(origin.clone()); + } + entry.metadata.clone() + }; + let session = record + .session_id + .as_deref() + .filter(|s| !s.is_empty()) + .map(|s| { + update( + &mut self.metadata_by_session, + format!("{}:session:{}", record.provider, s), + ) + }); + let status = update(&mut self.metadata_by_status, record.status_key()); + match session { + None => status, + Some(session) => StatusMetadata { + cwd: status.cwd.filter(|s| !s.is_empty()).or(session.cwd), + title: status.title.filter(|s| !s.is_empty()).or(session.title), + origin: status.origin.filter(|s| !s.is_empty()).or(session.origin), + }, + } + } + + /// Bound every map by `retain_for` and `max_statuses`. + fn prune(&mut self, now: DateTime) { + let cutoff = now - self.config.retain_for; + let max = self.config.max_statuses; + let before = self.statuses.len(); + self.statuses.retain(|_, s| s.updated_at >= cutoff); + evict_oldest(&mut self.statuses, max, |s| s.updated_at); + if self.statuses.len() < before { + self.dirty = true; + } + for map in [&mut self.metadata_by_session, &mut self.metadata_by_status] { + map.retain(|_, e| e.last_seen >= cutoff); + evict_oldest(map, max, |e| e.last_seen); + } + let statuses = &self.statuses; + self.pending_permissions + .retain(|key, pending| !pending.is_empty() && statuses.contains_key(key)); + } +} + +/// Keep the `max` newest entries. +fn evict_oldest(map: &mut HashMap, max: usize, time: impl Fn(&T) -> DateTime) { + if map.len() <= max { + return; + } + let mut times: Vec<(DateTime, String)> = + map.iter().map(|(k, v)| (time(v), k.clone())).collect(); + times.sort_unstable(); + let excess = map.len() - max; + for (_, key) in times.into_iter().take(excess) { + map.remove(&key); + } +} + +fn codex_title(session_id: &str) -> Option { + // `title_from_event` checks the Codex session index first; any event name other than + // `UserPromptSubmit` makes it return only that title. + let probe = HookEvent { + provider: "codex".into(), + logged_at: Utc::now(), + event_name: String::new(), + raw: Object::new(), + session_id: Some(session_id.to_string()), + turn_id: None, + agent_id: None, + cwd: None, + tool_name: None, + message: None, + origin: None, + }; + title_from_event(&probe) +} + +fn age_seconds(status: &AgentStatus, now: DateTime) -> f64 { + let micros = (now - status.updated_at) + .num_microseconds() + .unwrap_or(i64::MAX); + (micros as f64 / 1e6).max(0.0) +} + +fn sort_key(status: &AgentStatus) -> (u8, std::cmp::Reverse>) { + (status.mode.priority(), std::cmp::Reverse(status.updated_at)) +} + +/// `status_counts_active`. +pub fn status_counts_active(status: &AgentStatus) -> bool { + !matches!(status.mode, AgentMode::Completed | AgentMode::IdleReady) +} + +/// `status_is_stale` with tool-running expiry disabled (as the status bar configures it). +pub fn status_is_stale(status: &AgentStatus, now: DateTime, stale_after: Duration) -> bool { + let age = age_seconds(status, now); + match status.mode { + AgentMode::Completed => age > COMPLETED_VISIBLE_SECONDS as f64, + AgentMode::IdleReady => age > IDLE_VISIBLE_SECONDS as f64, + _ => age > stale_after.num_milliseconds() as f64 / 1000.0, + } +} + +/// `status_for_snapshot`: an old post-tool `WORKING` status is shown as `COMPLETED`. +pub fn status_for_snapshot(status: &AgentStatus, now: DateTime) -> AgentStatus { + let mut status = status.clone(); + if status.mode == AgentMode::Working + && status.event_name == "PostToolUse" + && age_seconds(&status, now) > POST_TOOL_WORKING_VISIBLE_SECONDS as f64 + { + status.mode = AgentMode::Completed; + } + status +} + +/// See [`LiveMonitor::next_transition_at`]. Mirrors the thresholds in [`status_is_stale`] and +/// [`status_for_snapshot`]. +pub fn next_transition_at<'a>( + statuses: impl IntoIterator, + now: DateTime, + stale_after: Duration, +) -> Option> { + let mut next: Option> = None; + for status in statuses { + let limits: &[Duration] = match status.mode { + AgentMode::Completed => &[Duration::seconds(COMPLETED_VISIBLE_SECONDS)], + AgentMode::IdleReady => &[Duration::seconds(IDLE_VISIBLE_SECONDS)], + AgentMode::Working if status.event_name == "PostToolUse" => &[ + Duration::seconds(POST_TOOL_WORKING_VISIBLE_SECONDS), + stale_after, + ], + _ => &[stale_after], + }; + for limit in limits { + let at = status.updated_at + *limit; + if at > now && next.is_none_or(|n| at < n) { + next = Some(at); + } + } + } + next +} + +/// `snapshot_from_statuses`. +pub fn snapshot_from_statuses<'a>( + statuses: impl IntoIterator, + now: DateTime, + stale_after: Duration, +) -> Snapshot { + let mut fresh = Vec::new(); + let mut stale = Vec::new(); + for status in statuses { + let mut current = status_for_snapshot(status, now); + current.stale = status_is_stale(¤t, now, stale_after); + if current.stale { + stale.push(current); + } else { + fresh.push(current); + } + } + if fresh.iter().any(status_counts_active) { + let (active, inactive): (Vec<_>, Vec<_>) = + fresh.into_iter().partition(status_counts_active); + fresh = active; + stale.extend(inactive.into_iter().map(|mut s| { + s.stale = true; + s + })); + } + // Ties broken by key for a deterministic order (Python uses dict insertion order). + let order = |a: &AgentStatus, b: &AgentStatus| { + sort_key(a) + .cmp(&sort_key(b)) + .then_with(|| a.agent_id.cmp(&b.agent_id)) + }; + fresh.sort_by(order); + stale.sort_by(order); + let aggregate = aggregate_status(&fresh, stale.len()); + Snapshot { + statuses: fresh, + stale, + aggregate, + } +} + +/// `aggregate_status`: representative is the minimum (priority, newest first). +pub fn aggregate_status(statuses: &[AgentStatus], stale_count: usize) -> Aggregate { + let representative = statuses.iter().min_by_key(|s| sort_key(s)).cloned(); + Aggregate { + mode: representative + .as_ref() + .map_or(AgentMode::IdleReady, |s| s.mode), + active_count: statuses.iter().filter(|s| status_counts_active(s)).count(), + stale_count, + representative, + } +} + +/// `track_pending_permissions`. +fn track_pending_permissions(record: &HookEvent, pending: &mut HashMap>) { + let signature = permission_signature(record); + let key = record.status_key(); + match (record.event_name.as_str(), signature) { + ("PermissionRequest", Some(sig)) => { + let set = pending.entry(key).or_default(); + if !set.contains(&sig) { + set.push(sig); + if set.len() > MAX_PENDING_PER_KEY { + set.remove(0); + } + } + } + ("PostToolUse", Some(sig)) => { + if let Some(set) = pending.get_mut(&key) { + set.retain(|s| *s != sig); + if set.is_empty() { + pending.remove(&key); + } + } + } + ("Stop" | "SessionEnd" | "UserPromptSubmit", _) => { + pending.remove(&key); + } + _ => {} + } +} + +/// `permission_signature`: tool name + NUL + command, when the tool input has a command. +pub fn permission_signature(record: &HookEvent) -> Option { + let raw = &record.raw; + let tool_name = match raw.get("tool_name") { + Some(Value::String(s)) if !s.is_empty() => Some(s.as_str()), + _ => record.tool_name.as_deref(), + }; + let Some(Value::Object(input)) = raw.get("tool_input") else { + return None; + }; + match input.get("command") { + Some(Value::String(command)) if !command.is_empty() => { + Some(format!("{}\0{}", tool_name.unwrap_or(""), command)) + } + _ => None, + } +} + +/// `should_ignore_status_transition`. +pub fn should_ignore_status_transition( + previous: Option<&AgentStatus>, + current: &AgentStatus, + has_pending_permissions: bool, +) -> bool { + let Some(previous) = previous else { + return false; + }; + if previous.mode == AgentMode::Completed && current.event_name == "Notification" { + return true; + } + previous.mode == AgentMode::WaitingForInput + && previous.event_name == "PermissionRequest" + && current.event_name != "PermissionRequest" + && has_pending_permissions +} + +/// `AgentStatus.to_dict(now)`, same key order. +pub fn status_to_value(s: &AgentStatus, now: DateTime) -> Value { + let age = (age_seconds(s, now) * 1000.0).round() / 1000.0; + json!({ + "provider": s.provider, + "agent_id": s.agent_id, + "display_name": s.display_name, + "mode": s.mode.value(), + "mode_label": s.mode.label(), + "priority": s.mode.priority(), + "updated_at": isoformat(&s.updated_at), + "age_seconds": age, + "event_name": s.event_name, + "session_id": s.session_id, + "cwd": s.cwd, + "tool_name": s.tool_name, + "message": s.message, + "origin": s.origin, + "stale": s.stale, + }) +} + +/// `AggregateStatus.to_dict(now)`. +pub fn aggregate_to_value(a: &Aggregate, now: DateTime) -> Value { + json!({ + "mode": a.mode.value(), + "mode_label": a.mode.label(), + "active_count": a.active_count, + "stale_count": a.stale_count, + "representative": a.representative.as_ref().map(|s| status_to_value(s, now)), + }) +} + +/// `agent_status_from_dict`, without the Codex title refresh (done in bulk on load). +pub fn status_from_value(v: &Value) -> Option { + let data = v.as_object()?; + let string_or_none = |key: &str| match data.get(key) { + Some(Value::String(s)) if !s.is_empty() => Some(s.clone()), + _ => None, + }; + let required = |key: &str| data.get(key).map(py_str); + Some(AgentStatus { + provider: required("provider")?, + agent_id: required("agent_id")?, + display_name: required("display_name")?, + mode: AgentMode::from_value(&required("mode")?)?, + updated_at: parse_datetime(Some(data.get("updated_at")?)), + event_name: required("event_name")?, + session_id: string_or_none("session_id"), + cwd: string_or_none("cwd"), + tool_name: string_or_none("tool_name"), + message: string_or_none("message"), + origin: string_or_none("origin"), + stale: truthy(data.get("stale")), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use chrono::TimeZone; + + fn base() -> DateTime { + Utc.with_ymd_and_hms(2026, 11, 7, 12, 0, 0).unwrap() + } + + fn event(name: &str, session: &str, at: DateTime, extra: Value) -> HookEvent { + let mut obj = json!({ + "hook_event_name": name, + "session_id": session, + "logged_at": isoformat(&at), + }); + if let (Value::Object(o), Value::Object(e)) = (&mut obj, extra) { + o.extend(e); + } + parse_log_object("claude", obj.as_object().unwrap()).expect("event parses") + } + + fn status(key: &str, mode: AgentMode, at: DateTime, event: &str) -> AgentStatus { + AgentStatus { + provider: "claude".into(), + agent_id: key.into(), + display_name: key.into(), + mode, + updated_at: at, + event_name: event.into(), + session_id: None, + cwd: None, + tool_name: None, + message: None, + origin: None, + stale: false, + } + } + + fn monitor(dir: &tempfile::TempDir) -> LiveMonitor { + LiveMonitor::new_at( + dir.path().join("latest.json"), + MonitorConfig::default(), + base(), + ) + } + + fn bash(cmd: &str) -> Value { + json!({"tool_name": "Bash", "tool_input": {"command": cmd}}) + } + + #[test] + fn permission_request_holds_waiting_until_post_tool_use() { + let dir = tempfile::tempdir().unwrap(); + let mut m = monitor(&dir); + let t = base(); + assert!(m.ingest_at(event("PermissionRequest", "s", t, bash("rm x")), t)); + let snap = m.snapshot(t); + assert_eq!(snap.aggregate.mode, AgentMode::WaitingForInput); + + let t1 = t + Duration::seconds(1); + assert!(!m.ingest_at(event("PreToolUse", "s", t1, bash("rm x")), t1)); + assert!(!m.ingest_at(event("Notification", "s", t1, json!({})), t1)); + assert_eq!(m.snapshot(t1).aggregate.mode, AgentMode::WaitingForInput); + + let t2 = t + Duration::seconds(2); + assert!(m.ingest_at(event("PostToolUse", "s", t2, bash("rm x")), t2)); + let snap = m.snapshot(t2); + assert_eq!(snap.aggregate.mode, AgentMode::Working); + assert!(m.pending_permissions.is_empty()); + } + + #[test] + fn stop_clears_pending_permissions() { + let dir = tempfile::tempdir().unwrap(); + let mut m = monitor(&dir); + let t = base(); + m.ingest_at(event("PermissionRequest", "s", t, bash("ls")), t); + assert!(m.ingest_at(event("Stop", "s", t, json!({})), t)); + assert!(m.pending_permissions.is_empty()); + assert_eq!(m.snapshot(t).aggregate.mode, AgentMode::Completed); + } + + #[test] + fn notification_after_completed_is_ignored() { + let dir = tempfile::tempdir().unwrap(); + let mut m = monitor(&dir); + let t = base(); + assert!(m.ingest_at(event("Stop", "s", t, json!({})), t)); + let ev = event( + "Notification", + "s", + t + Duration::seconds(1), + json!({"message": "Claude is waiting for your input"}), + ); + assert!(!m.ingest_at(ev, t)); + assert_eq!(m.snapshot(t).aggregate.mode, AgentMode::Completed); + } + + #[test] + fn next_transition_is_the_earliest_pending_threshold() { + let t = base(); + let hour = Duration::hours(1); + let s = [ + status("done", AgentMode::Completed, t, "Stop"), + status("tool", AgentMode::Working, t, "PostToolUse"), + status("work", AgentMode::Working, t, "UserPromptSubmit"), + status("idle", AgentMode::IdleReady, t, "SessionStart"), + ]; + let at = |secs| t + Duration::seconds(secs); + // Completed hides at +90, post-tool working flips at +120, the rest go stale at +3600. + assert_eq!(next_transition_at(&s, t, hour), Some(at(90))); + assert_eq!(next_transition_at(&s, at(90), hour), Some(at(120))); + assert_eq!(next_transition_at(&s, at(120), hour), Some(at(3600))); + assert_eq!(next_transition_at(&s, at(3600), hour), None); + assert_eq!(next_transition_at([], t, hour), None); + } + + #[test] + fn snapshot_changes_just_after_each_predicted_transition() { + let t = base(); + let hour = Duration::hours(1); + let ms = Duration::milliseconds; + for s in [ + status("done", AgentMode::Completed, t, "Stop"), + status("tool", AgentMode::Working, t, "PostToolUse"), + status("work", AgentMode::WaitingForInput, t, "Notification"), + ] { + let s = [s]; + let next = next_transition_at(&s, t, hour).unwrap(); + let view = |at| { + let snap = snapshot_from_statuses(&s, at, hour); + let modes: Vec<_> = snap.statuses.iter().map(|x| x.mode).collect(); + (snap.aggregate.mode, modes, snap.stale.len()) + }; + let start = view(t); + assert_eq!(view(next - ms(1)), start); + assert_eq!(view(next), start, "thresholds are strict"); + assert_ne!(view(next + ms(1)), start); + } + } + + #[test] + fn completed_hides_after_90_seconds() { + let t = base(); + let s = [status("a", AgentMode::Completed, t, "Stop")]; + let at90 = snapshot_from_statuses(&s, t + Duration::seconds(90), Duration::hours(1)); + assert_eq!(at90.statuses.len(), 1); + let at91 = snapshot_from_statuses(&s, t + Duration::seconds(91), Duration::hours(1)); + assert!(at91.statuses.is_empty()); + assert_eq!(at91.stale.len(), 1); + assert!(at91.stale[0].stale); + assert_eq!(at91.aggregate.mode, AgentMode::IdleReady); + assert_eq!(at91.aggregate.stale_count, 1); + } + + #[test] + fn idle_is_stale_once_it_has_age() { + let t = base(); + let s = [status("a", AgentMode::IdleReady, t, "SessionStart")]; + let snap = snapshot_from_statuses(&s, t + Duration::milliseconds(1), Duration::hours(1)); + assert!(snap.statuses.is_empty()); + assert_eq!(snap.stale.len(), 1); + } + + #[test] + fn working_goes_stale_after_stale_after() { + let t = base(); + let s = [status("a", AgentMode::ToolRunning, t, "PreToolUse")]; + let hour = Duration::hours(1); + assert_eq!(snapshot_from_statuses(&s, t + hour, hour).statuses.len(), 1); + let later = t + hour + Duration::seconds(1); + assert!(snapshot_from_statuses(&s, later, hour).statuses.is_empty()); + } + + #[test] + fn active_statuses_push_inactive_ones_to_stale() { + let t = base(); + let s = [ + status("done", AgentMode::Completed, t, "Stop"), + status("busy", AgentMode::Working, t, "UserPromptSubmit"), + ]; + let snap = snapshot_from_statuses(&s, t + Duration::seconds(5), Duration::hours(1)); + assert_eq!(snap.statuses.len(), 1); + assert_eq!(snap.statuses[0].agent_id, "busy"); + assert_eq!(snap.stale.len(), 1); + assert!(snap.stale[0].stale); + assert_eq!(snap.aggregate.active_count, 1); + assert_eq!(snap.aggregate.stale_count, 1); + } + + #[test] + fn post_tool_working_becomes_completed_then_stale() { + // Python parity quirk: past 120 s the status reads COMPLETED, which is already past 90 s. + let t = base(); + let s = [status("a", AgentMode::Working, t, "PostToolUse")]; + let at = t + Duration::seconds(121); + let snap = snapshot_from_statuses(&s, at, Duration::hours(1)); + assert!(snap.statuses.is_empty()); + assert_eq!(snap.stale[0].mode, AgentMode::Completed); + let fresh = snapshot_from_statuses(&s, t + Duration::seconds(60), Duration::hours(1)); + assert_eq!(fresh.aggregate.mode, AgentMode::Working); + } + + #[test] + fn aggregate_picks_min_priority_then_newest() { + let t = base(); + let s = vec![ + status("work", AgentMode::Working, t + Duration::seconds(9), "x"), + status("old-wait", AgentMode::WaitingForInput, t, "x"), + status( + "new-wait", + AgentMode::WaitingForInput, + t + Duration::seconds(5), + "x", + ), + ]; + let agg = aggregate_status(&s, 2); + assert_eq!(agg.mode, AgentMode::WaitingForInput); + assert_eq!(agg.representative.unwrap().agent_id, "new-wait"); + assert_eq!(agg.active_count, 3); + assert_eq!(agg.stale_count, 2); + let empty = aggregate_status(&[], 0); + assert_eq!(empty.mode, AgentMode::IdleReady); + assert!(empty.representative.is_none()); + } + + #[test] + fn snapshot_sorts_by_priority_then_newest() { + let t = base(); + let s = [ + status("w1", AgentMode::Working, t, "x"), + status("err", AgentMode::BlockedError, t, "x"), + status("w2", AgentMode::Working, t + Duration::seconds(1), "x"), + ]; + let snap = snapshot_from_statuses(&s, t + Duration::seconds(2), Duration::hours(1)); + let ids: Vec<_> = snap.statuses.iter().map(|s| s.agent_id.as_str()).collect(); + assert_eq!(ids, ["err", "w2", "w1"]); + } + + #[test] + fn latest_json_round_trip() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("state/latest.json"); + let now = Utc::now(); + let mut m = LiveMonitor::new(path.clone(), MonitorConfig::default()); + assert!(!m.flush().unwrap()); + let ev = event( + "PreToolUse", + "sess-1", + now, + json!({"tool_name": "Bash", "agent_origin": "Codex UI"}), + ); + assert!(m.ingest(ev)); + assert!(m.is_dirty()); + assert!(!path.exists(), "ingest must not write"); + assert!(m.flush().unwrap()); + assert!(!m.is_dirty()); + assert!(!dir.path().join("state/latest.json.tmp").exists()); + + let text = std::fs::read_to_string(&path).unwrap(); + assert!(!text.contains("\n "), "compact JSON"); + let data: Value = serde_json::from_str(&text).unwrap(); + let keys: Vec<_> = data["statuses"][0] + .as_object() + .unwrap() + .keys() + .cloned() + .collect(); + assert_eq!(keys[..4], ["provider", "agent_id", "display_name", "mode"]); + assert_eq!(keys.len(), 15); + + let reloaded = LiveMonitor::new(path, MonitorConfig::default()); + let snap = reloaded.snapshot(now); + assert_eq!(snap.aggregate.mode, AgentMode::ToolRunning); + assert_eq!(snap.statuses[0].tool_name.as_deref(), Some("Bash")); + assert_eq!(snap.statuses[0].agent_id, "claude:session:sess-1"); + assert!(!reloaded.is_dirty()); + } + + #[test] + fn status_value_round_trip_and_rejects_bad_rows() { + let t = base(); + let mut s = status("k", AgentMode::BlockedError, t, "StopFailure"); + s.cwd = Some("/tmp/p".into()); + let v = status_to_value(&s, t + Duration::milliseconds(1500)); + assert_eq!(v["age_seconds"], json!(1.5)); + assert_eq!(v["priority"], json!(1)); + assert_eq!(v["mode_label"], json!("Blocked / Error")); + let back = status_from_value(&v).unwrap(); + assert_eq!(back.mode, AgentMode::BlockedError); + assert_eq!(back.updated_at, t); + assert_eq!(back.cwd.as_deref(), Some("/tmp/p")); + assert!(status_from_value(&json!({"provider": "x"})).is_none()); + let mut bad = v.clone(); + bad["mode"] = json!("nope"); + assert!(status_from_value(&bad).is_none()); + assert!(status_from_value(&json!([1])).is_none()); + } + + #[test] + fn bounding_drops_old_and_excess_statuses() { + let dir = tempfile::tempdir().unwrap(); + let config = MonitorConfig { + max_statuses: 3, + ..MonitorConfig::default() + }; + let mut m = LiveMonitor::new_at(dir.path().join("latest.json"), config, base()); + let t = base(); + // Older than retain_for: never stored. + let old = t - Duration::hours(7); + assert!(!m.ingest_at(event("UserPromptSubmit", "old", old, json!({})), t)); + assert!(m.is_empty()); + for i in 0..5 { + let at = t + Duration::seconds(i); + m.ingest_at( + event("UserPromptSubmit", &format!("s{i}"), at, json!({})), + at, + ); + } + assert_eq!(m.len(), 3); + let mut keys: Vec<_> = m.statuses.keys().cloned().collect(); + keys.sort(); + assert_eq!( + keys, + [ + "claude:session:s2", + "claude:session:s3", + "claude:session:s4" + ] + ); + assert!(m.metadata_by_session.len() <= 3); + assert!(m.metadata_by_status.len() <= 3); + + // Time passes: everything ages out of retain_for. + let later = t + Duration::hours(7); + m.ingest_at(event("UserPromptSubmit", "new", later, json!({})), later); + assert_eq!(m.len(), 1); + assert_eq!(m.metadata_by_status.len(), 1); + } + + #[test] + fn load_bounds_oversized_state_file() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("latest.json"); + let t = base(); + let rows: Vec = (0..10) + .map(|i| { + let s = status( + &format!("k{i}"), + AgentMode::Working, + t - Duration::hours(i), + "x", + ); + status_to_value(&s, t) + }) + .collect(); + std::fs::write( + &path, + json!({"updated_at": "x", "statuses": rows}).to_string(), + ) + .unwrap(); + let config = MonitorConfig { + max_statuses: 4, + ..MonitorConfig::default() + }; + let m = LiveMonitor::new_at(path, config, t); + // retain_for 6h keeps k0..k6, max_statuses keeps the 4 newest. + let mut keys: Vec<_> = m.statuses.keys().cloned().collect(); + keys.sort(); + assert_eq!(keys, ["k0", "k1", "k2", "k3"]); + assert!(m.is_dirty(), "pruned state should be rewritten"); + } + + #[test] + fn pending_permissions_are_bounded() { + let dir = tempfile::tempdir().unwrap(); + let mut m = monitor(&dir); + let t = base(); + for i in 0..50 { + m.ingest_at( + event("PermissionRequest", "s", t, bash(&format!("cmd{i}"))), + t, + ); + } + assert_eq!( + m.pending_permissions["claude:session:s"].len(), + MAX_PENDING_PER_KEY + ); + } + + #[test] + fn replay_ignores_missing_logs_and_counts_records() { + let dir = tempfile::tempdir().unwrap(); + let mut m = monitor(&dir); + let log = dir.path().join("codex.jsonl"); + let now = Utc::now(); + let line = json!({ + "logged_at": isoformat(&now), + "event": { + "hook_event_name": "UserPromptSubmit", + "session_id": "eeeeeeee-ffff", + "cwd": "/tmp/project", + "prompt": "startup replay should restore this", + }, + }); + std::fs::write(&log, format!("{line}\nnot json\n\n")).unwrap(); + let sources = [("claude", dir.path().join("missing.jsonl")), ("codex", log)]; + assert_eq!(m.replay_paths(&sources, 20), 1); + let snap = m.snapshot(now); + assert_eq!(snap.aggregate.mode, AgentMode::Working); + assert!(snap.statuses[0].display_name.contains("startup replay")); + } + + #[test] + fn ingest_line_rejects_non_objects() { + let dir = tempfile::tempdir().unwrap(); + let mut m = monitor(&dir); + assert!(!m.ingest_line("claude", &json!([1, 2]))); + assert!(!m.ingest_line("claude", &json!({"no": "event"}))); + let line = json!({ + "hook_event_name": "UserPromptSubmit", + "session_id": "x", + "logged_at": isoformat(&Utc::now()), + }); + assert!(m.ingest_line("claude", &line)); + } +} diff --git a/src/origin.rs b/crates/sidepulse-core/src/origin.rs similarity index 100% rename from src/origin.rs rename to crates/sidepulse-core/src/origin.rs diff --git a/crates/sidepulse-core/src/power.rs b/crates/sidepulse-core/src/power.rs new file mode 100644 index 0000000..867346d --- /dev/null +++ b/crates/sidepulse-core/src/power.rs @@ -0,0 +1,698 @@ +//! Keep-awake power assertions and the SD-card keepalive touch (`keep_awake.py`). +//! +//! API: +//! - [`Assertion`]: RAII set of IOPM assertions. [`Assertion::caffeinate`] matches +//! `/usr/bin/caffeinate -dimsu` (display, idle, disk and system sleep, plus one user-activity +//! declaration). Dropping it releases every assertion. +//! - [`Hold`]: something that can be acquired and released; [`AssertionHold`] is the real one. +//! - [`KeepAwake`]: `KeepAwakeController` policy. `update(mode, now)` holds while agents work and +//! keeps a 300 s grace hold after completion, a question or an error. +//! - [`KeepaliveToucher`]: touches `/keepalive` at most once per 60 s per path, off-thread. +//! - [`keepalive_file_for_target`], [`keepalive_targets`], [`format_duration`]. +//! +//! Differences from Python: assertions are taken in-process with IOPMLib instead of spawning +//! `caffeinate -w ` (they die with the process just the same), and the keepalive touch is a +//! direct `open(O_CREAT)` + `futimens` instead of `/usr/bin/touch`. + +#[cfg(target_os = "macos")] +pub(crate) mod iokit; + +use std::collections::{HashMap, HashSet}; +use std::fs::{File, FileTimes}; +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant, SystemTime}; + +use crate::devices::{Device, KNOWN_LED_FILE_NAMES, MOUNT_ROOT}; +use crate::models::AgentMode; + +/// `AWAKE_GRACE_SECONDS`. +pub const AWAKE_GRACE: Duration = Duration::from_secs(300); +/// `SD_STATUS_READ_SECONDS`. +pub const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(60); +/// `KEEPALIVE_FILE_NAME`. +pub const KEEPALIVE_FILE_NAME: &str = "keepalive"; +/// `STATUS_BAR_KEEPALIVE_VOLUME_NAMES` (status_bar.py), used when no device is mounted. +pub const FALLBACK_KEEPALIVE_VOLUMES: [&str; 2] = ["SidePulsePro", "SidePulseDot"]; + +/// IOPM assertion types. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum AssertionKind { + /// `-d`: `PreventUserIdleDisplaySleep`. + PreventUserIdleDisplaySleep, + /// `-i`: `PreventUserIdleSystemSleep`. + PreventUserIdleSystemSleep, + /// `-m`: `PreventDiskIdle`. + PreventDiskIdle, + /// `-s`: `PreventSystemSleep` (honored on AC power only, like caffeinate). + PreventSystemSleep, +} + +impl AssertionKind { + pub fn as_str(self) -> &'static str { + match self { + Self::PreventUserIdleDisplaySleep => "PreventUserIdleDisplaySleep", + Self::PreventUserIdleSystemSleep => "PreventUserIdleSystemSleep", + Self::PreventDiskIdle => "PreventDiskIdle", + Self::PreventSystemSleep => "PreventSystemSleep", + } + } +} + +/// The `-dimsu` set used by `CAFFEINATE_COMMAND`. +pub const CAFFEINATE_DIMS: [AssertionKind; 4] = [ + AssertionKind::PreventUserIdleDisplaySleep, + AssertionKind::PreventUserIdleSystemSleep, + AssertionKind::PreventDiskIdle, + AssertionKind::PreventSystemSleep, +]; + +/// RAII guard over one or more IOPM assertions; all are released on drop. +#[derive(Debug)] +pub struct Assertion { + #[cfg_attr(not(target_os = "macos"), allow(dead_code))] + ids: Vec, +} + +impl Assertion { + /// Equivalent of `caffeinate -dimsu`. + pub fn caffeinate(reason: &str) -> io::Result { + Self::acquire(&CAFFEINATE_DIMS, reason, true) + } + + /// Creates each assertion in `kinds`; with `declare_user_activity` also declares local user + /// activity once (caffeinate `-u`), which wakes the display. Fails as a whole: anything + /// created before an error is released. + #[cfg(target_os = "macos")] + pub fn acquire( + kinds: &[AssertionKind], + reason: &str, + declare_user_activity: bool, + ) -> io::Result { + let mut guard = Self { + ids: Vec::with_capacity(kinds.len() + 1), + }; + for kind in kinds { + let id = iokit::assertion_create(kind.as_str(), reason).map_err(|rc| { + io::Error::other(format!( + "IOPMAssertionCreateWithName({}) failed: 0x{rc:08x}", + kind.as_str() + )) + })?; + guard.ids.push(id); + } + if declare_user_activity { + let id = iokit::declare_user_activity(reason).map_err(|rc| { + io::Error::other(format!( + "IOPMAssertionDeclareUserActivity failed: 0x{rc:08x}" + )) + })?; + guard.ids.push(id); + } + Ok(guard) + } + + #[cfg(not(target_os = "macos"))] + pub fn acquire( + _kinds: &[AssertionKind], + _reason: &str, + _declare_user_activity: bool, + ) -> io::Result { + Err(io::Error::new( + io::ErrorKind::Unsupported, + "power assertions need macOS", + )) + } + + /// Number of live assertion IDs held by this guard. + pub fn len(&self) -> usize { + self.ids.len() + } + + pub fn is_empty(&self) -> bool { + self.ids.is_empty() + } +} + +impl Drop for Assertion { + fn drop(&mut self) { + #[cfg(target_os = "macos")] + for id in self.ids.drain(..) { + iokit::assertion_release(id); + } + } +} + +/// Something that keeps the machine awake while held (the `caffeinate` process in Python). +pub trait Hold { + /// Acquires the hold if it is not already held. + fn acquire(&mut self) -> Result<(), String>; + /// Releases the hold if held. + fn release(&mut self); + /// `process_running()`. + fn is_held(&self) -> bool; +} + +/// A [`Hold`] backed by an [`Assertion::caffeinate`] guard. +#[derive(Debug)] +pub struct AssertionHold { + reason: String, + assertion: Option, +} + +impl AssertionHold { + pub fn new(reason: impl Into) -> Self { + Self { + reason: reason.into(), + assertion: None, + } + } +} + +impl Hold for AssertionHold { + fn acquire(&mut self) -> Result<(), String> { + if self.assertion.is_none() { + self.assertion = Some(Assertion::caffeinate(&self.reason).map_err(|e| e.to_string())?); + } + Ok(()) + } + + fn release(&mut self) { + self.assertion = None; + } + + fn is_held(&self) -> bool { + self.assertion.is_some() + } +} + +/// Port of `KeepAwakeController` (the hold half; see [`KeepaliveToucher`] for the SD touch). +pub struct KeepAwake { + pub enabled: bool, + pub grace: Duration, + hold: H, + last_mode: Option, + /// `holding_requested`: the policy wants a hold (feeds the closed-lid "agents" policy). + pub holding_requested: bool, + grace_until: Option, + pub last_error: Option, +} + +impl Default for KeepAwake { + fn default() -> Self { + Self::new(AssertionHold::new("SidePulse agents are working")) + } +} + +impl KeepAwake { + pub fn new(hold: H) -> Self { + Self { + enabled: true, + grace: AWAKE_GRACE, + hold, + last_mode: None, + holding_requested: false, + grace_until: None, + last_error: None, + } + } + + pub fn hold(&self) -> &H { + &self.hold + } + + /// `set_enabled`. + pub fn set_enabled(&mut self, enabled: bool) { + if self.enabled == enabled { + return; + } + self.enabled = enabled; + if !enabled { + self.release(); + self.holding_requested = false; + self.grace_until = None; + } + } + + /// `update(mode, now=...)`: returns whether a hold is active afterwards. + pub fn update(&mut self, mode: AgentMode, now: Instant) -> bool { + let should_hold = self.should_hold_for_mode(mode, now); + self.holding_requested = should_hold; + self.last_mode = Some(mode); + if !self.enabled || !should_hold { + self.release(); + return false; + } + self.ensure_awake(); + self.hold.is_held() + } + + /// `should_hold_for_mode`. + fn should_hold_for_mode(&mut self, mode: AgentMode, now: Instant) -> bool { + match mode { + AgentMode::Working | AgentMode::ToolRunning | AgentMode::LongTaskProgress => { + self.grace_until = None; + true + } + AgentMode::Completed | AgentMode::WaitingForInput | AgentMode::BlockedError => { + if self.last_mode != Some(mode) || self.grace_until.is_none() { + self.grace_until = Some(now + self.grace); + } + self.grace_until.is_some_and(|until| now < until) + } + _ => self.grace_until.is_some_and(|until| now < until), + } + } + + fn ensure_awake(&mut self) { + if self.hold.is_held() { + return; + } + match self.hold.acquire() { + Ok(()) => self.last_error = None, + Err(e) => self.last_error = Some(e), + } + } + + /// When the post-activity grace period ends, if it is still running at `now`. The hold is + /// released only by the next [`KeepAwake::update`] after that, so callers schedule one there. + pub fn grace_deadline(&self, now: Instant) -> Option { + self.grace_until.filter(|until| *until > now) + } + + /// `release()`. + pub fn release(&mut self) { + self.hold.release(); + } + + /// `process_running()`. + pub fn is_held(&self) -> bool { + self.hold.is_held() + } + + /// `detail(now=...)`: the menu status line. + pub fn detail(&self, now: Instant) -> String { + if !self.enabled { + return "Keep awake disabled".into(); + } + if let Some(error) = &self.last_error { + return format!("Keep awake error: {error}"); + } + if let Some(until) = self.grace_until.filter(|until| now < *until) { + let remaining = (until - now).as_secs(); + return format!("Keep awake grace: {}", format_duration(remaining)); + } + if self.hold.is_held() { + return "Keep awake active".into(); + } + "Keep awake standby".into() + } +} + +/// `format_duration(seconds)`: `"4m05s"` or `"42s"`. +pub fn format_duration(seconds: u64) -> String { + let (minutes, rest) = (seconds / 60, seconds % 60); + if minutes > 0 { + format!("{minutes}m{rest:02}s") + } else { + format!("{rest}s") + } +} + +/// `keepalive_file_for_target`: maps a device root or one of its known files to `/keepalive`. +pub fn keepalive_file_for_target(target: &Path) -> PathBuf { + let name = target + .file_name() + .map(|n| n.to_string_lossy().to_uppercase()) + .unwrap_or_default(); + let known = KNOWN_LED_FILE_NAMES.contains(&name.as_str()) + || name == KEEPALIVE_FILE_NAME.to_uppercase() + || name == "STATUS.TXT"; + if known { + target + .parent() + .unwrap_or(Path::new("")) + .join(KEEPALIVE_FILE_NAME) + } else { + target.join(KEEPALIVE_FILE_NAME) + } +} + +/// `status_keepalive_targets()` (status_bar.py): every device's LED file, or the fallback +/// `/Volumes/SidePulsePro/keepalive` and `/Volumes/SidePulseDot/keepalive` when none is found. +pub fn keepalive_targets(devices: &[Device]) -> Vec { + if !devices.is_empty() { + return devices.iter().map(Device::target).collect(); + } + FALLBACK_KEEPALIVE_VOLUMES + .iter() + .map(|name| Path::new(MOUNT_ROOT).join(name).join(KEEPALIVE_FILE_NAME)) + .collect() +} + +/// `touch_keepalive_file` without `/usr/bin/touch`: create if missing (never truncate or write +/// data) and set access and modification times to now. Fails with `NotFound` when the volume is +/// not mounted, so nothing is ever created under `/Volumes` itself. +pub fn touch(path: &Path) -> io::Result<()> { + let file = File::options() + .write(true) + .create(true) + .truncate(false) + .open(path)?; + let now = SystemTime::now(); + file.set_times(FileTimes::new().set_accessed(now).set_modified(now)) +} + +type TouchFn = fn(&Path) -> io::Result<()>; + +/// `poke_status_file` from `KeepAwakeController`: rate-limited keepalive touches. +pub struct KeepaliveToucher { + pub interval: Duration, + /// Run touches on a background thread (`status_read_async`) so a slow SD card never blocks. + pub asynchronous: bool, + toucher: TouchFn, + last_by_path: HashMap, + in_flight: Arc>>, + last_error: Arc>>, +} + +impl Default for KeepaliveToucher { + fn default() -> Self { + Self::new(touch, true) + } +} + +impl KeepaliveToucher { + pub fn new(toucher: TouchFn, asynchronous: bool) -> Self { + Self { + interval: KEEPALIVE_INTERVAL, + asynchronous, + toucher, + last_by_path: HashMap::new(), + in_flight: Arc::new(Mutex::new(HashSet::new())), + last_error: Arc::new(Mutex::new(None)), + } + } + + /// Touches the keepalive file for `target` if the interval has elapsed. Returns the path when + /// a touch was started (async) or succeeded (sync), like `poke_status_file`. + pub fn poke(&mut self, target: &Path, now: Instant) -> Option { + let path = keepalive_file_for_target(target); + if let Some(last) = self.last_by_path.get(&path) { + if now.saturating_duration_since(*last) < self.interval { + return None; + } + } + self.last_by_path.insert(path.clone(), now); + if self.asynchronous { + if !lock(&self.in_flight).insert(path.clone()) { + return None; + } + let (toucher, in_flight, last_error) = ( + self.toucher, + Arc::clone(&self.in_flight), + Arc::clone(&self.last_error), + ); + let worker_path = path.clone(); + let spawned = std::thread::Builder::new() + .name("sidepulse-keepalive".into()) + .spawn(move || { + let _ = run_touch(toucher, &worker_path, &last_error); + lock(&in_flight).remove(&worker_path); + }); + if spawned.is_err() { + lock(&self.in_flight).remove(&path); + return None; + } + return Some(path); + } + run_touch(self.toucher, &path, &self.last_error).then_some(path) + } + + /// When the next [`KeepaliveToucher::poke`] of any of `targets` will touch: `now` for a target + /// never touched, else its last touch plus [`KeepaliveToucher::interval`]. `None` without + /// targets. Lets a caller sleep exactly until a touch is due instead of polling. + pub fn next_due(&self, targets: &[PathBuf], now: Instant) -> Option { + targets + .iter() + .map(|target| { + self.last_by_path + .get(&keepalive_file_for_target(target)) + .map_or(now, |last| *last + self.interval) + }) + .min() + } + + /// `last_status_error`. + pub fn last_error(&self) -> Option { + lock(&self.last_error).clone() + } + + /// Forget timing state (`set_enabled(False)`). + pub fn reset(&mut self) { + self.last_by_path.clear(); + *lock(&self.last_error) = None; + } +} + +fn run_touch(toucher: TouchFn, path: &Path, last_error: &Mutex>) -> bool { + match toucher(path) { + Ok(()) => { + *lock(last_error) = None; + true + } + Err(e) => { + *lock(last_error) = Some(format!("{}: {e}", path.display())); + false + } + } +} + +fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { + m.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + + #[derive(Default)] + struct FakeHold { + held: bool, + acquires: usize, + releases: usize, + } + + impl Hold for FakeHold { + fn acquire(&mut self) -> Result<(), String> { + if !self.held { + self.held = true; + self.acquires += 1; + } + Ok(()) + } + fn release(&mut self) { + if self.held { + self.held = false; + self.releases += 1; + } + } + fn is_held(&self) -> bool { + self.held + } + } + + fn at(t0: Instant, secs: u64) -> Instant { + t0 + Duration::from_secs(secs) + } + + /// `test_keep_awake_holds_working_then_graces_done`. + #[test] + fn holds_working_then_graces_done() { + let t0 = Instant::now(); + let mut ka = KeepAwake::new(FakeHold::default()); + assert!(ka.update(AgentMode::Working, at(t0, 100))); + assert_eq!(ka.hold().acquires, 1); + assert!(ka.update(AgentMode::Completed, at(t0, 110))); + assert!(ka.detail(at(t0, 110)).contains("grace")); + assert_eq!(ka.detail(at(t0, 110)), "Keep awake grace: 5m00s"); + assert!(ka.update(AgentMode::IdleReady, at(t0, 200))); + assert!(ka.is_held()); + assert!(!ka.update(AgentMode::IdleReady, at(t0, 411))); + assert!(!ka.is_held()); + assert_eq!(ka.hold().releases, 1); + assert_eq!(ka.hold().acquires, 1); + assert_eq!(ka.detail(at(t0, 411)), "Keep awake standby"); + } + + /// `test_keep_awake_ask_grace_expires_without_refresh_extension`. + #[test] + fn ask_grace_expires_without_extension() { + let t0 = Instant::now(); + let mut ka = KeepAwake::new(FakeHold::default()); + assert!(ka.update(AgentMode::WaitingForInput, at(t0, 100))); + assert!(ka.update(AgentMode::WaitingForInput, at(t0, 350))); + assert!(!ka.update(AgentMode::WaitingForInput, at(t0, 401))); + assert_eq!(ka.hold().acquires, 1); + assert_eq!(ka.hold().releases, 1); + } + + #[test] + fn mode_change_restarts_grace_and_disable_clears() { + let t0 = Instant::now(); + let mut ka = KeepAwake::new(FakeHold::default()); + assert!(ka.update(AgentMode::Completed, at(t0, 0))); + assert!(ka.update(AgentMode::BlockedError, at(t0, 290))); + assert!(ka.update(AgentMode::BlockedError, at(t0, 589))); + assert!(!ka.update(AgentMode::BlockedError, at(t0, 590))); + assert!(!ka.update(AgentMode::Unknown, at(t0, 600))); + assert!(ka.update(AgentMode::ToolRunning, at(t0, 601))); + ka.set_enabled(false); + assert!(!ka.is_held()); + assert!(!ka.update(AgentMode::Working, at(t0, 602))); + assert!(ka.holding_requested); + assert_eq!(ka.detail(at(t0, 602)), "Keep awake disabled"); + } + + #[test] + fn format_duration_matches_python() { + assert_eq!(format_duration(0), "0s"); + assert_eq!(format_duration(59), "59s"); + assert_eq!(format_duration(65), "1m05s"); + assert_eq!(format_duration(300), "5m00s"); + } + + #[test] + fn keepalive_file_mapping() { + let dev = Path::new("/Volumes/SidePulsePro"); + let expected = dev.join("keepalive"); + assert_eq!(keepalive_file_for_target(&dev.join("LEDS.LED")), expected); + assert_eq!(keepalive_file_for_target(&dev.join("leds.led")), expected); + assert_eq!(keepalive_file_for_target(&dev.join("STATUS.TXT")), expected); + assert_eq!(keepalive_file_for_target(&dev.join("keepalive")), expected); + assert_eq!(keepalive_file_for_target(dev), expected); + } + + #[test] + fn keepalive_targets_fall_back_to_known_volumes() { + assert_eq!( + keepalive_targets(&[]), + vec![ + PathBuf::from("/Volumes/SidePulsePro/keepalive"), + PathBuf::from("/Volumes/SidePulseDot/keepalive"), + ] + ); + let dev = Device::from_path(Path::new("/tmp/x/SidePulseDot")); + assert_eq!( + keepalive_targets(&[dev]), + vec![PathBuf::from("/tmp/x/SidePulseDot/LEDS.LED")] + ); + } + + static TOUCHES: AtomicUsize = AtomicUsize::new(0); + fn counting_touch(_p: &Path) -> io::Result<()> { + TOUCHES.fetch_add(1, Ordering::SeqCst); + Ok(()) + } + + /// `test_keep_awake_touches_keepalive_file_once_per_interval`. + #[test] + fn touches_once_per_interval() { + let t0 = Instant::now(); + let dev = PathBuf::from("/tmp/fake/SidePulsePro"); + let status = dev.join("keepalive"); + let mut toucher = KeepaliveToucher::new(counting_touch, false); + assert_eq!( + toucher.poke(&dev.join("LEDS.LED"), at(t0, 0)), + Some(status.clone()) + ); + assert_eq!(toucher.poke(&dev.join("LEDS.LED"), at(t0, 30)), None); + assert_eq!( + toucher.poke(&dev.join("LEDS.LED"), at(t0, 61)), + Some(status) + ); + assert_eq!(TOUCHES.load(Ordering::SeqCst), 2); + } + + #[test] + fn next_due_is_exactly_when_poke_touches_again() { + fn ok(_: &Path) -> io::Result<()> { + Ok(()) + } + let t0 = Instant::now(); + let a = PathBuf::from("/tmp/fake/A/LEDS.LED"); + let b = PathBuf::from("/tmp/fake/B/LEDS.LED"); + let mut toucher = KeepaliveToucher::new(ok, false); + assert_eq!(toucher.next_due(&[], t0), None); + assert_eq!(toucher.next_due(std::slice::from_ref(&a), t0), Some(t0)); + toucher.poke(&a, t0); + toucher.poke(&b, at(t0, 10)); + let targets = [a.clone(), b.clone()]; + let due = toucher.next_due(&targets, at(t0, 20)).unwrap(); + assert_eq!(due, at(t0, 60)); + assert!(toucher.poke(&a, due - Duration::from_millis(1)).is_none()); + assert!(toucher.poke(&a, due).is_some()); + assert_eq!(toucher.next_due(&targets, due), Some(at(t0, 70))); + // A new device is due immediately. + let c = PathBuf::from("/tmp/fake/C/LEDS.LED"); + assert_eq!(toucher.next_due(&[a, b, c], due), Some(due)); + } + + #[test] + fn grace_deadline_tracks_the_grace_period() { + let t0 = Instant::now(); + let mut ka = KeepAwake::new(FakeHold::default()); + ka.update(AgentMode::Working, at(t0, 0)); + assert_eq!(ka.grace_deadline(at(t0, 0)), None); + ka.update(AgentMode::Completed, at(t0, 10)); + assert_eq!(ka.grace_deadline(at(t0, 10)), Some(at(t0, 310))); + assert_eq!(ka.grace_deadline(at(t0, 310)), None); + assert!(!ka.update(AgentMode::Completed, at(t0, 310))); + } + + #[test] + fn touch_creates_and_updates_without_truncating() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("keepalive"); + touch(&path).unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b""); + std::fs::write(&path, b"x").unwrap(); + touch(&path).unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"x"); + // A missing volume is an error, never a created directory. + let missing = dir.path().join("NotMounted").join("keepalive"); + assert!(touch(&missing).is_err()); + assert!(!dir.path().join("NotMounted").exists()); + } + + #[test] + fn async_touch_reports_errors() { + let dir = tempfile::tempdir().unwrap(); + let mut toucher = KeepaliveToucher::default(); + let missing = dir.path().join("Gone"); + assert!(toucher.poke(&missing, Instant::now()).is_some()); + for _ in 0..200 { + if toucher.last_error().is_some() { + break; + } + std::thread::sleep(Duration::from_millis(5)); + } + assert!(toucher.last_error().is_some()); + } + + #[cfg(target_os = "macos")] + #[test] + fn assertion_guard_acquires_and_releases() { + // Display/idle assertions only (no user-activity declaration, which would wake the screen). + let guard = Assertion::acquire( + &[AssertionKind::PreventUserIdleSystemSleep], + "sidepulse-core test", + false, + ) + .unwrap(); + assert_eq!(guard.len(), 1); + drop(guard); + } +} diff --git a/crates/sidepulse-core/src/power/iokit.rs b/crates/sidepulse-core/src/power/iokit.rs new file mode 100644 index 0000000..eb03d42 --- /dev/null +++ b/crates/sidepulse-core/src/power/iokit.rs @@ -0,0 +1,525 @@ +//! Minimal CoreFoundation / IOKit / IOPMLib FFI shared by `battery`, `lid` and `power`. +//! +//! Only the handful of calls the hardware modules need are declared here, so the crate needs no +//! new dependencies. Every owned CF object is wrapped in [`CfOwned`] (released on drop) and every +//! IOKit object in [`IoObject`] (`IOObjectRelease` on drop). Converting CF values goes through +//! [`to_json`], which yields plain `serde_json` values so the parsing logic stays pure and testable. + +#![allow(non_upper_case_globals)] + +use std::ffi::{c_char, c_void, CString}; +use std::ptr; + +use serde_json::{Map, Number, Value}; + +pub type CFTypeRef = *const c_void; +pub type CFStringRef = *const c_void; +pub type CFDictionaryRef = *const c_void; +pub type CFMutableDictionaryRef = *mut c_void; +pub type CFAllocatorRef = *const c_void; +pub type CFIndex = isize; +pub type CFTypeID = usize; +pub type Boolean = u8; +pub type MachPort = u32; +pub type IoObjectT = u32; +pub type KernReturn = i32; +pub type IoReturn = i32; +pub type IOPMAssertionID = u32; + +const kCFStringEncodingUTF8: u32 = 0x0800_0100; +const kCFNumberSInt64Type: CFIndex = 4; +const kCFNumberFloat64Type: CFIndex = 6; +/// `kIOMainPortDefault` / `kIOMasterPortDefault` are both `MACH_PORT_NULL`. +const kIOMainPortDefault: MachPort = 0; +pub const kIOPMAssertionLevelOn: u32 = 255; +pub const kIOPMUserActiveLocal: u32 = 0; +pub const kIOReturnSuccess: IoReturn = 0; + +#[link(name = "CoreFoundation", kind = "framework")] +extern "C" { + fn CFRelease(cf: CFTypeRef); + fn CFGetTypeID(cf: CFTypeRef) -> CFTypeID; + fn CFStringGetTypeID() -> CFTypeID; + fn CFNumberGetTypeID() -> CFTypeID; + fn CFBooleanGetTypeID() -> CFTypeID; + fn CFDictionaryGetTypeID() -> CFTypeID; + fn CFArrayGetTypeID() -> CFTypeID; + fn CFDataGetTypeID() -> CFTypeID; + fn CFStringCreateWithCString( + alloc: CFAllocatorRef, + c_str: *const c_char, + encoding: u32, + ) -> CFStringRef; + fn CFStringGetLength(s: CFStringRef) -> CFIndex; + fn CFStringGetMaximumSizeForEncoding(length: CFIndex, encoding: u32) -> CFIndex; + fn CFStringGetCString( + s: CFStringRef, + buffer: *mut c_char, + size: CFIndex, + encoding: u32, + ) -> Boolean; + fn CFNumberIsFloatType(n: CFTypeRef) -> Boolean; + fn CFNumberGetValue(n: CFTypeRef, the_type: CFIndex, value: *mut c_void) -> Boolean; + fn CFBooleanGetValue(b: CFTypeRef) -> Boolean; + fn CFDictionaryGetValue(dict: CFDictionaryRef, key: *const c_void) -> *const c_void; + fn CFDictionaryGetCount(dict: CFDictionaryRef) -> CFIndex; + fn CFDictionaryGetKeysAndValues( + dict: CFDictionaryRef, + keys: *mut *const c_void, + values: *mut *const c_void, + ); + fn CFArrayGetCount(array: CFTypeRef) -> CFIndex; + fn CFArrayGetValueAtIndex(array: CFTypeRef, idx: CFIndex) -> *const c_void; + fn CFDataGetLength(data: CFTypeRef) -> CFIndex; + fn CFDataGetBytePtr(data: CFTypeRef) -> *const u8; +} + +#[link(name = "IOKit", kind = "framework")] +extern "C" { + fn IOServiceMatching(name: *const c_char) -> CFMutableDictionaryRef; + fn IOServiceGetMatchingService(main_port: MachPort, matching: CFDictionaryRef) -> IoObjectT; + fn IORegistryEntryFromPath(main_port: MachPort, path: *const c_char) -> IoObjectT; + fn IORegistryEntryCreateCFProperty( + entry: IoObjectT, + key: CFStringRef, + allocator: CFAllocatorRef, + options: u32, + ) -> CFTypeRef; + fn IORegistryEntryCreateCFProperties( + entry: IoObjectT, + properties: *mut CFMutableDictionaryRef, + allocator: CFAllocatorRef, + options: u32, + ) -> KernReturn; + fn IOObjectRelease(object: IoObjectT) -> KernReturn; + fn IOPMAssertionCreateWithName( + assertion_type: CFStringRef, + level: u32, + name: CFStringRef, + assertion_id: *mut IOPMAssertionID, + ) -> IoReturn; + fn IOPMAssertionRelease(assertion_id: IOPMAssertionID) -> IoReturn; + fn IOPMAssertionDeclareUserActivity( + name: CFStringRef, + user_type: u32, + assertion_id: *mut IOPMAssertionID, + ) -> IoReturn; +} + +/// An owned (+1 retained) CoreFoundation object, released on drop. +pub struct CfOwned(CFTypeRef); + +impl CfOwned { + /// Takes ownership of a reference returned by a CF "Create"/"Copy" function. + fn from_create(raw: CFTypeRef) -> Option { + (!raw.is_null()).then_some(Self(raw)) + } + + pub fn as_ptr(&self) -> CFTypeRef { + self.0 + } + + /// Creates a `CFString` from UTF-8 text. `None` if the text contains a NUL byte. + pub fn string(text: &str) -> Option { + let c = CString::new(text).ok()?; + // SAFETY: `c` is a valid NUL-terminated buffer that outlives the call; a null allocator + // selects the default allocator. The result is a +1 reference owned by `CfOwned`. + Self::from_create(unsafe { + CFStringCreateWithCString(ptr::null(), c.as_ptr(), kCFStringEncodingUTF8) + }) + } +} + +impl Drop for CfOwned { + fn drop(&mut self) { + // SAFETY: `self.0` is a non-null +1 reference that this wrapper exclusively owns. + unsafe { CFRelease(self.0) } + } +} + +/// An IOKit registry entry / service handle, released on drop. +pub struct IoObject(IoObjectT); + +impl IoObject { + /// First registered service whose class matches `class_name`. + pub fn matching_service(class_name: &str) -> Option { + let c = CString::new(class_name).ok()?; + // SAFETY: `c` is NUL-terminated and outlives the call. `IOServiceMatching` returns a +1 + // dictionary that `IOServiceGetMatchingService` consumes (releases), even on failure, + // so it must not be released here. A null dictionary is checked before passing it on. + let service = unsafe { + let matching = IOServiceMatching(c.as_ptr()); + if matching.is_null() { + return None; + } + IOServiceGetMatchingService(kIOMainPortDefault, matching as CFDictionaryRef) + }; + (service != 0).then_some(Self(service)) + } + + /// Registry entry at a plane path such as `IODeviceTree:/product`. + pub fn from_path(path: &str) -> Option { + let c = CString::new(path).ok()?; + // SAFETY: `c` is NUL-terminated and outlives the call; the returned handle (or 0) is + // owned by `IoObject` and released on drop. + let entry = unsafe { IORegistryEntryFromPath(kIOMainPortDefault, c.as_ptr()) }; + (entry != 0).then_some(Self(entry)) + } + + /// Copies one property (`IORegistryEntryCreateCFProperty`). + pub fn property(&self, key: &str) -> Option { + let key = CfOwned::string(key)?; + // SAFETY: `self.0` is a live registry handle and `key` a valid CFString for the duration + // of the call. The result is a +1 reference (or null) owned by `CfOwned`. + CfOwned::from_create(unsafe { + IORegistryEntryCreateCFProperty(self.0, key.as_ptr(), ptr::null(), 0) + }) + } + + /// Copies the full property dictionary (`IORegistryEntryCreateCFProperties`). + pub fn properties(&self) -> Option { + let mut dict: CFMutableDictionaryRef = ptr::null_mut(); + // SAFETY: `self.0` is a live registry handle and `dict` is a valid out-pointer. On + // success the dictionary is a +1 reference owned by `CfOwned`. + let kr = unsafe { IORegistryEntryCreateCFProperties(self.0, &mut dict, ptr::null(), 0) }; + if kr != 0 { + return None; + } + CfOwned::from_create(dict as CFTypeRef) + } +} + +impl Drop for IoObject { + fn drop(&mut self) { + // SAFETY: `self.0` is a non-zero handle this wrapper exclusively owns. + unsafe { + IOObjectRelease(self.0); + } + } +} + +/// Looks up `key` in a CF dictionary and converts the value. Borrowed values are not released. +pub fn dict_get(dict: &CfOwned, key: &str) -> Option { + let key = CfOwned::string(key)?; + // SAFETY: `dict` is a live CFDictionary (callers pass the result of `properties()`), and + // `key` is a valid CFString. `CFDictionaryGetValue` returns a borrowed reference (or null) + // that stays valid while `dict` is alive, which covers the `to_json` call below. + let value = unsafe { + if CFGetTypeID(dict.as_ptr()) != CFDictionaryGetTypeID() { + return None; + } + CFDictionaryGetValue(dict.as_ptr(), key.as_ptr()) + }; + if value.is_null() { + return None; + } + Some(to_json(value)) +} + +/// Converts a borrowed CF property-list value into JSON. `CFData` becomes `Null`; it is read +/// separately with [`data_bytes`] where needed. +pub fn to_json(value: CFTypeRef) -> Value { + if value.is_null() { + return Value::Null; + } + // SAFETY: `value` is a non-null, live CF object borrowed from a container the caller holds. + // Each branch only calls accessors valid for the type ID it checked first, with correctly + // sized out-buffers. Nested values are borrowed from `value` and outlive the recursion. + unsafe { + let type_id = CFGetTypeID(value); + if type_id == CFBooleanGetTypeID() { + Value::Bool(CFBooleanGetValue(value) != 0) + } else if type_id == CFNumberGetTypeID() { + if CFNumberIsFloatType(value) != 0 { + let mut out = 0f64; + CFNumberGetValue( + value, + kCFNumberFloat64Type, + &mut out as *mut f64 as *mut c_void, + ); + Number::from_f64(out).map_or(Value::Null, Value::Number) + } else { + let mut out = 0i64; + CFNumberGetValue( + value, + kCFNumberSInt64Type, + &mut out as *mut i64 as *mut c_void, + ); + Value::Number(out.into()) + } + } else if type_id == CFStringGetTypeID() { + cf_string(value).map_or(Value::Null, Value::String) + } else if type_id == CFArrayGetTypeID() { + let count = CFArrayGetCount(value); + (0..count) + .map(|i| to_json(CFArrayGetValueAtIndex(value, i))) + .collect() + } else if type_id == CFDictionaryGetTypeID() { + let count = CFDictionaryGetCount(value).max(0) as usize; + let mut keys = vec![ptr::null::(); count]; + let mut values = vec![ptr::null::(); count]; + CFDictionaryGetKeysAndValues(value, keys.as_mut_ptr(), values.as_mut_ptr()); + let mut map = Map::new(); + for (k, v) in keys.into_iter().zip(values) { + if CFGetTypeID(k) == CFStringGetTypeID() { + if let Some(key) = cf_string(k) { + map.insert(key, to_json(v)); + } + } + } + Value::Object(map) + } else { + Value::Null + } + } +} + +/// Bytes of a `CFData` value; `None` for any other type. +pub fn data_bytes(value: &CfOwned) -> Option> { + // SAFETY: `value` is a live CF object; the byte pointer is only read after confirming the + // type is CFData, and only for `CFDataGetLength` bytes while `value` is alive. + unsafe { + if CFGetTypeID(value.as_ptr()) != CFDataGetTypeID() { + return None; + } + let len = CFDataGetLength(value.as_ptr()).max(0) as usize; + let ptr = CFDataGetBytePtr(value.as_ptr()); + if ptr.is_null() || len == 0 { + return Some(Vec::new()); + } + Some(std::slice::from_raw_parts(ptr, len).to_vec()) + } +} + +/// Copies a borrowed `CFString` into a Rust `String`. +/// +/// # Safety +/// `s` must be a live `CFString`. +unsafe fn cf_string(s: CFTypeRef) -> Option { + let len = CFStringGetLength(s); + let cap = CFStringGetMaximumSizeForEncoding(len, kCFStringEncodingUTF8) + 1; + if cap <= 0 { + return None; + } + let mut buf = vec![0u8; cap as usize]; + if CFStringGetCString( + s, + buf.as_mut_ptr() as *mut c_char, + cap, + kCFStringEncodingUTF8, + ) == 0 + { + return None; + } + let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len()); + buf.truncate(end); + String::from_utf8(buf).ok() +} + +/// `IOPMAssertionCreateWithName(type, kIOPMAssertionLevelOn, name)`. +pub fn assertion_create(assertion_type: &str, name: &str) -> Result { + let kind = CfOwned::string(assertion_type).ok_or(-1)?; + let name = CfOwned::string(name).ok_or(-1)?; + let mut id: IOPMAssertionID = 0; + // SAFETY: both CFStrings are live for the call and `id` is a valid out-pointer. + let rc = unsafe { + IOPMAssertionCreateWithName(kind.as_ptr(), kIOPMAssertionLevelOn, name.as_ptr(), &mut id) + }; + if rc == kIOReturnSuccess { + Ok(id) + } else { + Err(rc) + } +} + +/// `IOPMAssertionDeclareUserActivity(name, kIOPMUserActiveLocal)`, which wakes the display. +pub fn declare_user_activity(name: &str) -> Result { + let name = CfOwned::string(name).ok_or(-1)?; + let mut id: IOPMAssertionID = 0; + // SAFETY: `name` is live for the call and `id` is a valid out-pointer. + let rc = + unsafe { IOPMAssertionDeclareUserActivity(name.as_ptr(), kIOPMUserActiveLocal, &mut id) }; + if rc == kIOReturnSuccess { + Ok(id) + } else { + Err(rc) + } +} + +/// `IOPMAssertionRelease(id)`. +pub fn assertion_release(id: IOPMAssertionID) -> IoReturn { + // SAFETY: releasing an assertion ID is safe even if it is stale; the kernel validates it. + unsafe { IOPMAssertionRelease(id) } +} + +// ---- Notifications delivered on the main run loop ------------------------------------------- + +pub type CFRunLoopRef = *mut c_void; +pub type CFRunLoopSourceRef = *mut c_void; +pub type CFRunLoopMode = CFStringRef; +pub type IONotificationPortRef = *mut c_void; +type IOServiceInterestCallback = extern "C" fn( + refcon: *mut c_void, + service: IoObjectT, + message_type: u32, + argument: *mut c_void, +); +type IOPowerSourceCallbackType = extern "C" fn(context: *mut c_void); + +#[link(name = "CoreFoundation", kind = "framework")] +extern "C" { + static kCFRunLoopCommonModes: CFRunLoopMode; + fn CFRunLoopGetMain() -> CFRunLoopRef; + fn CFRunLoopAddSource(rl: CFRunLoopRef, source: CFRunLoopSourceRef, mode: CFRunLoopMode); + fn CFRunLoopRemoveSource(rl: CFRunLoopRef, source: CFRunLoopSourceRef, mode: CFRunLoopMode); +} + +#[link(name = "IOKit", kind = "framework")] +extern "C" { + fn IONotificationPortCreate(main_port: MachPort) -> IONotificationPortRef; + fn IONotificationPortDestroy(notify: IONotificationPortRef); + fn IONotificationPortGetRunLoopSource(notify: IONotificationPortRef) -> CFRunLoopSourceRef; + fn IOServiceAddInterestNotification( + notify: IONotificationPortRef, + service: IoObjectT, + interest_type: *const c_char, + callback: IOServiceInterestCallback, + refcon: *mut c_void, + notification: *mut IoObjectT, + ) -> KernReturn; + fn IOPSNotificationCreateRunLoopSource( + callback: IOPowerSourceCallbackType, + context: *mut c_void, + ) -> CFRunLoopSourceRef; +} + +/// `kIOGeneralInterest`. +const kIOGeneralInterest: &[u8] = b"IOGeneralInterest\0"; + +type InterestHandler = Box; + +/// A `kIOGeneralInterest` registration on one service, delivered on the main run loop (common +/// modes, so it also fires while a menu is open). Unregistered on drop. +pub struct InterestWatch { + port: IONotificationPortRef, + notification: IoObjectT, + // Boxed twice so the refcon stays a thin pointer at a stable address. + _handler: Box, +} + +extern "C" fn interest_trampoline( + refcon: *mut c_void, + _service: IoObjectT, + message_type: u32, + _argument: *mut c_void, +) { + // SAFETY: `refcon` is the `Box` owned by the `InterestWatch`, which outlives + // the registration (it is released in `Drop` before the box is freed). IOKit calls this on the + // main run loop only, so there is never concurrent access to the handler. + let handler = unsafe { &mut *refcon.cast::() }; + handler(message_type); +} + +impl InterestWatch { + /// Registers `handler(message_type)` for general-interest messages from the first service + /// matching `class_name`. Must be called on the main thread. + pub fn new(class_name: &str, handler: InterestHandler) -> Option { + let service = IoObject::matching_service(class_name)?; + let mut handler = Box::new(handler); + // SAFETY: `kIOMainPortDefault` is valid; the returned port (or null) is checked. + let port = unsafe { IONotificationPortCreate(kIOMainPortDefault) }; + if port.is_null() { + return None; + } + let mut notification: IoObjectT = 0; + let refcon = (&mut *handler as *mut InterestHandler).cast::(); + // SAFETY: `port` and `service.0` are live, the interest type is NUL-terminated, the + // callback has the C signature IOKit expects, `refcon` points at the boxed handler that + // this watch keeps alive, and `notification` is a valid out-pointer. The service object + // may be released after registering; the notification holds its own reference. + let kr = unsafe { + IOServiceAddInterestNotification( + port, + service.0, + kIOGeneralInterest.as_ptr().cast(), + interest_trampoline, + refcon, + &mut notification, + ) + }; + if kr != 0 { + // SAFETY: `port` came from `IONotificationPortCreate` and is not used afterwards. + unsafe { IONotificationPortDestroy(port) }; + return None; + } + // SAFETY: `port` is live; its run-loop source is owned by the port (not retained here) + // and is added to the main run loop, which lives for the whole process. + unsafe { + let source = IONotificationPortGetRunLoopSource(port); + CFRunLoopAddSource(CFRunLoopGetMain(), source, kCFRunLoopCommonModes); + } + Some(Self { + port, + notification, + _handler: handler, + }) + } +} + +impl Drop for InterestWatch { + fn drop(&mut self) { + // SAFETY: both handles are owned by this watch. Releasing the notification object stops + // delivery; destroying the port also invalidates its run-loop source. + unsafe { + IOObjectRelease(self.notification); + IONotificationPortDestroy(self.port); + } + } +} + +type PowerSourceHandler = Box; + +/// `IOPSNotificationCreateRunLoopSource`: fires on any power-source change (plug, unplug, +/// charge level, time remaining), on the main run loop. Removed on drop. +pub struct PowerSourceWatch { + source: CFRunLoopSourceRef, + _handler: Box, +} + +extern "C" fn power_source_trampoline(context: *mut c_void) { + // SAFETY: `context` is the `Box` owned by the `PowerSourceWatch`, which + // removes the source before freeing it; delivery is on the main run loop only. + let handler = unsafe { &mut *context.cast::() }; + handler(); +} + +impl PowerSourceWatch { + /// Must be called on the main thread. + pub fn new(handler: PowerSourceHandler) -> Option { + let mut handler = Box::new(handler); + let context = (&mut *handler as *mut PowerSourceHandler).cast::(); + // SAFETY: the callback has the expected C signature and `context` points at the boxed + // handler kept alive by this watch. The result is a +1 source (or null). + let source = + unsafe { IOPSNotificationCreateRunLoopSource(power_source_trampoline, context) }; + if source.is_null() { + return None; + } + // SAFETY: `source` is a live run-loop source; the main run loop lives for the process. + unsafe { CFRunLoopAddSource(CFRunLoopGetMain(), source, kCFRunLoopCommonModes) }; + Some(Self { + source, + _handler: handler, + }) + } +} + +impl Drop for PowerSourceWatch { + fn drop(&mut self) { + // SAFETY: `source` is the +1 reference created in `new`, added to the main run loop. + unsafe { + CFRunLoopRemoveSource(CFRunLoopGetMain(), self.source, kCFRunLoopCommonModes); + CFRelease(self.source); + } + } +} diff --git a/src/providers.rs b/crates/sidepulse-core/src/providers.rs similarity index 100% rename from src/providers.rs rename to crates/sidepulse-core/src/providers.rs diff --git a/src/pyjson.rs b/crates/sidepulse-core/src/pyjson.rs similarity index 100% rename from src/pyjson.rs rename to crates/sidepulse-core/src/pyjson.rs diff --git a/crates/sidepulse-hook/Cargo.toml b/crates/sidepulse-hook/Cargo.toml new file mode 100644 index 0000000..1b6fd50 --- /dev/null +++ b/crates/sidepulse-hook/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "sidepulse-hook" +description = "Drop-in native replacement for SidePulse's Python agent hook." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +publish.workspace = true + +[dependencies] +sidepulse-core = { path = "../sidepulse-core" } diff --git a/src/bin/sidepulse-hook.rs b/crates/sidepulse-hook/src/main.rs similarity index 79% rename from src/bin/sidepulse-hook.rs rename to crates/sidepulse-hook/src/main.rs index 7825299..d7ed5e2 100644 --- a/src/bin/sidepulse-hook.rs +++ b/crates/sidepulse-hook/src/main.rs @@ -8,14 +8,14 @@ fn main() { std::panic::set_hook(Box::new(|_| {})); let args: Vec = std::env::args().skip(1).collect(); let _ = std::panic::catch_unwind(|| { - let Some((provider, log_path)) = sidepulse::hook::parse_args(&args) else { + let Some((provider, log_path)) = sidepulse_core::hook::parse_args(&args) else { return; }; let mut input = Vec::new(); if std::io::stdin().read_to_end(&mut input).is_err() { return; } - sidepulse::hook::hook_log_main(&provider, &log_path, &input); + sidepulse_core::hook::hook_log_main(&provider, &log_path, &input); }); std::process::exit(0); } diff --git a/scripts/install-bar.sh b/scripts/install-bar.sh new file mode 100755 index 0000000..2c63ff0 --- /dev/null +++ b/scripts/install-bar.sh @@ -0,0 +1,80 @@ +#!/bin/bash +# Install sidepulse-bar as the login agent, replacing the Python SidePulse menu-bar app. +# scripts/install-bar.sh install (builds release first) and switch over +# scripts/install-bar.sh --revert stop sidepulse-bar and restore the Python app's agent +set -euo pipefail + +LABEL=io.sidepulse.bar +PY_LABEL=io.sidepulse.agentstatus +AGENTS="$HOME/Library/LaunchAgents" +PLIST="$AGENTS/$LABEL.plist" +PY_PLIST="$AGENTS/$PY_LABEL.plist" +BACKUP="$HOME/Library/LaunchAgents.disabled-sidepulse-python" +BIN="$HOME/.local/bin/sidepulse-bar" +STATE="${XDG_STATE_HOME:-$HOME/.local/state}/sidepulse/agent-monitor" +DOMAIN="gui/$(id -u)" + +# `launchctl bootout` returns before the job is gone; bootstrapping too early fails with EIO. +stop_job() { + launchctl bootout "$DOMAIN/$1" 2>/dev/null || true + for _ in $(seq 50); do + launchctl print "$DOMAIN/$1" >/dev/null 2>&1 || return 0 + sleep 0.2 + done +} + +start_job() { + for _ in 1 2 3 4 5; do + launchctl bootstrap "$DOMAIN" "$1" 2>/dev/null && return 0 + sleep 1 + done + launchctl bootstrap "$DOMAIN" "$1" +} + +if [[ "${1:-}" == "--revert" ]]; then + stop_job "$LABEL" + rm -f "$PLIST" + if [[ -f "$BACKUP/$PY_LABEL.plist" ]]; then + mv "$BACKUP/$PY_LABEL.plist" "$PY_PLIST" + start_job "$PY_PLIST" + echo "Restored the Python SidePulse app ($PY_LABEL)." + else + echo "No backed-up Python agent found; run 'sidepulse setup' to reinstall it." + fi + exit 0 +fi + +cd "$(dirname "$0")/.." +cargo build --release -p sidepulse-bar +mkdir -p "$(dirname "$BIN")" "$STATE" "$AGENTS" +install -m 755 target/release/sidepulse-bar "$BIN" + +cat > "$PLIST" < + + + + Label$LABEL + ProgramArguments$BIN + RunAtLoad + + KeepAliveSuccessfulExit + ProcessTypeInteractive + StandardOutPath$STATE/sidepulse-bar.out.log + StandardErrorPath$STATE/sidepulse-bar.err.log + + +EOF +plutil -lint "$PLIST" >/dev/null + +# Stop the Python app first: both apps own the same events.sock and LED device. +stop_job "$PY_LABEL" +if [[ -f "$PY_PLIST" ]]; then + mkdir -p "$BACKUP" + mv "$PY_PLIST" "$BACKUP/" +fi + +stop_job "$LABEL" +start_job "$PLIST" +echo "sidepulse-bar installed as $LABEL (logs: $STATE/sidepulse-bar.out.log)." +echo "Revert with: scripts/install-bar.sh --revert"