From 04221b498431ecba8bcde2e68b7450d2b39e70ed Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Tue, 27 Oct 2026 16:36:05 -0400 Subject: [PATCH 1/3] LR-BEHAV-BG-TASKS: a running job keeps the Mac awake and the app out of App Nap --- Cargo.lock | 1 + Cargo.toml | 4 +- apps/lightcraft-web/src/web.rs | 1 + apps/lightcraft/Cargo.toml | 1 + apps/lightcraft/src/keep_awake.rs | 111 +++++++++++++++++++++++++++ apps/lightcraft/src/main.rs | 2 + apps/lightcraft/src/session.rs | 5 ++ crates/engine/src/activity.rs | 81 +++++++++++++++++++ crates/ui-egui/src/app.rs | 2 + crates/ui-egui/src/app/frame.rs | 28 +++++++ crates/ui-egui/src/lib.rs | 6 +- crates/ui-egui/src/services.rs | 6 ++ crates/ui-egui/src/tests/activity.rs | 53 +++++++++++++ crates/ui-egui/tests/shutdown.rs | 12 ++- docs/background-tasks.md | 7 ++ docs/parity-checklist.md | 3 +- docs/whats-new.md | 6 +- 17 files changed, 323 insertions(+), 6 deletions(-) create mode 100644 apps/lightcraft/src/keep_awake.rs diff --git a/Cargo.lock b/Cargo.lock index acd433bc27b..775307b0aff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3589,6 +3589,7 @@ dependencies = [ name = "lightcraft" version = "0.18.0" dependencies = [ + "block2 0.6.2", "chrono", "craft-update", "eframe", diff --git a/Cargo.toml b/Cargo.toml index 8549d6167e4..d5d0a74fec5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -114,7 +114,9 @@ muda = { version = "0.21", default-features = false } # native menu bar (macOS: # macOS: the profile of the screen showing the window (safe AppKit bindings; muda and wgpu use the same) objc2 = { version = "0.6", default-features = false, features = ["std"] } objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSApplication", "NSColorSpace", "NSResponder", "NSScreen", "NSWindow"] } -objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSArray", "NSData"] } +objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSData", "NSProcessInfo", "NSString"] } +# macOS: the block `NSProcessInfo` runs while a job holds the Mac awake (the version objc2-foundation already uses) +block2 = { version = "0.6", default-features = false, features = ["std"] } # Linux: the desktop's dark/light setting from the XDG settings portal (Settings ▸ Interface ▸ # Appearance Mode ▸ Auto). Pure Rust; the version accesskit already brings in, pinned to it. zbus = "=5.19.0" diff --git a/apps/lightcraft-web/src/web.rs b/apps/lightcraft-web/src/web.rs index 79773918b47..de06f87bdf7 100644 --- a/apps/lightcraft-web/src/web.rs +++ b/apps/lightcraft-web/src/web.rs @@ -334,6 +334,7 @@ fn services( pick_folder: None, // the browser reports prefers-color-scheme to egui system_theme: None, + keep_awake: None, } } diff --git a/apps/lightcraft/Cargo.toml b/apps/lightcraft/Cargo.toml index cf8aaf2e067..afd108711a2 100644 --- a/apps/lightcraft/Cargo.toml +++ b/apps/lightcraft/Cargo.toml @@ -51,6 +51,7 @@ muda = { workspace = true } objc2 = { workspace = true } objc2-app-kit = { workspace = true } objc2-foundation = { workspace = true } +block2 = { workspace = true } [dev-dependencies] # tests record why they skip (`cargo xtask ci` lists the skips) diff --git a/apps/lightcraft/src/keep_awake.rs b/apps/lightcraft/src/keep_awake.rs new file mode 100644 index 00000000000..a67033fab24 --- /dev/null +++ b/apps/lightcraft/src/keep_awake.rs @@ -0,0 +1,111 @@ +//! Keep running while a long job does (macOS). +//! +//! While an export, import or other job the person started is in flight, macOS must neither put the Mac to idle +//! sleep nor App-Nap the window: a minimized or hidden app is throttled, and a long export of a library on a share +//! stalls. The UI says when that changes (`Services::keep_awake`, from `Activity::wake_reason`); this holds the +//! matching `NSProcessInfo` activity (user initiated, idle system sleep disabled) whose reason names the job, which +//! `pmset -g assertions` then shows. +//! +//! The activity is held with `performActivityWithOptions:reason:usingBlock:`, which is safe to call: a helper thread +//! sits inside the block until its [`Hold`] is dropped, and AppKit ends the activity when the block returns. +//! `beginActivityWithOptions:reason:` would need `endActivity:`, an `unsafe` method, and this crate forbids `unsafe`. +//! Activities belong to the process, not to the thread that began them. + +use std::sync::{Arc, Mutex, PoisonError, mpsc}; + +use block2::RcBlock; +use objc2_foundation::{NSActivityOptions, NSProcessInfo, NSString}; + +/// A running activity: dropping it ends it. +pub struct Hold { + /// The helper thread waits for this to disconnect. + _release: mpsc::Sender<()>, +} + +/// Begin an activity named `reason`. `previous` ends only once this one has begun, so the Mac is never left +/// unprotected when the job named in the reason changes. If the helper thread can't start, `previous` is returned +/// still held (the Mac stays protected, under the old reason), or `None` when there was none. +pub fn begin(reason: &str, previous: Option) -> Option { + let (release, wait) = mpsc::channel::<()>(); + let reason = reason.to_owned(); + // shared with the thread so that a thread that never starts leaves it here + let previous = Arc::new(Mutex::new(previous)); + let handed = previous.clone(); + let spawned = std::thread::Builder::new().name("keep-awake".into()).spawn(move || { + // (an `NSString` is not `Send`: made here) + let reason = NSString::from_str(&reason); + let held = RcBlock::new(move || { + // begun: the one before it can go + drop(handed.lock().unwrap_or_else(PoisonError::into_inner).take()); + // (Err: the hold was dropped, which is the end) + let _ = wait.recv(); + }); + NSProcessInfo::processInfo().performActivityWithOptions_reason_usingBlock( + NSActivityOptions::UserInitiated | NSActivityOptions::IdleSystemSleepDisabled, + &reason, + &held, + ); + }); + match spawned { + Ok(_) => Some(Hold { _release: release }), + Err(e) => { + log::warn!("could not keep the Mac awake for a running job: {e}"); + previous.lock().unwrap_or_else(PoisonError::into_inner).take() + } + } +} + +/// The host service: holds one activity while the UI says a job needs it. +pub fn service() -> lightcraft_ui_egui::KeepAwakeFn { + let mut hold: Option = None; + Box::new(move |reason| { + hold = match reason { + Some(reason) => begin(reason, hold.take()), + None => None, + }; + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::time::{Duration, Instant}; + + fn assertions() -> String { + let out = std::process::Command::new("pmset").args(["-g", "assertions"]).output().expect("pmset runs"); + String::from_utf8_lossy(&out.stdout).into_owned() + } + + fn wait_for(reason: &str, present: bool) -> bool { + let t0 = Instant::now(); + while t0.elapsed() < Duration::from_secs(10) { + if assertions().contains(reason) == present { + return true; + } + std::thread::sleep(Duration::from_millis(100)); + } + false + } + + #[test] + fn a_hold_shows_in_the_power_assertions_until_it_is_dropped() { + let reason = format!("LightCraft test hold {}", std::process::id()); + let hold = begin(&reason, None).expect("the helper thread starts"); + assert!(wait_for(&reason, true), "pmset lists the activity while the hold lives"); + drop(hold); + assert!(wait_for(&reason, false), "pmset stops listing it once the hold is dropped"); + } + + #[test] + fn a_new_reason_replaces_the_old_one() { + let first = format!("LightCraft first hold {}", std::process::id()); + let second = format!("LightCraft second hold {}", std::process::id()); + let a = begin(&first, None); + assert!(wait_for(&first, true)); + let b = begin(&second, a); + assert!(wait_for(&second, true)); + assert!(wait_for(&first, false), "the earlier one ends once the later one has begun"); + drop(b); + assert!(wait_for(&second, false)); + } +} diff --git a/apps/lightcraft/src/main.rs b/apps/lightcraft/src/main.rs index 3a7bda66960..f496ff8f5a1 100644 --- a/apps/lightcraft/src/main.rs +++ b/apps/lightcraft/src/main.rs @@ -32,6 +32,8 @@ mod control_server; mod dialog_filter; mod editors; mod hdr_display; +#[cfg(target_os = "macos")] +mod keep_awake; mod logging; #[cfg(target_os = "macos")] mod native_menu; diff --git a/apps/lightcraft/src/session.rs b/apps/lightcraft/src/session.rs index c02ce47a1e0..1d903732ba1 100644 --- a/apps/lightcraft/src/session.rs +++ b/apps/lightcraft/src/session.rs @@ -150,6 +150,11 @@ pub(crate) fn services(cc: &eframe::CreationContext<'_>, log_file: Option<&std:: screen_profile: win_screen_profile::service(cc), #[cfg(not(any(target_os = "macos", target_os = "linux", windows)))] screen_profile: None, + // macOS: a running job keeps the Mac awake and the window out of App Nap + #[cfg(target_os = "macos")] + keep_awake: Some(keep_awake::service()), + #[cfg(not(target_os = "macos"))] + keep_awake: None, pick_display_profile: Some(Box::new(|| { let mut d = file_dialog() .set_title(lightcraft_ui_egui::i18n::tr("Choose Monitor Profile")) diff --git a/crates/engine/src/activity.rs b/crates/engine/src/activity.rs index 147d20f3a58..3b8628d63e2 100644 --- a/crates/engine/src/activity.rs +++ b/crates/engine/src/activity.rs @@ -217,6 +217,27 @@ impl Activity { pub fn running_cancellable(&self) -> Vec { lock(&self.inner.tasks).iter().filter(|e| e.is_cancellable() && !e.is_cancelled()).map(|e| e.info()).collect() } + + /// Why the machine should stay awake for the work in flight, or `None` when nothing needs it: the label of the + /// oldest job the person started, with `+ N more` when others run too. A job asked to stop no longer counts, and + /// neither does housekeeping the person did not ask for ([`holds_awake`]). The label is English: it is for the + /// system's logs and tools (`pmset -g assertions`), not for the window. + pub fn wake_reason(&self) -> Option { + let tasks = lock(&self.inner.tasks); + let mut holding = tasks.iter().filter(|e| holds_awake(e.kind) && !e.is_cancelled()); + let first = holding.next()?; + Some(match holding.count() { + 0 => first.label.clone(), + more => format!("{} + {more} more", first.label), + }) + } +} + +/// Whether a task of `kind` is work the person started and would not want cut short by the machine sleeping. The +/// thumbnail cache tidy, the GPU check, the focus-point reading, the face scan and the checks of recent libraries and +/// of raw files start by themselves (and the first can hang on an offline share). +fn holds_awake(kind: &str) -> bool { + !matches!(kind, "cache" | "facesGpu" | "focus" | "faces" | "library" | "recheck") } /// A task's place in the list, held by whoever owns the job; dropping it removes the row. @@ -303,6 +324,66 @@ impl TaskHandle { } } +#[cfg(test)] +mod wake_tests { + use super::*; + + #[test] + fn nothing_running_needs_no_wake() { + assert_eq!(Activity::default().wake_reason(), None); + } + + #[test] + fn a_running_export_names_itself() { + let a = Activity::default(); + let _g = a.start("export", "Exporting", Cancel::Yes); + assert_eq!(a.wake_reason().as_deref(), Some("Exporting")); + } + + #[test] + fn housekeeping_the_person_did_not_ask_for_does_not_count() { + let a = Activity::default(); + let _c = a.start("cache", "Tidying the thumbnail cache", Cancel::Yes); + let _f = a.start("facesGpu", "Checking the GPU for faces", Cancel::No); + let _s = a.start("faces", "Finding faces", Cancel::No); + let _p = a.start("focus", "Reading focus points", Cancel::Yes); + let _l = a.start("library", "Checking recent libraries", Cancel::No); + let _r = a.start("recheck", "Checking raw files", Cancel::Yes); + assert_eq!(a.wake_reason(), None); + let _e = a.start("import", "Importing", Cancel::Yes); + assert_eq!(a.wake_reason().as_deref(), Some("Importing")); + } + + #[test] + fn several_jobs_name_the_oldest_and_count_the_rest() { + let a = Activity::default(); + let _x = a.start("export", "Exporting", Cancel::Yes); + let _c = a.start("cache", "Tidying the thumbnail cache", Cancel::Yes); + let _i = a.start("import", "Importing", Cancel::Yes); + let _p = a.start("previews", "Building previews", Cancel::Yes); + assert_eq!(a.wake_reason().as_deref(), Some("Exporting + 2 more")); + } + + #[test] + fn the_hold_ends_when_the_last_job_ends() { + let a = Activity::default(); + let x = a.start("export", "Exporting", Cancel::Yes); + let i = a.start("import", "Importing", Cancel::Yes); + drop(x); + assert_eq!(a.wake_reason().as_deref(), Some("Importing")); + drop(i); + assert_eq!(a.wake_reason(), None); + } + + #[test] + fn a_job_that_was_asked_to_stop_no_longer_holds() { + let a = Activity::default(); + let x = a.start("export", "Exporting", Cancel::Yes); + a.cancel(x.id()).unwrap(); + assert_eq!(a.wake_reason(), None); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 74425972d80..d10a9e5d21f 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -137,6 +137,7 @@ impl LightcraftApp { display_error: None, screen_profile: None, screen_profile_read: None, + awake_told: None, library_problem: None, library_window_input: Default::default(), alt_asks_for_library: false, @@ -610,6 +611,7 @@ impl LightcraftApp { /// on other threads (export, denoise, the device warm-up). `false`: the deadline passed first /// (the host exits anyway). The app renders nothing afterwards. pub fn shutdown(&mut self, timeout: std::time::Duration) -> bool { + self.release_keep_awake(); lightcraft_engine::gpu::begin_shutdown(); #[cfg(not(target_arch = "wasm32"))] let t0 = std::time::Instant::now(); diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 66e377a9138..6059e369e1c 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -59,11 +59,39 @@ impl LightcraftApp { } } + /// Tell the host what should keep the machine awake (`services.keep_awake`), when that changes. While a job + /// holds, a repaint is asked for every second so its end is noticed (and the hold released) even when nothing + /// else is drawn. Once the app is shutting down the hold is gone for good ([`LightcraftApp::release_keep_awake`]). + pub(super) fn sync_keep_awake(&mut self, ctx: &egui::Context) { + if lightcraft_engine::gpu::shutting_down() { + return; + } + let Some(keep_awake) = self.services.keep_awake.as_mut() else { return }; + let reason = self.session.activity.wake_reason(); + if reason.is_some() { + ctx.request_repaint_after(std::time::Duration::from_secs(1)); + } + if reason != self.awake_told { + keep_awake(reason.as_deref()); + self.awake_told = reason; + } + } + + /// Let go of the hold the host was told about, if any (quitting). + pub(super) fn release_keep_awake(&mut self) { + if let Some(keep_awake) = self.services.keep_awake.as_mut() + && self.awake_told.take().is_some() + { + keep_awake(None); + } + } + /// Queues and timers. Each consumed queue is drained once per call; time-gated work uses the /// monotonic app clock, so a hidden `run_logic` keeps it advancing and a second layout pass is /// a no-op rather than a duplicate. pub(super) fn logic_background(&mut self, ctx: &egui::Context) { self.background_prep(ctx); + self.sync_keep_awake(ctx); panels::notices::logic(self, ctx); // closing the window (or Quit) with changes only in memory: retry, else ask first if ctx.input(|i| i.viewport().close_requested()) && !panels::notices::may_close(self) { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e1b34105562..1c3bae9ac7c 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -102,8 +102,8 @@ pub use clock::{monotonic_ms, now_ms}; #[cfg(target_os = "linux")] pub use services::OpenModelFolderFn; pub use services::{ - CheckEditorFn, HostAction, OpenAllWithFn, OpenUrlFn, OpenWithFn, PickFiles, PickFolder, PngEncode, RevealFn, SaveFile, ScreenProfileFn, Services, - SharedWrite, SystemThemeFn, WriteFn, + CheckEditorFn, HostAction, KeepAwakeFn, OpenAllWithFn, OpenUrlFn, OpenWithFn, PickFiles, PickFolder, PngEncode, RevealFn, SaveFile, + ScreenProfileFn, Services, SharedWrite, SystemThemeFn, WriteFn, }; use state::{GestureFrame, InjectedPress}; @@ -385,6 +385,8 @@ pub struct LightcraftApp { /// and when it was last read (egui time, s). pub(crate) screen_profile: Option>, pub(crate) screen_profile_read: Option, + /// What the host was last told keeps the machine awake (`services.keep_awake`): the reason, or `None` for idle. + pub(crate) awake_told: Option, /// The library failed to open at launch: the blocking window, then the temporary-session /// banner (issue #100). Cleared once a library opens. pub library_problem: Option, diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 695a9d7d6de..ab8bdf7193a 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -35,6 +35,10 @@ pub type OpenModelFolderFn = std::sync::Arc Result<(), String> + /// not known). pub type ScreenProfileFn = Box Option>>; +/// Told when the work that should keep the machine awake changes: `Some(reason)` while a job the person started runs +/// (the reason names it), `None` once nothing needs it. Called only on a change, always from the UI thread. +pub type KeepAwakeFn = Box)>; + /// Whether an external editor can be started (its name as in [`Services::open_with`]); the /// error says why not and what to do (e.g. PhotoCraft isn't installed). pub type CheckEditorFn = Box Result<(), String>>; @@ -130,4 +134,6 @@ pub struct Services { pub restore_library: Option, /// The system appearance for Appearance Mode ▸ Auto, ahead of egui's own report. pub system_theme: Option, + /// Keep the system from sleeping or throttling the app while a long job runs (macOS App Nap and idle sleep). + pub keep_awake: Option, } diff --git a/crates/ui-egui/src/tests/activity.rs b/crates/ui-egui/src/tests/activity.rs index b353405ffca..b3d86e219c2 100644 --- a/crates/ui-egui/src/tests/activity.rs +++ b/crates/ui-egui/src/tests/activity.rs @@ -591,3 +591,56 @@ fn immediate_library_commands_and_auto_sync_show_completion() { assert!(h.app.run("library.compact", json!({})).is_err()); assert!(h.app.ui.toast.is_none()); } + +/// What `services.keep_awake` was told, in order. +type Told = std::rc::Rc>>>; + +fn demo_keeping_awake() -> (Headless, Told) { + let told = Told::default(); + let sink = told.clone(); + let keep_awake: crate::KeepAwakeFn = Box::new(move |reason| sink.borrow_mut().push(reason.map(str::to_owned))); + let app = LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, keep_awake: Some(keep_awake), ..Default::default() }); + let mut h = Headless::new(app, [1200.0, 800.0], 1.0); + h.settle(T); + told.borrow_mut().clear(); + (h, told) +} + +#[test] +fn a_running_job_is_told_to_the_host_once_and_its_end_too() { + let (mut h, told) = demo_keeping_awake(); + for _ in 0..3 { + h.step(); + } + assert!(told.borrow().is_empty(), "nothing runs: the host hears nothing"); + + let g = h.app.session.activity.start("export", "Exporting", Cancel::Yes); + for _ in 0..4 { + h.step(); + } + assert_eq!(*told.borrow(), [Some("Exporting".to_string())], "told once, not on every frame"); + + drop(g); + for _ in 0..4 { + h.step(); + } + assert_eq!(*told.borrow(), [Some("Exporting".to_string()), None]); +} + +#[test] +fn a_cancelled_job_is_released_before_it_stops() { + let (mut h, told) = demo_keeping_awake(); + let g = h.app.session.activity.start("export", "Exporting", Cancel::Yes); + h.step(); + h.app.session.activity.cancel(g.id()).unwrap(); + h.step(); + assert_eq!(*told.borrow(), [Some("Exporting".to_string()), None]); +} + +#[test] +fn a_window_with_no_host_service_ignores_jobs() { + let mut h = demo(); + let _g = h.app.session.activity.start("export", "Exporting", Cancel::Yes); + h.step(); + assert_eq!(h.app.awake_told, None); +} diff --git a/crates/ui-egui/tests/shutdown.rs b/crates/ui-egui/tests/shutdown.rs index 1a601bc78f3..719a5795ff7 100644 --- a/crates/ui-egui/tests/shutdown.rs +++ b/crates/ui-egui/tests/shutdown.rs @@ -10,7 +10,11 @@ use lightcraft_ui_egui::{LightcraftApp, Services}; #[test] fn shutdown_leaves_no_render_worker_running() { - let services = Services { png: None, ..Default::default() }; + // what the host was told about jobs holding the machine awake + let told = std::rc::Rc::new(std::cell::RefCell::new(Vec::>::new())); + let sink = told.clone(); + let keep_awake: lightcraft_ui_egui::KeepAwakeFn = Box::new(move |reason| sink.borrow_mut().push(reason.map(str::to_owned))); + let services = Services { png: None, keep_awake: Some(keep_awake), ..Default::default() }; let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo(), services), [1200.0, 760.0], 1.0); // frames until the grid's thumbnails are being rendered on the workers let t0 = Instant::now(); @@ -19,8 +23,13 @@ fn shutdown_leaves_no_render_worker_running() { h.step(); } assert!(!lightcraft_engine::gpu::shutting_down()); + // a job is running when the app quits: the hold on the machine ends with it + let _job = h.app.session.activity.start("export", "Exporting", lightcraft_engine::activity::Cancel::Yes); + h.step(); + assert_eq!(told.borrow().last(), Some(&Some("Exporting".to_string()))); assert!(h.app.shutdown(Duration::from_secs(120)), "the jobs that were running ended in time"); + assert_eq!(told.borrow().last(), Some(&None), "quitting lets go of the hold"); assert_eq!(h.app.renderer.live_workers(), 0); assert_eq!(h.app.renderer.queued(), 0, "jobs that had not started are dropped"); assert!(lightcraft_engine::gpu::shutting_down()); @@ -30,6 +39,7 @@ fn shutdown_leaves_no_render_worker_running() { for _ in 0..3 { h.step(); } + assert_eq!(told.borrow().last(), Some(&None), "the job still runs, but the window does not take the hold again"); assert_eq!(h.app.renderer.live_workers(), 0); assert_eq!(h.app.renderer.queued(), 0); diff --git a/docs/background-tasks.md b/docs/background-tasks.md index 6f2b0034772..d7bc718def1 100644 --- a/docs/background-tasks.md +++ b/docs/background-tasks.md @@ -6,6 +6,13 @@ the amount of work isn't known), the count and what it's working on, and ✕ if a task that can stop is running. Agents see the same list through `activity.list` / `activity.cancel`, and `ui.inspect` reports it as `activity`. +On macOS a running job the person started also keeps the Mac awake: `Activity::wake_reason` names the oldest such job +(housekeeping that starts by itself, like the thumbnail-cache tidy, the focus-point reading and the face scan, doesn't count, and neither does a job that was asked to stop), the UI tells +the host when that changes (`Services::keep_awake`), and the app holds an `NSProcessInfo` activity (user initiated, +idle system sleep disabled) with that reason until the last job ends, is cancelled or the app quits. +`pmset -g assertions` lists it. A new `kind` that is background housekeeping rather than something the person asked for +goes in `holds_awake` in `activity.rs`. + The registry is `lightcraft_engine::activity` (`crates/engine/src/activity.rs`, `Session::activity`). The stack is `crates/ui-egui/src/panels/activity.rs`. Every job that can last more than a moment uses it; **don't add a progress window, panel or progress toast of your own**. A dialog may still show progress inline (the Synchronize Folder diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index cf6ab0de745..df5b7543227 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -463,7 +463,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-BEHAV-BATCH | Batch apply to selection | P0 | ✅ | `cmd:photo.rate`, `cmd:develop.paste`, `cmd:preset.apply`, `cmd:app.export` | | | LR-BEHAV-PREVIEW-HOVER | Hover previews | P1 | ✅ | `crates/ui-egui/src/panels/presets.rs`, `crates/ui-egui/src/panels/profiles.rs`, `crates/ui-egui/src/panels/right.rs` (`versions`), `crates/ui-egui/src/panels/detail.rs` | presets, profile menu, profile browser and versions preview in the loupe | | LR-BEHAV-PROGRESSIVE | Progressive rendering | P0 | ✅ | `crates/engine/src/media.rs`, `crates/preview/src/lib.rs` | | -| LR-BEHAV-BG-TASKS | Background tasks | P0 | ✅ | `cmd:activity.list`, `cmd:activity.cancel`, `crates/engine/src/activity.rs`, `crates/ui-egui/src/panels/activity.rs`, `crates/ui-egui/src/widgets/progress.rs`, `docs/background-tasks.md`, `crates/preview/src/lib.rs` (`JobPool`) | renders off the UI thread; exports run several photos of a batch side by side (`export_parallelism`, memory-gated; files, names and order as one at a time, #496); one activity stack in the top-left corner under the top bar, as in Lightroom Classic (issue #345): imports, folder scans, exports (and the contact sheet PDF), Synchronize Folder (its scan and its run), Build / Smart Previews, Lightroom catalog inspect / import, Photo Merge, model downloads (SAM 3, face, AI Denoise), the face scan, AI Denoise, Find Missing Photos and Reload from Disk (`cmd:photo.reload`, its files decoded on a worker thread, cancellable; `wait: true` for agents) each show a row (name, progress bar or a sweep while the amount isn't known, count and current item) once 0.5 s old, three rows then "+N more"; ✕ cancels the jobs that can stop ("Stopping…" until they do); quitting asks while a cancellable task runs; agents and `ui.inspect` (`activity`) see the same list. No pause (Lightroom can pause some tasks) | +| LR-BEHAV-BG-TASKS | Background tasks | P0 | ✅ | `cmd:activity.list`, `cmd:activity.cancel`, `crates/engine/src/activity.rs`, `crates/ui-egui/src/panels/activity.rs`, `crates/ui-egui/src/widgets/progress.rs`, `docs/background-tasks.md`, `crates/preview/src/lib.rs` (`JobPool`), `apps/lightcraft/src/keep_awake.rs` | renders off the UI thread; exports run several photos of a batch side by side (`export_parallelism`, memory-gated; files, names and order as one at a time, #496); one activity stack in the top-left corner under the top bar, as in Lightroom Classic (issue #345): imports, folder scans, exports (and the contact sheet PDF), Synchronize Folder (its scan and its run), Build / Smart Previews, Lightroom catalog inspect / import, Photo Merge, model downloads (SAM 3, face, AI Denoise), the face scan, AI Denoise, Find Missing Photos and Reload from Disk (`cmd:photo.reload`, its files decoded on a worker thread, cancellable; `wait: true` for agents) each show a row (name, progress bar or a sweep while the amount isn't known, count and current item) once 0.5 s old, three rows then "+N more"; ✕ cancels the jobs that can stop ("Stopping…" until they do); quitting asks while a cancellable task runs; agents and `ui.inspect` (`activity`) see the same list; on macOS a running job the person started holds an `NSProcessInfo` activity (no idle sleep, no App Nap) until the last one ends or is cancelled. No pause (Lightroom can pause some tasks) | | LR-BEHAV-OFFLINE | Offline editing | P1 | ✅ | | local-first: everything works offline | | LR-BEHAV-WEB-SAFETY | Library safety in the browser build | P1 | 🟡 | `cmd:file.backupLibrary`, `cmd:file.restoreLibrary`, `apps/lightcraft-web/src/safety.rs`, `apps/lightcraft-web/src/backup.rs`, `apps/lightcraft-web/src/files.rs` | web only (experimental): Back Up Library (zip of the catalog and every stored original) and a non-destructive Restore; failed saves show as unsaved and are retried; a photo that can't be stored isn't added; one tab per library (Web Locks); notices for storage that isn't persistent and for a library that can't open; `?reset` asks first; a panic shows a message. Missing: `?safe` start, deleting originals of removed photos, zip64 (backups > 4 GB) | | LR-BEHAV-GPU | GPU acceleration | P0 | ✅ | `crates/gpu/src/render.rs`, `cmd:app.gpu`, `docs/gpu-pipeline.md`, `crates/ui-egui/src/panels/notices.rs` | CPU fallback per render on device limits, out of memory, device errors / loss, incomplete or black results (`perf.gpuReason`, `perf.gpuFallback`; each render reports its own reason — `lightcraft_gpu::try_render`, `gpuFallback` per exported file — issue #675); short submissions for slow iGPUs; backend choice (DX12 only on Windows, `LIGHTCRAFT_GPU_BACKEND` / `WGPU_BACKEND`), device created after the window opens, crash sentinel (issue #136); a GPU lost while LightCraft runs (driver reset) stops it with that message and turns GPU rendering off for the next start, which says why (issue #1337; the window's renderer can't survive the lost device); quitting waits (up to 2 s) for renders in flight and starts no new GPU work, so none is inside the driver when the process exits (`crates/gpu/src/exit.rs`, issue #620; seen crashing only on Linux + NVIDIA, other drivers unverified); with GPU rendering on and no adapter found at all (e.g. no Vulkan loader on NixOS outside `nix develop`), the desktop app says once per session that it renders on the CPU and points to Help ▸ System Info (`gpu_notice`; not when the GPU is turned off or only a software adapter exists); no tiling beyond the buffer limit (CPU) | @@ -802,6 +802,7 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | Date | Change | Summary | |---|---|---| +| 2026-10-27 | minor | LR-BEHAV-BG-TASKS: on macOS a running job the person started (export, import, preview build, merge, Synchronize Folder…) keeps the Mac from idle sleep and the app out of App Nap until the last one ends or is cancelled; status unchanged (✅) | | 2026-11-07 | correction | Compressed ORF sensor support withdrawn pending provenance review; embedded preview fallback remains. Coverage regenerated without the removed decoder: 557 verified, 665 unverified, 187 preview-only, 37 unsupported; 94% use-weighted coverage. | | 2026-11-04 | minor | Compressed ORF support was introduced in #3775; subsequently withdrawn pending provenance review. Earlier clean-room and verification claims are withdrawn; compressed files use embedded previews when available. See [ORF status](orf-compression.md). | | 2026-10-28 | minor | KEY-HIDEPINS ✅ → 🟡: in the Masking panel an unmodified H toggles the mask pins (`view.maskPins`, the View ▸ Show Mask Pins switch) instead of opening Remove; the toggle yields only to an explicit assignment of H itself, a Remove key reassigned to anything else still opens Remove there, and outside Masking — and the full-screen preview, where no panel shows — H keeps its own binding (Remove, by default). Remove's spot pins keep ⇧H as their only hide toggle (`tests/keymap` `h_toggles_the_mask_pins_while_masking`, `a_remapped_remove_key_still_opens_remove_while_masking`, `h_still_toggles_the_pins_when_remove_moves_to_another_key`) | diff --git a/docs/whats-new.md b/docs/whats-new.md index ab0f90c0338..4688fa3cec1 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -38,6 +38,11 @@ process 5: new photos (and Reset) get it, photos you already edited keep their look until you choose Photo ▸ Update to Current Process. See [process versions](process-versions.md). +### On macOS, a long job keeps the Mac awake +- While an export, import, preview build, merge or other job you started is running, the Mac no longer goes to sleep + on its own and macOS no longer slows the app down when its window is hidden or minimized. Both end as soon as the + last job finishes or is canceled. + ## 2026-11-02 ### The Windows title bar is readable from the moment the window opens @@ -343,7 +348,6 @@ a second. On a Mac the window also holds one drawable less: its width × height × 4 bytes, 15–22 MB for a 1200–1500-point-wide window on a Retina display. - ## 2026-10-24 ### AI Denoise follows the photo's real noise From 3636d6477a2f1b9865b6bcb9c24eb94dca8c9214 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 8 Nov 2026 07:14:45 -0500 Subject: [PATCH 2/3] LR-BEHAV-BG-TASKS: list every housekeeping kind the keep-awake rule skips Co-Authored-By: Claude --- docs/background-tasks.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/background-tasks.md b/docs/background-tasks.md index d7bc718def1..1363e30ec80 100644 --- a/docs/background-tasks.md +++ b/docs/background-tasks.md @@ -7,7 +7,8 @@ a task that can stop is running. Agents see the same list through `activity.list `ui.inspect` reports it as `activity`. On macOS a running job the person started also keeps the Mac awake: `Activity::wake_reason` names the oldest such job -(housekeeping that starts by itself, like the thumbnail-cache tidy, the focus-point reading and the face scan, doesn't count, and neither does a job that was asked to stop), the UI tells +(housekeeping that starts by itself doesn't count: the thumbnail-cache tidy, the GPU check, the focus-point reading, +the face scan and the checks of recent libraries and of raw files; neither does a job that was asked to stop), the UI tells the host when that changes (`Services::keep_awake`), and the app holds an `NSProcessInfo` activity (user initiated, idle system sleep disabled) with that reason until the last job ends, is cancelled or the app quits. `pmset -g assertions` lists it. A new `kind` that is background housekeeping rather than something the person asked for From 1e5a09811a7550b06dda693241b913b3ba412434 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 8 Nov 2026 07:26:21 -0500 Subject: [PATCH 3/3] LR-BEHAV-BG-TASKS: a test that a holding job asks for a repaint within a second Co-Authored-By: Claude --- crates/ui-egui/src/app/frame.rs | 37 +++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 6059e369e1c..292f66f3acd 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -548,3 +548,40 @@ impl LightcraftApp { pub(crate) fn import_tick_allowed(ctx: &egui::Context) -> bool { ctx.current_pass_index() == 0 } + +#[cfg(test)] +mod keep_awake_tests { + use std::sync::{Arc, Mutex}; + use std::time::Duration; + + use crate::Services; + use lightcraft_engine::activity::Cancel; + + use super::*; + + /// A context that records every delay it is asked to repaint after. + fn recording_context() -> (egui::Context, Arc>>) { + let ctx = egui::Context::default(); + let asked = Arc::new(Mutex::new(Vec::new())); + let sink = asked.clone(); + ctx.set_request_repaint_callback(move |info| sink.lock().unwrap().push(info.delay)); + (ctx, asked) + } + + fn app_with_keep_awake() -> LightcraftApp { + let keep_awake: crate::KeepAwakeFn = Box::new(|_| {}); + LightcraftApp::new(lightcraft_engine::Session::with_demo(), Services { png: None, keep_awake: Some(keep_awake), ..Default::default() }) + } + + #[test] + fn a_holding_job_asks_for_a_repaint_within_a_second_and_an_idle_app_asks_for_none() { + let (ctx, asked) = recording_context(); + let mut app = app_with_keep_awake(); + app.sync_keep_awake(&ctx); + assert!(asked.lock().unwrap().is_empty(), "nothing runs: no repaint is asked for"); + + let _job = app.session.activity.start("export", "Exporting", Cancel::Yes); + app.sync_keep_awake(&ctx); + assert_eq!(*asked.lock().unwrap(), [Duration::from_secs(1)], "the end of the job is looked for every second"); + } +}