feat(desktop): keep the Mac awake while agents work, lid closed included

Codeman > Keep This Mac Awake in the macOS app: While Agents Work (an
agent at work, plus 5 minutes after the last one stops) or Always While
Codeman Is Open. Off by default, and only for a Codeman on this Mac.

- Idle sleep needs no password: the app holds an NSProcessInfo activity
  with IdleSystemSleepDisabled, which the kernel drops with the process.
  While it only watches for work, an activity that still allows sleep
  keeps App Nap from slowing its look at the server.
- On a MacBook, Only on Power Adapter (on by default) pauses it on
  battery, and Also With the Lid Closed installs a small LaunchDaemon
  behind macOS's administrator prompt. It sets pmset disablesleep only
  while the app keeps a fresh request file with its live pid, only on
  the power adapter, and undoes only what it set itself. The app writes
  the script and plist as root from the copies built into it.
- A status line at the bottom of the submenu says what it does now.

This brings the macOS part of the keep-awake idea from PR #595 into the
app; the server-side setting and the Linux route are left out for now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Codeman maintainer committed 2026-11-09 04:51:39 +01:00
1 parent f62c1f7e2f
commit 79a6c03363
10 files changed
+2474

No files matched your search

+37
View File
@@ -3,6 +3,7 @@
//! (`~/Library/Application Support/Codeman/desktop.json` on macOS). Passwords
//! never go here; they live in the Keychain (see `credentials`).
use crate::keep_awake;
use crate::logo::BlinkStyles;
use serde::{Deserialize, Serialize};
use std::fs;
@@ -49,6 +50,10 @@ pub struct Config {
/// reads as off: a bad style must not make the whole file unreadable.
#[serde(deserialize_with = "lenient_blink")]
pub logo_blink: BlinkStyles,
/// Keep This Mac Awake (keep_awake.rs): when, only on the power adapter, and
/// with the lid closed too. Read field by field, like `logo_blink`.
#[serde(deserialize_with = "lenient_keep_awake")]
pub keep_awake: keep_awake::Settings,
/// Anything that is not a whole frame reads as None: a bad frame must not
/// make the whole file unreadable, which would cost the server list.
#[serde(deserialize_with = "lenient_window")]
@@ -64,6 +69,10 @@ fn lenient_blink<'de, D: serde::Deserializer<'de>>(d: D) -> Result<BlinkStyles,
Ok(BlinkStyles::read(&serde_json::Value::deserialize(d)?))
}
fn lenient_keep_awake<'de, D: serde::Deserializer<'de>>(d: D) -> Result<keep_awake::Settings, D::Error> {
Ok(keep_awake::Settings::read(&serde_json::Value::deserialize(d)?))
}
impl Default for Config {
fn default() -> Self {
Config {
@@ -71,6 +80,7 @@ impl Default for Config {
auto_connect: true,
start_fullscreen: false,
logo_blink: BlinkStyles::default(),
keep_awake: keep_awake::Settings::default(),
window: None,
}
}
@@ -429,6 +439,33 @@ mod tests {
}
}
#[test]
fn keep_awake_round_trips_and_a_bad_value_never_costs_the_file() {
use crate::keep_awake::{Mode, Settings};
let mut c = Config::default();
assert_eq!(c.keep_awake, Settings::default());
c.keep_awake.mode = Mode::WhileWorking;
c.keep_awake.lid = true;
let text = serde_json::to_string(&c).unwrap();
assert!(
text.contains(r#""keepAwake":{"mode":"whileWorking","acOnly":true,"lid":true}"#),
"{text}"
);
assert_eq!(serde_json::from_str::<Config>(&text).unwrap().keep_awake, c.keep_awake);
for bad in [
r#"{"keepAwake":3}"#,
r#"{"keepAwake":null}"#,
r#"{"keepAwake":"always"}"#,
] {
let c: Config = serde_json::from_str(bad).unwrap();
assert_eq!(c.keep_awake, Settings::default(), "{bad}");
}
// A file from before the setting: every other field still reads.
let c: Config = serde_json::from_str(r#"{"startFullscreen":true}"#).unwrap();
assert!(c.start_fullscreen);
assert_eq!(c.keep_awake, Settings::default());
}
#[test]
fn the_style_a_mac_saved_before_there_were_states_is_kept() {
use crate::logo::BlinkStyle;
File diff suppressed because it is too large. Load diff
+18
View File
@@ -222,6 +222,13 @@ pub fn content_size(window: &tao::window::Window) -> Option<(f64, f64)> {
imp::content_size(window)
}
/// An app-modal message with an OK button, for something the user asked the app
/// itself to do that failed. Main thread only; does nothing elsewhere.
#[cfg(target_os = "macos")]
pub fn show_message(title: &str, detail: &str) {
imp::show_message(title, detail);
}
#[cfg(target_os = "macos")]
mod imp {
use std::cell::{Cell, RefCell};
@@ -456,6 +463,17 @@ mod imp {
}
}
pub(super) fn show_message(title: &str, detail: &str) {
let Some(mtm) = MainThreadMarker::new() else {
return;
};
let alert = NSAlert::new(mtm);
alert.setMessageText(&NSString::from_str(title));
alert.setInformativeText(&NSString::from_str(detail));
let _ = alert.addButtonWithTitle(&NSString::from_str("OK"));
alert.runModal();
}
pub(super) fn content_size(window: &tao::window::Window) -> Option<(f64, f64)> {
// NSWindow is main-thread only.
MainThreadMarker::new()?;
+163
View File
@@ -27,6 +27,7 @@ mod assets;
mod config;
mod credentials;
mod gui_install;
mod keep_awake;
mod local_server;
mod login;
mod logo;
@@ -182,6 +183,18 @@ enum UserEvent {
/// install opened in Terminal, the install command copied): the message
/// goes to the page if it is still the one choosing a server.
ToConnectPage(serde_json::Value),
/// The keep-awake worker's status line, for the value numbered `generation`
/// (keep_awake::KeepAwake::is_current).
KeepAwakeStatus {
generation: u64,
text: String,
},
/// The administrator prompt for the lid helper was answered, and its command
/// ran (keep_awake::install_helper, keep_awake::remove_helper).
LidHelperDone {
install: bool,
outcome: keep_awake::AdminOutcome,
},
}
struct ProbeDone {
@@ -318,6 +331,10 @@ struct App {
fullscreen_retry: Option<(Instant, u8)>,
/// The child that watches the connected server and blinks the logo.
logo_watch: logo::Watcher,
/// The worker that keeps this Mac awake while its agents work.
keep_awake: keep_awake::KeepAwake,
/// An administrator prompt for the lid helper is open.
lid_helper_busy: bool,
}
fn main() {
@@ -370,6 +387,7 @@ fn main() {
let mut windows = HashMap::new();
windows.insert(main_id, AppWindow::new(webview, window, Kind::Main));
let keep_awake_proxy = proxy.clone();
let mut app = App {
proxy,
config,
@@ -397,6 +415,10 @@ fn main() {
add_agent_on_load: false,
fullscreen_retry: wants_fullscreen.then(|| (Instant::now() + FULLSCREEN_FIRST_CHECK, 0)),
logo_watch: logo::Watcher::default(),
keep_awake: keep_awake::KeepAwake::new(move |generation, text| {
let _ = keep_awake_proxy.send_event(UserEvent::KeepAwakeStatus { generation, text });
}),
lid_helper_busy: false,
};
event_loop.run(move |event, target, control_flow| app.handle(event, target, control_flow));
@@ -730,6 +752,7 @@ impl App {
} => self.show_main_window(),
Event::MainEventsCleared => self.on_events_cleared(control_flow),
Event::LoopDestroyed => {
self.keep_awake.shutdown();
self.record_main_frame();
self.save_config();
}
@@ -796,6 +819,7 @@ impl App {
if id == self.main_id {
// Closing the main window quits; the server and its
// sessions keep running, so nothing is lost.
self.keep_awake.shutdown();
self.record_main_frame();
self.save_config();
*control_flow = ControlFlow::Exit;
@@ -875,6 +899,7 @@ impl App {
*self.phase.borrow_mut() = next;
}
self.sync_logo_watch();
self.sync_keep_awake();
}
if let Some(w) = self.windows.get_mut(&window) {
w.committed = Url::parse(&url).ok();
@@ -937,6 +962,14 @@ impl App {
}
UserEvent::AuthRejected => self.recheck_login(),
UserEvent::ContentProcessGone { window } => self.on_content_process_gone(window),
UserEvent::KeepAwakeStatus { generation, text } => {
if self.keep_awake.is_current(generation) {
if let Some(items) = &self.menu.keep_awake {
items.status.set_text(&text);
}
}
}
UserEvent::LidHelperDone { install, outcome } => self.on_lid_helper_done(install, outcome),
}
}
@@ -1061,12 +1094,142 @@ impl App {
}
}
/// Keep-awake watches the open server while a mode is chosen. Whether that
/// server is this Mac is the worker's to find out.
fn sync_keep_awake(&mut self) {
let settings = self.config.keep_awake;
let server = self.phase.borrow().loaded().cloned();
let watch = server
.filter(|_| settings.mode != keep_awake::Mode::Off)
.map(|server| keep_awake::Watch {
server,
authorization: self.auth.clone(),
settings,
});
let idle = match (settings.mode, &watch) {
(keep_awake::Mode::Off, _) => Some(keep_awake::OFF_TEXT),
(_, None) => Some(keep_awake::NO_SERVER_TEXT),
_ => None,
};
self.keep_awake.sync(watch);
if let (Some(text), Some(items)) = (idle, &self.menu.keep_awake) {
items.status.set_text(text);
}
}
fn choose_keep_awake_mode(&mut self, mode: keep_awake::Mode) {
if let Some(items) = &self.menu.keep_awake {
// A click flips the item it landed on, the chosen one included.
for (item_mode, item) in &items.modes {
item.set_checked(*item_mode == mode);
}
}
self.config.keep_awake.mode = mode;
self.config_dirty = true;
self.sync_keep_awake();
}
fn toggle_keep_awake_ac_only(&mut self) {
let Some(item) = self.menu.keep_awake.as_ref().and_then(|items| items.ac_only.as_ref()) else {
return;
};
self.config.keep_awake.ac_only = item.is_checked();
self.config_dirty = true;
self.sync_keep_awake();
}
/// Choosing the lid item asks for the administrator password first while the
/// helper is missing or from another version; the setting goes on once it is in.
fn toggle_keep_awake_lid(&mut self) {
let Some(items) = &self.menu.keep_awake else {
return;
};
let Some(item) = &items.lid else {
return;
};
let state = keep_awake::request_path().map_or(keep_awake::HelperState::Missing, |request| {
keep_awake::helper_state(&request)
});
if !item.is_checked() || state == keep_awake::HelperState::Installed {
self.config.keep_awake.lid = item.is_checked();
self.config_dirty = true;
items.show_helper(state, self.config.keep_awake.lid);
self.sync_keep_awake();
return;
}
// Not on until the helper is in.
item.set_checked(false);
self.run_lid_helper(true);
}
fn run_lid_helper(&mut self, install: bool) {
if self.lid_helper_busy {
return;
}
self.lid_helper_busy = true;
let proxy = self.proxy.clone();
std::thread::spawn(move || {
let outcome = match install {
true => keep_awake::install_helper(),
false => keep_awake::remove_helper(),
};
let _ = proxy.send_event(UserEvent::LidHelperDone { install, outcome });
});
}
fn on_lid_helper_done(&mut self, install: bool, outcome: keep_awake::AdminOutcome) {
use keep_awake::{AdminOutcome, HelperState};
self.lid_helper_busy = false;
let state =
keep_awake::request_path().map_or(HelperState::Missing, |request| keep_awake::helper_state(&request));
let failure = match (&outcome, install, state) {
(AdminOutcome::Cancelled, _, _) => None,
(AdminOutcome::Failed(error), true, _) => Some(("The lid helper could not be installed.", error.clone())),
(AdminOutcome::Failed(error), false, _) => Some(("The lid helper could not be removed.", error.clone())),
(AdminOutcome::Done, true, HelperState::Installed) => {
self.config.keep_awake.lid = true;
self.config_dirty = true;
None
}
(AdminOutcome::Done, true, _) => Some((
"The lid helper could not be installed.",
"The installation ran, but the helper's files are not what the app wrote.".to_owned(),
)),
(AdminOutcome::Done, false, HelperState::Missing) => {
self.config.keep_awake.lid = false;
self.config_dirty = true;
None
}
(AdminOutcome::Done, false, _) => Some((
"The lid helper could not be removed.",
"The removal ran, but the helper's files are still there.".to_owned(),
)),
};
if let Some(items) = &self.menu.keep_awake {
items.show_helper(state, self.config.keep_awake.lid);
}
self.keep_awake.refresh();
self.sync_keep_awake();
if let Some((title, detail)) = failure {
eprintln!("codeman-desktop: {title} {detail}");
#[cfg(target_os = "macos")]
macos::show_message(title, &detail);
}
}
fn on_menu(&mut self, id: &str) {
if let Some((signal, style)) = BlinkStyle::from_menu_id(id) {
self.choose_logo_blink(signal, style);
return;
}
if let Some(mode) = keep_awake::Mode::from_menu_id(id) {
self.choose_keep_awake_mode(mode);
return;
}
match id {
keep_awake::AC_ONLY_ID => self.toggle_keep_awake_ac_only(),
keep_awake::LID_ID => self.toggle_keep_awake_lid(),
keep_awake::REMOVE_HELPER_ID => self.run_lid_helper(false),
menu_id::SWITCH => self.show_connect_page(None, true),
menu_id::ADD_AGENT => self.add_agent(),
menu_id::RELOAD => self.reload_focused(),
+99
View File
@@ -4,6 +4,7 @@ use muda::accelerator::{Accelerator, Code, Modifiers};
use muda::{AboutMetadata, CheckMenuItem, Menu, MenuItem, PredefinedMenuItem, Submenu};
use crate::config::Config;
use crate::keep_awake::{self, HelperState, Mode};
use crate::logo::{self, BlinkStyle, Signal};
use crate::{APP_NAME, VERSION};
@@ -29,6 +30,94 @@ pub struct AppMenu {
/// One item per state and style. Empty on a Mac without a lit logo, which has no
/// such menu.
pub logo_styles: Vec<(Signal, BlinkStyle, CheckMenuItem)>,
/// None where the app cannot keep the Mac awake (a build for another OS).
pub keep_awake: Option<KeepAwakeMenu>,
}
/// App menu > Keep This Mac Awake.
pub struct KeepAwakeMenu {
pub modes: Vec<(Mode, CheckMenuItem)>,
/// Only on a Mac with a lid: a desktop Mac always runs on mains and cannot close.
pub ac_only: Option<CheckMenuItem>,
pub lid: Option<CheckMenuItem>,
pub remove_helper: Option<MenuItem>,
/// What it does right now (keep_awake::status_line). Not clickable.
pub status: MenuItem,
}
impl KeepAwakeMenu {
/// The lid items as the helper now is. The lid item ends in an ellipsis while
/// choosing it asks for the administrator password first.
pub fn show_helper(&self, state: HelperState, lid_on: bool) {
if let Some(item) = &self.lid {
item.set_text(lid_label(state));
item.set_checked(lid_on && state == HelperState::Installed);
}
if let Some(item) = &self.remove_helper {
item.set_enabled(state != HelperState::Missing);
}
}
}
fn lid_label(state: HelperState) -> &'static str {
match state {
HelperState::Installed => "Also With the Lid Closed",
_ => "Also With the Lid Closed\u{2026}",
}
}
fn build_keep_awake(config: &Config) -> muda::Result<(Submenu, KeepAwakeMenu)> {
let settings = config.keep_awake;
let submenu = Submenu::new("Keep This Mac Awake", true);
let mut modes = Vec::new();
for mode in Mode::ALL {
let item = CheckMenuItem::with_id(mode.menu_id(), mode.label(), true, settings.mode == mode, None);
submenu.append(&item)?;
modes.push((mode, item));
}
let (mut ac_only, mut lid, mut remove_helper) = (None, None, None);
if keep_awake::has_lid() {
let state =
keep_awake::request_path().map_or(HelperState::Missing, |request| keep_awake::helper_state(&request));
let ac = CheckMenuItem::with_id(
keep_awake::AC_ONLY_ID,
"Only on Power Adapter",
true,
settings.ac_only,
None,
);
let lid_item = CheckMenuItem::with_id(
keep_awake::LID_ID,
lid_label(state),
true,
settings.lid && state == HelperState::Installed,
None,
);
let remove = MenuItem::with_id(
keep_awake::REMOVE_HELPER_ID,
"Remove the Lid Helper\u{2026}",
state != HelperState::Missing,
None,
);
submenu.append_items(&[&PredefinedMenuItem::separator(), &ac, &lid_item, &remove])?;
(ac_only, lid, remove_helper) = (Some(ac), Some(lid_item), Some(remove));
}
let initial = match settings.mode {
Mode::Off => keep_awake::OFF_TEXT,
_ => keep_awake::NO_SERVER_TEXT,
};
let status = MenuItem::new(initial, false, None);
submenu.append_items(&[&PredefinedMenuItem::separator(), &status])?;
Ok((
submenu,
KeepAwakeMenu {
modes,
ac_only,
lid,
remove_helper,
status,
},
))
}
pub fn build_menu(config: &Config) -> muda::Result<AppMenu> {
@@ -67,6 +156,15 @@ pub fn build_menu(config: &Config) -> muda::Result<AppMenu> {
&PredefinedMenuItem::quit(None),
],
)?;
// Right under "Add a Coding Agent to This Mac…".
let keep_awake = match keep_awake::available() {
true => {
let (submenu, items) = build_keep_awake(config)?;
app_menu.insert(&submenu, 4)?;
Some(items)
}
false => None,
};
// Without these items Cmd+C / Cmd+V do nothing inside a WKWebView.
let edit = Submenu::with_items(
"Edit",
@@ -157,5 +255,6 @@ pub fn build_menu(config: &Config) -> muda::Result<AppMenu> {
help_menu,
start_fullscreen,
logo_styles,
keep_awake,
})
}