diff --git a/crates/engine/src/activity.rs b/crates/engine/src/activity.rs index 147d20f3a5..c7b4944ca4 100644 --- a/crates/engine/src/activity.rs +++ b/crates/engine/src/activity.rs @@ -7,14 +7,80 @@ //! check between files or photos: the guard adopts it ([`Cancel::Flag`]), so the stack's ✕, `activity.cancel` and the //! job's own Cancel all set the same atomic. Numbers are worded by the frontend from `done`, `total` and [`Unit`]; a //! detail set here is a name (a file, a model), never a sentence, so the frontend can translate everything else. +//! +//! Jobs that must not run side by side share a [`Lane`]. One asked for while its lane is busy can wait in line +//! ([`Activity::enqueue`]): it keeps what it was asked ([`Request`], the command and its parameters) and runs it +//! when the jobs ahead of it are over ([`crate::Session::start_waiting`]), planning its work then, not when it was +//! asked. Nothing waits across another library: the files may have changed meanwhile. use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use serde::Serialize; +use serde_json::Value; /// The longest label or detail kept, in characters (a file name can be anything). const MAX_TEXT: usize = 200; +/// The most tasks waiting in line, in all lanes. +pub const MAX_WAITING: usize = 100; + +/// Jobs that must not run side by side: one waits for those ahead of it to end. Kinds without a lane run as they +/// always did (and are refused while one of their kind runs, where that is the rule). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub enum Lane { + /// Build Previews and Build / Discard Smart Previews: one preview build at a time (`Session::preview_build`). + Previews, +} + +impl Lane { + /// The lane of tasks of `kind` ([`TaskInfo::kind`]). + pub fn of(kind: &str) -> Option { + match kind { + "previews" | "smartPreviews" => Some(Lane::Previews), + _ => None, + } + } +} + +/// What a job was asked: the command and its parameters, with everything that depends on the moment (the +/// selection, the photos in view) written out, so that running it later does the same work. +#[derive(Clone, Debug, PartialEq)] +pub struct Request { + pub command: String, + pub params: Value, +} + +/// A task waiting in line ([`Activity::enqueue`]), as [`Activity::take_ready`] hands it over to be started. +#[derive(Debug)] +pub struct Waiting { + pub id: u64, + pub kind: &'static str, + pub label: String, + pub lane: Lane, + pub request: Request, + queued: web_time::Instant, +} + +impl Waiting { + fn info(&self, place: usize) -> TaskInfo { + TaskInfo { + id: self.id, + kind: self.kind, + label: self.label.clone(), + done: 0, + total: 0, + unit: Unit::Count, + detail: String::new(), + cancellable: true, + cancelling: false, + age_ms: millis(self.queued.elapsed()), + waiting: true, + place, + lane: Some(self.lane), + } + } +} /// The background tasks in flight. Cheap to clone (one `Arc`), so worker threads can hold it. #[derive(Clone, Default)] @@ -26,6 +92,10 @@ pub struct Activity { struct Inner { /// Oldest first. tasks: Mutex>>, + /// The tasks waiting in line, in the order they were asked for. + waiting: Mutex>, + /// The id the waiting task being started keeps (its kind, its id): see [`Activity::take_ready`]. + reserved: Mutex>, next: AtomicU64, } @@ -87,6 +157,11 @@ pub struct TaskInfo { /// Cancel was asked for; the job stops at its next check. pub cancelling: bool, pub age_ms: u64, + /// It waits in line for the tasks ahead of it in its lane (nothing done yet: `done` and `total` are 0). + pub waiting: bool, + /// Its place in its lane's line, from 1; 0 for a running task. + pub place: usize, + pub lane: Option, } struct Entry { @@ -162,7 +237,10 @@ impl Entry { detail: lock(&self.detail).clone(), cancellable: self.is_cancellable(), cancelling: self.is_cancelled(), - age_ms: u64::try_from(self.started.elapsed().as_millis()).unwrap_or(u64::MAX), + age_ms: millis(self.started.elapsed()), + waiting: false, + place: 0, + lane: Lane::of(self.kind), } } } @@ -171,7 +249,9 @@ impl Activity { /// Register a task; it is listed until the returned guard is dropped. `label` is English (the frontend /// translates it). pub fn start(&self, kind: &'static str, label: &str, cancel: Cancel) -> TaskGuard { - let id = self.inner.next.fetch_add(1, Ordering::Relaxed).saturating_add(1); + // a task that waited in line keeps the id it had there + let reserved = lock(&self.inner.reserved).take_if(|(k, _)| *k == kind).map(|(_, id)| id); + let id = reserved.unwrap_or_else(|| self.inner.next.fetch_add(1, Ordering::Relaxed).saturating_add(1)); let cancel = match cancel { Cancel::No => None, Cancel::Yes => Some(Arc::new(AtomicBool::new(false))), @@ -194,29 +274,130 @@ impl Activity { TaskGuard { activity: self.clone(), entry } } - /// Every task in flight, oldest first. + /// Every task in flight, oldest first, then those waiting in line, in the order they were asked for. pub fn list(&self) -> Vec { - lock(&self.inner.tasks).iter().map(|e| e.info()).collect() + let mut rows: Vec = lock(&self.inner.tasks).iter().map(|e| e.info()).collect(); + rows.extend(self.waiting()); + rows } - /// Ask task `id` to stop (it stops at its next check). An unknown id (the task may have just ended) or a task - /// that can't be cancelled is an error. + /// The tasks waiting in line, in the order they were asked for, each with its place in its lane. + pub fn waiting(&self) -> Vec { + let waiting = lock(&self.inner.waiting); + let mut ahead: Vec<(Lane, usize)> = Vec::new(); + waiting + .iter() + .map(|w| { + let place = match ahead.iter_mut().find(|(lane, _)| *lane == w.lane) { + Some((_, n)) => { + *n += 1; + *n + } + None => { + ahead.push((w.lane, 1)); + 1 + } + }; + w.info(place) + }) + .collect() + } + + /// Ask task `id` to stop (it stops at its next check), or take it out of the line if it waits. An unknown id + /// (the task may have just ended) or a task that can't be cancelled is an error. pub fn cancel(&self, id: u64) -> Result<(), String> { + { + let mut waiting = lock(&self.inner.waiting); + if let Some(at) = waiting.iter().position(|w| w.id == id) { + waiting.remove(at); + return Ok(()); + } + } let tasks = lock(&self.inner.tasks); let entry = tasks.iter().find(|e| e.id == id).ok_or_else(|| format!("no task {id}"))?; if entry.try_cancel() { Ok(()) } else { Err(format!("{} can't be cancelled", entry.label)) } } - /// Ask every cancellable task to stop; returns how many were asked. + /// Ask every cancellable task to stop, and empty the line (what waits would start as soon as they stopped); + /// returns how many were asked or taken out. pub fn cancel_all(&self) -> usize { + let dropped = std::mem::take(&mut *lock(&self.inner.waiting)).len(); let tasks = lock(&self.inner.tasks); - tasks.iter().filter(|e| e.try_cancel()).count() + dropped + tasks.iter().filter(|e| e.try_cancel()).count() } /// Tasks that quitting would cut short: cancellable ones not already stopping. pub fn running_cancellable(&self) -> Vec { lock(&self.inner.tasks).iter().filter(|e| e.is_cancellable() && !e.is_cancelled()).map(|e| e.info()).collect() } + + /// Put a task of `kind` in line behind the others of its lane; it runs `request` when its turn comes. Returns + /// its id and its place in the line. A kind without a lane, or a line already [`MAX_WAITING`] long, is an error. + pub fn enqueue(&self, kind: &'static str, label: &str, request: Request) -> Result<(u64, usize), String> { + let lane = Lane::of(kind).ok_or_else(|| format!("{kind} tasks don't wait in line"))?; + let mut waiting = lock(&self.inner.waiting); + if waiting.len() >= MAX_WAITING { + return Err(format!("{MAX_WAITING} tasks are waiting already")); + } + let id = self.inner.next.fetch_add(1, Ordering::Relaxed).saturating_add(1); + waiting.push(Waiting { id, kind, label: capped(label), lane, request, queued: web_time::Instant::now() }); + let place = waiting.iter().filter(|w| w.lane == lane).count(); + Ok((id, place)) + } + + /// Whether a task of `lane` runs now. + pub fn lane_busy(&self, lane: Lane) -> bool { + lock(&self.inner.tasks).iter().any(|e| Lane::of(e.kind) == Some(lane)) + } + + /// Whether a task waits in `lane`'s line. + pub fn lane_waiting(&self, lane: Lane) -> bool { + lock(&self.inner.waiting).iter().any(|w| w.lane == lane) + } + + /// Take the first waiting task whose lane is free out of the line, to be started now. The next task of its + /// kind started ([`Activity::start`]) keeps its id, until [`Activity::started`] says the attempt is over. + pub fn take_ready(&self) -> Option { + self.take_ready_if(|_| true) + } + + /// [`Activity::take_ready`] among the tasks whose request `runs` can run: each frontend starts what it knows how to + /// (the engine its commands, the app its own). Only the first in each lane's line is looked at: one the caller + /// can't run holds its lane, as it would if it had started. + pub fn take_ready_if(&self, runs: impl Fn(&Request) -> bool) -> Option { + let mut waiting = lock(&self.inner.waiting); + let mut held: Vec = lock(&self.inner.tasks).iter().filter_map(|e| Lane::of(e.kind)).collect(); + let mut at = None; + for (i, w) in waiting.iter().enumerate() { + if held.contains(&w.lane) { + continue; + } + if runs(&w.request) { + at = Some(i); + break; + } + held.push(w.lane); + } + let w = waiting.remove(at?); + *lock(&self.inner.reserved) = Some((w.kind, w.id)); + Some(w) + } + + /// The attempt to start the task [`Activity::take_ready`] handed over is over (it started, or it could not). + pub fn started(&self) { + *lock(&self.inner.reserved) = None; + } + + /// Another library was opened: what waited in line was about the old one's photos and folders, so the line + /// empties. Returns how many tasks waited. + pub fn library_changed(&self) -> usize { + std::mem::take(&mut *lock(&self.inner.waiting)).len() + } +} + +/// Milliseconds, saturating. +fn millis(d: std::time::Duration) -> u64 { + u64::try_from(d.as_millis()).unwrap_or(u64::MAX) } /// A task's place in the list, held by whoever owns the job; dropping it removes the row. @@ -435,4 +616,93 @@ mod tests { std::thread::spawn(move || h.progress(3, 7)).join().unwrap(); assert_eq!((a.list()[0].done, a.list()[0].total), (3, 7)); } + + fn request(command: &str) -> Request { + Request { command: command.into(), params: serde_json::json!({}) } + } + + #[test] + fn a_task_of_a_kind_without_a_lane_does_not_wait() { + let a = Activity::default(); + let e = a.enqueue("export", "Exporting", request("x")).unwrap_err(); + assert!(e.contains("export"), "{e}"); + assert!(a.list().is_empty()); + } + + #[test] + fn the_line_is_bounded_and_lists_places_per_lane() { + let a = Activity::default(); + for place in 1..=MAX_WAITING { + assert_eq!(a.enqueue("previews", "P", request("x")).unwrap().1, place); + } + assert!(a.enqueue("smartPreviews", "S", request("x")).unwrap_err().contains("100")); + let rows = a.list(); + assert_eq!(rows.len(), MAX_WAITING); + assert!(rows.iter().all(|r| r.waiting && r.lane == Some(Lane::Previews))); + assert_eq!(rows.iter().map(|r| r.place).collect::>(), (1..=MAX_WAITING).collect::>()); + } + + #[test] + fn a_waiting_task_starts_when_its_lane_is_free_and_keeps_its_id() { + let a = Activity::default(); + let ahead = a.start("previews", "P", Cancel::Yes); + let (id, _) = a.enqueue("smartPreviews", "S", request("smart")).unwrap(); + assert!(a.lane_busy(Lane::Previews) && a.lane_waiting(Lane::Previews)); + assert!(a.take_ready().is_none(), "the lane is busy: one preview build at a time"); + drop(ahead); + assert!(!a.lane_busy(Lane::Previews)); + let w = a.take_ready().expect("the lane is free"); + assert_eq!((w.id, w.request.command.as_str()), (id, "smart")); + assert!(!a.lane_waiting(Lane::Previews)); + let g = a.start("smartPreviews", "S", Cancel::Yes); + a.started(); + assert_eq!(g.id(), id, "it keeps the id it had in line"); + assert!(!a.list()[0].waiting); + assert_ne!(a.start("export", "E", Cancel::Yes).id(), id); + } + + #[test] + fn an_attempt_that_did_not_start_a_task_gives_its_id_up() { + let a = Activity::default(); + let (id, _) = a.enqueue("previews", "P", request("x")).unwrap(); + let w = a.take_ready().unwrap(); + assert_eq!(w.id, id); + a.started(); // the command failed before starting anything + assert_ne!(a.start("previews", "P", Cancel::Yes).id(), id, "a later task of the kind doesn't take it"); + } + + #[test] + fn take_ready_if_skips_what_the_caller_cannot_run_but_keeps_its_lane_held() { + let a = Activity::default(); + a.enqueue("previews", "mine", request("engine")).unwrap(); + a.enqueue("previews", "next", request("engine")).unwrap(); + assert!(a.take_ready_if(|r| r.command == "other").is_none(), "the first in the lane isn't ours: it holds the lane"); + assert_eq!(a.take_ready_if(|_| true).map(|w| w.label), Some("mine".to_string())); + } + + #[test] + fn cancelling_a_waiting_task_removes_it_and_cancel_all_empties_the_line() { + let a = Activity::default(); + let _running = a.start("previews", "P", Cancel::Yes); + let (first, _) = a.enqueue("previews", "A", request("x")).unwrap(); + a.enqueue("previews", "B", request("x")).unwrap(); + a.enqueue("smartPreviews", "C", request("x")).unwrap(); + a.cancel(first).unwrap(); + assert!(a.cancel(first).is_err()); + assert_eq!(a.waiting().iter().map(|t| (t.label.as_str(), t.place)).collect::>(), vec![("B", 1), ("C", 2)]); + assert_eq!(a.cancel_all(), 3, "the running one and the two that waited"); + assert!(a.waiting().is_empty() && !a.lane_waiting(Lane::Previews)); + } + + #[test] + fn a_library_change_empties_the_line() { + let a = Activity::default(); + let running = a.start("previews", "P", Cancel::Yes); + a.enqueue("previews", "A", request("x")).unwrap(); + a.enqueue("smartPreviews", "B", request("x")).unwrap(); + assert_eq!(a.library_changed(), 2); + assert_eq!(a.list().len(), 1, "what runs goes on"); + drop(running); + assert!(a.take_ready().is_none()); + } } diff --git a/crates/engine/src/cmd/activity.rs b/crates/engine/src/cmd/activity.rs index ed4e8d35c7..3fa99b488a 100644 --- a/crates/engine/src/cmd/activity.rs +++ b/crates/engine/src/cmd/activity.rs @@ -11,7 +11,7 @@ pub fn specs() -> Vec { "Background Tasks", [], None, - "{} → {tasks: [{id, kind, label, done, total, unit: count|bytes|percent, detail, cancellable, cancelling, ageMs}]} — the long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first; total 0 = not known yet", + "{} → {tasks: [{id, kind, label, done, total, unit: count|bytes|percent, detail, cancellable, cancelling, ageMs, waiting, place, lane}]} — the long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first, then those waiting in line for a task of their lane (waiting: true, place: 1 = next in its lane, lane: previews; done and total 0); total 0 = not known yet", always, |s, _| Ok(json!({"tasks": s.activity.list()})) ), @@ -20,7 +20,7 @@ pub fn specs() -> Vec { "Cancel Background Task", [], None, - "{id} | {all: true} → {cancelled: n} — ask a task (or every cancellable task) to stop; it stops at its next file or photo (a preview build also stops between a photo's own previews). An unknown id (it may have just finished) or a task that can't be cancelled is an error", + "{id} | {all: true} → {cancelled: n} — ask a task (or every cancellable task) to stop; it stops at its next file or photo (a preview build also stops between a photo's own previews). A task waiting in line is taken out of it and never runs; all also empties the line. An unknown id (it may have just finished) or a task that can't be cancelled is an error", always, |s, p| { const C: &str = "activity.cancel"; diff --git a/crates/engine/src/cmd/previews.rs b/crates/engine/src/cmd/previews.rs index 0d506b5adf..1d2a54e8bf 100644 --- a/crates/engine/src/cmd/previews.rs +++ b/crates/engine/src/cmd/previews.rs @@ -9,7 +9,7 @@ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use serde_json::{Value, json}; use super::{CommandSpec, always, bad, cmd, str_param}; -use crate::activity::{Cancel, TaskGuard}; +use crate::activity::{Cancel, Lane, Request, TaskGuard}; use crate::media::{RenderJob, THUMB_SIZES}; use crate::{Result, Session}; @@ -194,19 +194,80 @@ impl Drop for Building { } } -/// The build's row in the activity stack (`what` as in [`PreviewBuild::what`]). -fn task_for(s: &Session, state: &PreviewBuild) -> TaskGuard { - let (kind, label) = match state.what { - "" if state.background => ("previews", "Preparing photos in the background"), +/// The row in the activity stack of a build of `what` (as in [`PreviewBuild::what`]), `background`: the background +/// preparation's build ([`PreviewBuild::background`]): its kind and its label. +fn row_of(what: &str, background: bool) -> (&'static str, &'static str) { + match what { + "" if background => ("previews", "Preparing photos in the background"), "" => ("previews", "Building previews"), "smart previews" => ("smartPreviews", "Building smart previews"), _ => ("smartPreviews", "Discarding smart previews"), - }; + } +} + +/// The build's row in the activity stack. +fn task_for(s: &Session, state: &PreviewBuild) -> TaskGuard { + let (kind, label) = row_of(state.what, state.background); let task = s.activity.start(kind, label, Cancel::Flag(state.cancel.clone())); task.progress(0, state.total as u64); task } +/// A build's state and its row, which go together. However the build ends (it finishes, its worker panics, or the +/// worker can't be started) the state reads as finished first, and then the row goes: a build waiting in line starts +/// when the row is gone, and is refused if the state still said a build runs. A build that did not mark itself +/// finished did not end well: it says so, instead of reading as one that built nothing. +/// (A build asked for with `row: false` has no row: the job that asked shows it.) +struct Running { + state: Arc, + task: Option, +} + +impl Drop for Running { + fn drop(&mut self) { + if !self.state.finished.load(Ordering::Relaxed) { + self.state + .error + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .get_or_insert_with(|| "the build stopped unexpectedly".to_string()); + } + self.state.finished.store(true, Ordering::Relaxed); + } +} + +/// What a build of `ids` was asked, as it runs later (from the line): the photos written out (the selection or the +/// view may have changed by then), in the background (nothing waits for it then), and not queued again. +fn request_for(command: &str, p: &Value, ids: &[lightcraft_catalog::PhotoId]) -> Request { + let mut params = p.as_object().cloned().unwrap_or_default(); + for key in ["id", "queue", "wait"] { + params.remove(key); + } + params.insert("ids".into(), ids.iter().map(|id| id.0).collect()); + Request { command: command.into(), params: Value::Object(params) } +} + +/// The refusal of a build while another runs, unless the call asks to `queue`. +const REFUSED: &str = "a preview build is already running"; + +fn queue_param(p: &Value) -> bool { + p.get("queue").and_then(Value::as_bool).unwrap_or(false) +} + +/// A build asked for with `queue`: while one runs (`busy`: one that does not give way to this one) or others already +/// wait, this one waits in line behind them → `{queued: id, place}`. `None`: nothing is ahead of it, so it starts now. +fn wait_in_line(s: &Session, c: &str, p: &Value, what: &str, busy: bool, request: &Request) -> Option> { + if !busy && !s.activity.lane_waiting(Lane::Previews) { + return None; + } + if p.get("wait").and_then(Value::as_bool) == Some(true) { + return Some(Err(bad(c, "a build that waits in line can't also be waited for: leave out wait"))); + } + let background = p.get("background").and_then(Value::as_bool).unwrap_or(false); + let (kind, label) = row_of(what, background); + Some(s.activity.enqueue(kind, label, request.clone()).map(|(id, place)| json!({"queued": id, "place": place})).map_err(|e| bad(c, e))) +} + /// Render one photo's jobs in order. The source the first job decodes serves the ones after it /// (the grid thumbnail is made from the view's source instead of decoding the file again). /// `None` when `cancel` was asked for before a job started: that photo is not counted as done. @@ -494,18 +555,24 @@ fn build(s: &mut Session, p: &Value) -> Result { let force = p.get("force").and_then(Value::as_bool).unwrap_or(false); // (`row: false`: the job that asked shows the progress in its own row) let row = p.get("row").and_then(Value::as_bool).unwrap_or(true); + let queue = queue_param(p); // the background preparation gives way to a build that was asked for; nothing replaces a build // that was asked for (it carries on, and the photos it built are skipped by the next). The // background one is stopped only once this request is known to be good (below): a request // with bad ids leaves it running (CodeRabbit on #3544) let mut gives_way = None; + // (a build that runs and does not give way: this one is refused, or waits in line) + let mut busy = false; if let Some(b) = s.preview_build.as_ref().filter(|b| b.running()) { if b.background && !background { gives_way = Some(b.cancel.clone()); } else { - return Err(bad(C, "a preview build is already running")); + busy = true; } } + if !queue && busy { + return Err(bad(C, REFUSED)); + } s.fit_disk_cache(); // explicit ids, else the selected photos (more than one: as the menu says), else everything in // view (a single photo selected is the one open, not a choice of photos: "Visible" in the menu) @@ -514,6 +581,9 @@ fn build(s: &mut Session, p: &Value) -> Result { } else { s.visible_cloned() }; + if queue && let Some(queued) = wait_in_line(s, C, p, "", busy, &request_for(C, p, &ids)) { + return queued; + } let jobs: Vec = ids.iter().map(|id| (id.0, jobs_for(s, *id, edge))).filter(|j| !j.1.is_empty()).collect(); // the background build stays the session's until this one has started (a worker that can't // start leaves it running and in place: CodeRabbit on #3544) @@ -530,7 +600,7 @@ fn build(s: &mut Session, p: &Value) -> Result { state.focus_on(lightcraft_catalog::PhotoId(at), p.get("backward").and_then(Value::as_bool).unwrap_or(false)); } s.preview_build = Some(state.clone()); - let task = row.then(|| task_for(s, &state)); + let run = Running { task: row.then(|| task_for(s, &state)), state: state.clone() }; // the background preparation leaves most of the machine to the photo on screen and the user let lanes = if background { crate::prep::background_lanes() } else { lanes(jobs.len(), edge.is_none()) }; let wait = p.get("wait").and_then(Value::as_bool).unwrap_or(false) || cfg!(target_arch = "wasm32"); @@ -538,22 +608,22 @@ fn build(s: &mut Session, p: &Value) -> Result { if let Some(cancel) = gives_way { cancel.store(true, Ordering::Relaxed); } - run_all(jobs, &state, task.as_ref(), lanes, force); + run_all(jobs, &run.state, run.task.as_ref(), lanes, force); return Ok(state.json()); } #[cfg(not(target_arch = "wasm32"))] { // the row stays while the worker runs (it is dropped with the closure, however that ends) - let st = state.clone(); #[cfg(test)] let started = if test_gate::take_fail_spawn() { - drop(task); + drop(run); Err(std::io::Error::other("no thread (test)")) } else { - std::thread::Builder::new().name("lc-build-previews".into()).spawn(move || run_all(jobs, &st, task.as_ref(), lanes, force)) + std::thread::Builder::new().name("lc-build-previews".into()).spawn(move || run_all(jobs, &run.state, run.task.as_ref(), lanes, force)) }; #[cfg(not(test))] - let started = std::thread::Builder::new().name("lc-build-previews".into()).spawn(move || run_all(jobs, &st, task.as_ref(), lanes, force)); + let started = + std::thread::Builder::new().name("lc-build-previews".into()).spawn(move || run_all(jobs, &run.state, run.task.as_ref(), lanes, force)); if let Err(e) = started { // never started: not left "running", which would hold every later build back, and the // build it was to replace carries on @@ -737,15 +807,24 @@ fn smart(s: &mut Session, p: &Value) -> Result { // (as Build Previews: the photos named, or the selected ones when more than one is, else // everything in view; read first, so a request with bad ids stops nothing: CodeRabbit on #3577) let ids = if p.get("ids").is_some() || p.get("id").is_some() || s.selection.ids.len() > 1 { s.targets(p)? } else { s.visible_cloned() }; + let queue = background && queue_param(p); // (the background preparation gives way, as to Build Previews: once this one's worker has started) let mut gives_way = None; + let mut busy = false; if background && let Some(b) = s.preview_build.as_ref().filter(|b| b.running()) { if b.background { gives_way = Some(b.cancel.clone()); } else { - return Err(bad(C, "a preview build is already running")); + busy = true; } } + if background && !queue && busy { + return Err(bad(C, REFUSED)); + } + let what = if discard { "discarding smart previews" } else { "smart previews" }; + if queue && let Some(queued) = wait_in_line(s, C, p, what, busy, &request_for(C, p, &ids)) { + return queued; + } let mut jobs: Vec = Vec::new(); for id in ids { let Some(ph) = s.catalog.photo(id).cloned() else { continue }; @@ -760,17 +839,16 @@ fn smart(s: &mut Session, p: &Value) -> Result { } let custom = s.smart_previews_dir.is_some(); if background { - let what = if discard { "discarding smart previews" } else { "smart previews" }; let state = Arc::new(PreviewBuild { total: jobs.len(), what, ..Default::default() }); let previous = s.preview_build.replace(state.clone()); - let task = task_for(s, &state); - let st = state.clone(); + // (this build always has its row) + let run = Running { task: Some(task_for(s, &state)), state: state.clone() }; let work = move || { - if let Err(e) = smart_run(&dir, custom, discard, jobs, Some((&st, &task))) { + if let Err(e) = smart_run(&dir, custom, discard, jobs, run.task.as_ref().map(|task| (&*run.state, task))) { log::warn!("{C}: {e}"); - *st.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(e); + *run.state.error.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(e); } - st.finished.store(true, Ordering::Relaxed); + run.state.finished.store(true, Ordering::Relaxed); }; #[cfg(test)] let started = if test_gate::take_fail_spawn() { @@ -929,7 +1007,7 @@ pub fn specs() -> Vec { "Build Smart Previews", [], None, - "{ids?, discard?: bool, background?: bool} — build (or discard) the smart previews of the selected photos (when more than one is selected; else all in view): compact proxies in the library that keep photos editable and exportable (at proxy size) while their originals are offline; a damaged proxy (cut short) is rebuilt → {built, repaired, removed, failed}; with background (the app's menu) the files are read and written on a worker thread → {total, done, failed, repaired, running, what} like library.buildPreviews (progress: library.previewProgress, stop: library.cancelPreviews)", + "{ids?, discard?: bool, background?: bool, queue?: bool} — build (or discard) the smart previews of the selected photos (when more than one is selected; else all in view): compact proxies in the library that keep photos editable and exportable (at proxy size) while their originals are offline; a damaged proxy (cut short) is rebuilt → {built, repaired, removed, failed}; with background (the app's menu) the files are read and written on a worker thread → {total, done, failed, repaired, running, what} like library.buildPreviews (progress: library.previewProgress, stop: library.cancelPreviews). A background one while a preview build runs is refused, or with queue waits in line for it, as library.buildPreviews does → {queued, place}", always, smart ), @@ -956,7 +1034,7 @@ pub fn specs() -> Vec { "Build Previews", [], None, - "{size?: standard (2048 px, or the loupe's size when bigger, or `edge`) | full (1:1), ids?, wait?: bool, force?: bool, from?: id, backward?: bool, background?: bool, row?: bool} — render the grid thumbnail and loupe view of the selected photos (when more than one is selected; else all in view) into the preview cache (memory and disk), in the background unless `wait`. Photos whose previews are there already (big enough) are skipped unless `force`; the photos nearest `from` go first. `background`: the background preparation's build (two lanes, waits while the photo on screen renders; a build asked for replaces it). `row: false`: no row of its own in the activity stack (the caller's row shows it) → {total, done, failed, skipped, shared, running}", + "{size?: standard (2048 px, or the loupe's size when bigger, or `edge`) | full (1:1), ids?, wait?: bool, force?: bool, from?: id, backward?: bool, background?: bool, row?: bool, queue?: bool} — render the grid thumbnail and loupe view of the selected photos (when more than one is selected; else all in view) into the preview cache (memory and disk), in the background unless `wait`. Photos whose previews are there already (big enough) are skipped unless `force`; the photos nearest `from` go first. `background`: the background preparation's build (two lanes, waits while the photo on screen renders; a build asked for replaces it). `row: false`: no row of its own in the activity stack (the caller's row shows it) → {total, done, failed, skipped, shared, running}. One build runs at a time (this, or Build / Discard Smart Previews in the background; the background preparation gives way to a build asked for): while one runs another is refused, or with queue waits in line for it and starts by itself when the builds ahead of it end → {queued: its activity id, place: 1 = next}. It builds the photos chosen when it was asked; activity.list shows it waiting, activity.cancel takes it out of the line. Not with wait while one runs", always, build ), @@ -1059,4 +1137,38 @@ mod tests { assert_eq!(r["total"], json!(ids.len())); assert_eq!(r["failed"], json!(0)); } + // Given a build whose worker dies (or can't start), the build reads as finished and its row goes, so that a + // build waiting in line starts instead of being refused as "already running" + #[test] + fn a_build_whose_worker_dies_reads_as_finished_before_its_row_goes() { + use std::sync::Arc; + use std::sync::atomic::Ordering; + + let s = Session::with_demo(); + let state = Arc::new(super::PreviewBuild::default()); + let run = super::Running { task: Some(super::task_for(&s, &state)), state: state.clone() }; + assert!(s.activity.lane_busy(crate::activity::Lane::Previews)); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { + let _run = run; + panic!("synthetic worker panic"); + })); + assert!(r.is_err()); + assert!(state.finished.load(Ordering::Relaxed)); + assert_eq!(state.error().as_deref(), Some("the build stopped unexpectedly"), "a crash is not a success that built nothing"); + assert!(!s.activity.lane_busy(crate::activity::Lane::Previews)); + } + + // Given a build that marked itself finished, its row going leaves no error + #[test] + fn a_build_that_finished_leaves_no_error() { + use std::sync::Arc; + use std::sync::atomic::Ordering; + + let s = Session::with_demo(); + let state = Arc::new(super::PreviewBuild::default()); + let run = super::Running { task: Some(super::task_for(&s, &state)), state: state.clone() }; + state.finished.store(true, Ordering::Relaxed); + drop(run); + assert!(state.error().is_none()); + } } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index b0e3d2b9e5..1094caa34c 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -330,6 +330,8 @@ pub struct Session { /// Current time provider (ISO 8601); injectable for tests and wasm. pub clock: Box String + Send>, depth: u32, + /// [`Session::start_waiting`] is starting tasks (the commands it runs don't start more themselves). + starting_waiting: bool, /// Selected mask (Masking panel), by mask id. pub active_mask: Option, /// AI masks (SAM 3): the model and the last photo prepared for it. @@ -517,6 +519,7 @@ impl Session { media: media::MediaCache::default(), clock: Box::new(|| "2026-09-30T12:00:00".to_string()), depth: 0, + starting_waiting: false, active_mask: None, segmenter: segment::Segmenter::default(), active_spot: None, @@ -581,6 +584,15 @@ impl Session { /// Run a command by id. THE entry point for every frontend. pub fn execute(&mut self, id: &str, params: &Value) -> Result { + let r = self.dispatch(id, params, true); + // a task this command freed the lane of starts now, not at the next frame + self.start_waiting(); + r + } + + /// [`Session::execute`] without starting waiting tasks; `journal`: record the call when the command is journaled + /// (not for a task that waited: the call that asked for it is recorded already). + fn dispatch(&mut self, id: &str, params: &Value, journal: bool) -> Result { let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?; // a command that validates the photos a call names isn't held back by the selection if !(spec.explicit_targets && cmd::names_photos(params)) { @@ -588,13 +600,33 @@ impl Session { } let empty = Value::Object(Default::default()); let params = if params.is_null() { &empty } else { params }; - self.run_command(id, spec.journal.then_some(params), |s| (spec.run)(s, params)).map_err(|e| match e { + self.run_command(id, (journal && spec.journal).then_some(params), |s| (spec.run)(s, params)).map_err(|e| match e { // a shared parameter check ([`Session::targets`]) names the command it ran for EngineError::BadParams { cmd, msg } if cmd.is_empty() => EngineError::BadParams { cmd: id.to_string(), msg }, e => e, }) } + /// Start the tasks waiting in line whose lane is free ([`crate::activity`]), each by running the command it was + /// asked with. One that can't start is logged and the next in line goes on. Every frontend gets this after each + /// command; the app also calls it every frame, for a lane that frees while nothing is asked. + pub fn start_waiting(&mut self) { + if self.depth > 0 || self.starting_waiting { + return; + } + self.starting_waiting = true; + // (bounded: each turn takes one task out of a line that is at most this long) + for _ in 0..activity::MAX_WAITING { + let Some(w) = self.activity.take_ready() else { break }; + let r = self.dispatch(&w.request.command, &w.request.params, false); + self.activity.started(); + if let Err(e) = r { + log::warn!("{}: a task that waited could not start: {e}", w.request.command); + } + } + self.starting_waiting = false; + } + /// Run `f` as command `id` with what [`Session::execute`] does around every command: the /// panic guard, auto versions, XMP sidecar auto-write and the durable save (a failed save is /// `NotSaved`). Not journaled. The app's import task commits its batches this way. diff --git a/crates/engine/src/library.rs b/crates/engine/src/library.rs index 8cd242face..c25d16eda4 100644 --- a/crates/engine/src/library.rs +++ b/crates/engine/src/library.rs @@ -557,6 +557,11 @@ impl Session { static LOADS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); catalog.revision = LOADS.fetch_add(1, std::sync::atomic::Ordering::Relaxed).wrapping_add(1) << 32; self.catalog = catalog; + // nor do tasks waiting in line carry over: they name the old library's photos and folders + let dropped = self.activity.library_changed(); + if dropped > 0 { + log::info!("library: {dropped} task(s) waiting in line were dropped with the old library"); + } // (nothing of the list the last library showed is this one's) self.refresh_view(); self.library_generation = crate::LIBRARY_GEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 03592df41b..93de56b349 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -57,6 +57,7 @@ mod slideshow_export; mod slow_drive; mod spots; mod sync; +mod task_queue; mod view_follow; pub(super) mod xmp; diff --git a/crates/engine/src/tests/task_queue.rs b/crates/engine/src/tests/task_queue.rs new file mode 100644 index 0000000000..1eade86344 --- /dev/null +++ b/crates/engine/src/tests/task_queue.rs @@ -0,0 +1,249 @@ +//! Tasks waiting in line for their lane (see `crate::activity`), with the preview builds. +//! +//! Scenarios, in the words of an agent building previews for several shoots: +//! +//! * Build Previews while a build runs: without `queue` it is refused, as it always was. With `queue` it waits +//! behind the build, `activity.list` says it is next, and it builds the photos chosen when it was asked. +//! * It starts by itself when the build ahead of it ends. +//! * `activity.cancel` on it takes it out of the line: it never runs; `all` empties the line. +//! * The line is bounded. +//! * Another library: nothing waits for it. +//! +//! These go through commands and `activity.list` only, so that they describe what a control or MCP client sees. + +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::Ordering; + +use serde_json::{Value, json}; + +use crate::Session; +use crate::activity::{Cancel, MAX_WAITING, TaskGuard}; +use crate::cmd::previews::PreviewBuild; + +fn temp_dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("lc-task-queue-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d +} + +/// A preview build that holds the lane until [`release`]: its row runs, and the build reads as unfinished. +struct Hold { + _row: TaskGuard, + build: Arc, +} + +fn hold(s: &mut Session) -> Hold { + let build = Arc::new(PreviewBuild::default()); + s.preview_build = Some(build.clone()); + Hold { _row: s.activity.start("previews", "Building previews", Cancel::Yes), build } +} + +/// The held build ends as a real one does: finished first, then its row goes. +fn release(h: Hold) { + h.build.finished.store(true, Ordering::Release); + drop(h); +} + +/// Wait (at most a minute) until no task runs or waits. +fn settle(s: &mut Session) { + let t0 = std::time::Instant::now(); + loop { + // any command lets a waiting task whose lane is free start (the app's frame loop does too) + let rows = tasks(s); + if rows.is_empty() { + return; + } + assert!(t0.elapsed().as_secs() < 60, "tasks still listed: {rows:?}"); + std::thread::sleep(std::time::Duration::from_millis(10)); + } +} + +fn tasks(s: &mut Session) -> Vec { + s.execute("activity.list", &json!({})).unwrap()["tasks"].as_array().cloned().unwrap_or_default() +} + +fn build_ids(s: &Session, n: usize) -> Vec { + s.catalog.photos().take(n).map(|p| p.id.0).collect() +} + +/// Given a preview build running and two photos chosen, when Build Previews is asked for with `queue`, then it waits +/// behind the build, first in line, with nothing done. When other photos are chosen meanwhile and the build ahead +/// ends, then it starts by itself and builds the two photos chosen when it was asked. +#[test] +fn a_build_asked_for_while_one_runs_waits_behind_it_and_builds_the_photos_chosen_then() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 3); + s.execute("library.select", &json!({"ids": [ids[0], ids[1]]})).unwrap(); + let h = hold(&mut s); + let r = s.execute("library.buildPreviews", &json!({"edge": 256, "queue": true})).unwrap(); + let id = r["queued"].as_u64().expect("an id while it waits"); + assert_eq!(r["place"], 1); + let rows = tasks(&mut s); + assert_eq!(rows.len(), 2, "the running build, then the waiting one: {rows:?}"); + assert_eq!(rows[1]["id"], id); + assert_eq!((rows[1]["waiting"].as_bool(), rows[1]["place"].as_u64(), rows[1]["lane"].as_str()), (Some(true), Some(1), Some("previews"))); + assert_eq!((rows[1]["done"].as_u64(), rows[1]["total"].as_u64()), (Some(0), Some(0))); + assert_eq!(rows[1]["label"], "Building previews"); + assert_eq!((rows[0]["waiting"].as_bool(), rows[0]["place"].as_u64()), (Some(false), Some(0)), "the running one is not in line"); + s.execute("library.select", &json!({"ids": [ids[2]]})).unwrap(); + release(h); + settle(&mut s); + let progress = s.execute("library.previewProgress", &json!({})).unwrap(); + assert_eq!((progress["total"].as_u64(), progress["done"].as_u64()), (Some(2), Some(2)), "{progress}"); + // the journal has the call that asked for it, once: starting it was not a second call + assert_eq!(s.journal.iter().filter(|(c, _)| c == "library.buildPreviews").count(), 1, "{:?}", s.journal); +} + +/// Given a preview build running, when a build is asked for without `queue`, then it is refused as before, and +/// nothing waits. +#[test] +fn a_build_asked_for_while_one_runs_is_refused_unless_it_asks_to_queue() { + let mut s = Session::with_demo(); + let h = hold(&mut s); + let e = s.execute("library.buildPreviews", &json!({"edge": 256})).unwrap_err().to_string(); + assert!(e.contains("a preview build is already running"), "{e}"); + let e = s.execute("library.buildPreviews", &json!({"edge": 256, "queue": false})).unwrap_err().to_string(); + assert!(e.contains("a preview build is already running"), "{e}"); + assert_eq!(tasks(&mut s).len(), 1, "only the running build is listed"); + release(h); + assert!(tasks(&mut s).is_empty()); +} + +/// Given no build running, when a build is asked for with `queue`, then it starts at once, as one without it does. +#[test] +fn a_build_that_asks_to_queue_starts_at_once_when_nothing_is_ahead_of_it() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 2); + let r = s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true, "wait": true})).unwrap(); + assert!(r.get("queued").is_none(), "{r}"); + assert_eq!((r["total"].as_u64(), r["done"].as_u64()), (Some(2), Some(2)), "{r}"); +} + +/// Given a build waiting behind another, when `activity.cancel` is asked for it, then it leaves the line and never +/// runs. +#[test] +fn a_waiting_build_taken_out_of_the_line_never_runs() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + let held = h.build.clone(); + let id = s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap()["queued"].as_u64().unwrap(); + assert_eq!(s.execute("activity.cancel", &json!({"id": id})).unwrap()["cancelled"], 1); + assert_eq!(tasks(&mut s).len(), 1, "only the running build is left"); + assert!(s.execute("activity.cancel", &json!({"id": id})).is_err(), "it is gone: an unknown id"); + release(h); + settle(&mut s); + assert!(s.preview_build.as_ref().is_some_and(|b| Arc::ptr_eq(b, &held)), "no build started after the held one"); +} + +/// Given builds waiting, when every task is cancelled, then the line is empty and the count includes the waiting ones, +/// so that nothing starts as soon as the running build stops. +#[test] +fn cancelling_every_task_empties_the_line() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + let held = h.build.clone(); + for _ in 0..2 { + s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + } + assert_eq!(tasks(&mut s).len(), 3); + assert_eq!(s.execute("activity.cancel", &json!({"all": true})).unwrap()["cancelled"], 3, "the running one and the two waiting"); + assert_eq!(tasks(&mut s).len(), 1, "only the running (stopping) build is listed"); + release(h); + settle(&mut s); + assert!(s.preview_build.as_ref().is_some_and(|b| Arc::ptr_eq(b, &held)), "nothing started after it"); +} + +/// Given a full line, when one more build is asked for, then it is refused and says why; the line is as it was. +#[test] +fn the_line_is_bounded() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + for place in 1..=MAX_WAITING { + let r = s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + assert_eq!(r["place"].as_u64(), Some(place as u64)); + } + let e = s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap_err().to_string(); + assert!(e.contains(&MAX_WAITING.to_string()), "{e}"); + assert_eq!(tasks(&mut s).len(), MAX_WAITING + 1); + s.execute("activity.cancel", &json!({"all": true})).unwrap(); + release(h); +} + +/// Build Smart Previews in the background waits in the same line (one preview build at a time). +#[test] +fn smart_previews_wait_behind_a_preview_build() { + let dir = temp_dir("smart"); + let mut s = Session::new(); + s.open_library(&dir, true).unwrap(); + let ids = build_ids(&s, 2); + let h = hold(&mut s); + let e = s.execute("library.smartPreviews", &json!({"ids": ids, "background": true})).unwrap_err().to_string(); + assert!(e.contains("already running"), "{e}"); + let r = s.execute("library.smartPreviews", &json!({"ids": ids, "background": true, "queue": true})).unwrap(); + assert!(r["queued"].is_u64(), "{r}"); + let rows = tasks(&mut s); + assert_eq!( + (rows[1]["kind"].as_str(), rows[1]["waiting"].as_bool(), rows[1]["lane"].as_str()), + (Some("smartPreviews"), Some(true), Some("previews")) + ); + release(h); + settle(&mut s); + let progress = s.execute("library.previewProgress", &json!({})).unwrap(); + // (the demo photos aren't files, so it has nothing to build: that it ran at all is what counts) + assert_eq!(progress["what"], "smart previews", "{progress}"); + assert_eq!(progress["running"], false, "{progress}"); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Two builds waiting, the first of which can't start (here: it was asked for a size no build accepts, as if what it +/// needs went away while it waited): the second still runs. +#[test] +fn a_build_that_can_not_start_does_not_hold_up_the_line() { + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + let bad = crate::activity::Request { command: "library.buildPreviews".into(), params: json!({"size": "huge"}) }; + s.activity.enqueue("previews", "Building previews", bad).unwrap(); + s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + release(h); + settle(&mut s); + let progress = s.execute("library.previewProgress", &json!({})).unwrap(); + assert_eq!((progress["total"].as_u64(), progress["done"].as_u64()), (Some(1), Some(1)), "{progress}"); +} + +/// `queue` with `wait` while a build runs: the call can't both wait in line and return when the build is done. +#[test] +fn a_build_that_would_wait_for_its_turn_and_its_end_is_refused() { + let mut s = Session::with_demo(); + let h = hold(&mut s); + let e = s.execute("library.buildPreviews", &json!({"edge": 256, "queue": true, "wait": true})).unwrap_err().to_string(); + assert!(e.contains("wait"), "{e}"); + assert_eq!(tasks(&mut s).len(), 1); + release(h); +} + +/// Given a build waiting and one still running, when another library is opened, then nothing waits any more: the +/// build asked for was about the old library's photos. +#[test] +fn another_library_drops_what_waits() { + let dir = temp_dir("switch"); + let mut s = Session::with_demo(); + let ids = build_ids(&s, 1); + let h = hold(&mut s); + s.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + assert_eq!(tasks(&mut s).len(), 2); + s.open_library(&dir, false).unwrap(); + let rows = tasks(&mut s); + assert_eq!(rows.len(), 1, "only the old library's running build: {rows:?}"); + assert_eq!(rows[0]["waiting"], false); + release(h); + settle(&mut s); + s.close_library().unwrap(); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/ui-egui/src/app/frame.rs b/crates/ui-egui/src/app/frame.rs index 798101a7ef..17a022484c 100644 --- a/crates/ui-egui/src/app/frame.rs +++ b/crates/ui-egui/src/app/frame.rs @@ -75,6 +75,8 @@ impl LightcraftApp { crate::lens_db::tick(self); updates_ui::tick(self, ctx); self.preview_build_status(ctx); + // a task waiting in line whose lane freed while nothing was asked starts now (commands start them too) + self.session.start_waiting(); self.save_status(ctx); self.ai_mask_detail(ctx, now); self.place_names_outcome(ctx); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 63403650b2..2032fd6f94 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -158,7 +158,7 @@ pub fn inspect(app: &LightcraftApp, ctx: &egui::Context) -> Value { "export": {"running": app.export.as_ref().map(crate::export_task::ExportTask::status), "last": app.last_export_result}, "import": app.import.as_ref().map(crate::import::ImportTask::status), "tasks": app.tasks.labels(), - // every long-running task in flight, as the activity stack shows them (`activity.list`) + // every long-running task in flight and every task waiting in line (`activity.list`); the stack draws the running ones "activity": app.session.activity.list(), // commands waiting on a native file dialog shown off the UI thread (`pick`) "fileDialogs": app.pending_picks.iter().map(|p| p.command.clone()).collect::>(), diff --git a/crates/ui-egui/src/panels/activity.rs b/crates/ui-egui/src/panels/activity.rs index dffdd1c4d3..0aadc19834 100644 --- a/crates/ui-egui/src/panels/activity.rs +++ b/crates/ui-egui/src/panels/activity.rs @@ -55,7 +55,8 @@ fn detail_line(t: &TaskInfo) -> String { /// Draw the stack (called every frame, after the panels and dialogs). pub fn show(app: &mut LightcraftApp, ctx: &egui::Context) { - let all = app.session.activity.list(); + // (a task waiting in line has nothing to show yet and no progress to draw: agents see it in `activity.list`) + let all: Vec = app.session.activity.list().into_iter().filter(|t| !t.waiting).collect(); if all.is_empty() { app.activity_expanded = false; return; diff --git a/crates/ui-egui/src/tests/activity.rs b/crates/ui-egui/src/tests/activity.rs index b353405ffc..e827fafce1 100644 --- a/crates/ui-egui/src/tests/activity.rs +++ b/crates/ui-egui/src/tests/activity.rs @@ -110,6 +110,9 @@ fn count_text_by_unit() { cancellable: true, cancelling: false, age_ms: 600, + waiting: false, + place: 0, + lane: None, }; assert_eq!(count_text(&t), "3 of 25"); (t.done, t.total, t.unit) = (12 * 1_048_576, 340 * 1_048_576, Unit::Bytes); @@ -591,3 +594,35 @@ 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()); } + +/// Given a preview build running and another waiting in line behind it, then the stack shows the running build only, +/// and the waiting one starts by itself, in a frame, when the build ahead of it ends. +#[test] +fn a_task_waiting_in_line_has_no_row_and_starts_when_the_lane_frees() { + use lightcraft_engine::cmd::previews::PreviewBuild; + use std::sync::atomic::Ordering; + + let mut h = demo(); + let build = std::sync::Arc::new(PreviewBuild::default()); + h.app.session.preview_build = Some(build.clone()); + let running = h.app.session.activity.start("previews", "Building previews", Cancel::Yes); + let ids: Vec = h.app.session.catalog.photos().take(1).map(|p| p.id.0).collect(); + let queued = h.app.session.execute("library.buildPreviews", &json!({"ids": ids, "edge": 256, "queue": true})).unwrap(); + let waiting = queued["queued"].as_u64().expect("it waits"); + assert_eq!(h.app.session.activity.list().len(), 2); + wait_visible(&mut h); + assert!(has(&h, &format!("activity:row:{}", running.id()))); + assert!(!has(&h, &format!("activity:row:{waiting}")) && rows(&h) == 1, "a waiting task draws no row"); + // the lane frees with no command asked: the frame loop starts it + build.finished.store(true, Ordering::Release); + drop(running); + let t0 = std::time::Instant::now(); + while h.app.session.activity.list().iter().any(|t| t.id == waiting && t.label == "Building previews") && t0.elapsed() < T { + h.step(); + let started = h.app.session.preview_build.as_ref().is_some_and(|b| !std::sync::Arc::ptr_eq(b, &build)); + if started { + break; + } + } + assert!(h.app.session.preview_build.as_ref().is_some_and(|b| !std::sync::Arc::ptr_eq(b, &build)), "the waiting build started"); +} diff --git a/crates/ui-egui/src/tests/progress.rs b/crates/ui-egui/src/tests/progress.rs index 09e9234a0c..b0c9f6f7d4 100644 --- a/crates/ui-egui/src/tests/progress.rs +++ b/crates/ui-egui/src/tests/progress.rs @@ -276,6 +276,9 @@ fn an_activity_bar_is_named_after_its_task() { cancellable: true, cancelling: false, age_ms: 600, + waiting: false, + place: 0, + lane: None, }; let (nodes, _, _) = frames(Vec::new(), |ui| crate::panels::activity::bar(ui, &task, 200.0).rect.width()); let bar = nodes.iter().find(|n| n.role == "ProgressIndicator").unwrap_or_else(|| panic!("{nodes:?}")); diff --git a/docs/background-tasks.md b/docs/background-tasks.md index 6f2b003477..650a94063f 100644 --- a/docs/background-tasks.md +++ b/docs/background-tasks.md @@ -49,6 +49,18 @@ guard.detail(&file_name); - **Quiet periodic work** shows no row: the auto-import folder listing runs every few seconds through `tasks::spawn(.., None, ..)`. +## Waiting in line + +Jobs that must not run side by side share a lane (`activity::Lane`; for now only the preview builds: Build Previews and +the background Build / Discard Smart Previews). A call that sets `queue: true` while its lane is busy does not fail: +`Activity::enqueue` keeps what it was asked (`Request`: the command and its parameters, with the photos written out) +and `Session::start_waiting` runs it, under the id it had in line, once the lane is free. The engine calls it after +every command and the app every frame. `activity.list` shows a waiting task after the running ones (`waiting`, +`place`, `lane`); the activity stack in the app draws only running tasks. `activity.cancel` takes a waiting task out +of the line, `activity.cancel {all: true}` empties it, and opening another library drops it: the photos it names +belong to the old one. At most `MAX_WAITING` (100) tasks wait. Without `queue` a call is refused while its lane is +busy, as before. A waiting task whose start fails (there is no smart previews folder any more, say) is logged and the next in line goes on. + ## Examples in the code | Job | Where | Shows how to | diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 4f25582349..1b34c9e288 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -89,7 +89,7 @@ filmstrip is visible. | `engine.commands` | — | Engine + UI commands: id, label, menu, shortcut, params doc, enabled | | `ui.menu.list` | — | Menu entries (flat: id, label, menu path, shortcut, enabled) | | `ui.menu.tree` | — | The menu bar as shown (File … Help): items `{id, params?, label, shortcut?, enabled, checked?}`, separators, submenus — the model behind the native macOS menu bar and the in-window menus | -| `ui.inspect` | — | UI state, window, `loupe` (`source`, `pending`, `failed` = why its render failed, else `null`, and `region: {full, window, pending}` when a zoomed view also renders the window on screen at no more than 100 % — `full` is the frame it is cut from, `window` its `[x, y, w, h]` — and `regionBefore` for the Before side of a Before/After view), canvas/image rects, `scroll: {grid, filmstrip}` (scroll offsets in points, `null` until drawn), active photo, selection, perf (`frameMs` = layout, `logicMs` = per-frame logic before it, `updateMs` = both, `maxUpdateMs`, `fps`, render queue …, `gpu` = adapter in use, `gpuReason` = why renders don't use the GPU, `gpuFallback` = latest render redone on the CPU and why, `gpuWindowDevice` / `screenTextures` / `mainOnGpu` = renders run on the window's device / can be drawn from the GPU / the loupe shows one now — see `docs/gpu-pipeline.md`, `loupeSteps` = how the loupe showed each photo it was stepped to, measured on the frames it drew: `{steps: [{photo, anyMs, anySource, fullMs, fullSource, sharpMs, dwellMs}], total, current}` — ms from the step to the first frame with anything of the photo, with a full-size picture (`embedded` camera JPEG, `cached` or `render`), and with LightCraft's own render; `dwellMs` is how long it stayed, the latest 256 steps; `total` counts every step finished since launch, a cursor that keeps rising when old steps leave the list; `thumbsMade` = photos given a grid thumbnail since launch (never lowered when old thumbnails are evicted, unlike `thumbTextures`); `previewCache` = the rendered-preview cache: `memEntries` / `memBytes` in memory, the disk cache's `diskHits`, `diskMisses`, `diskWrites` and `diskBudget` (bytes; all `null` without a library on disk), and `loupeEdge` (px, the loupe's longest edge, the size standard previews are built at)), status, memory (bytes per cache, see `library.memory`; plus stage caches — `budgetBytes`, `trimmed`, `sharedSourceBytes` (the one device copy of a big original) — and textures), `export: {running: {total, done, current} \| null, last}`, `notices` (warnings waiting to be shown, e.g. a damaged settings file, or once per session the drive holding the preview cache running low; OK = `button:noticeOk`, and the low-drive notice's `button:noticeSettings` opens Settings ▸ Performance), `quitPrompt` (why quitting was stopped: tasks that would be cut short are running — `button:quitAnyway` cancels them and quits, `button:quitCancel` keeps working — or unsaved changes: `button:quitRetry` / `button:quitAnyway` / `button:quitCancel`), `import: {done, total, imported, cancelled} \| null` (an import runs on a worker thread), `tasks` (other background work: `Find Missing Photos`, `Auto Import`), `activity` (every long-running task in flight as the activity stack in the top-left corner shows it, same shape as `activity.list`; a row appears once its task is 0.5 s old, ids `activity:row:`, ✕ = `activity:cancel:`, `activity:more` expands past 3 rows), `fileDialogs` (commands waiting on a native file dialog, which runs off the UI thread; they run again with the answer when it closes), `copied` (the text the UI last put on the clipboard, `null` until something is copied) | +| `ui.inspect` | — | UI state, window, `loupe` (`source`, `pending`, `failed` = why its render failed, else `null`, and `region: {full, window, pending}` when a zoomed view also renders the window on screen at no more than 100 % — `full` is the frame it is cut from, `window` its `[x, y, w, h]` — and `regionBefore` for the Before side of a Before/After view), canvas/image rects, `scroll: {grid, filmstrip}` (scroll offsets in points, `null` until drawn), active photo, selection, perf (`frameMs` = layout, `logicMs` = per-frame logic before it, `updateMs` = both, `maxUpdateMs`, `fps`, render queue …, `gpu` = adapter in use, `gpuReason` = why renders don't use the GPU, `gpuFallback` = latest render redone on the CPU and why, `gpuWindowDevice` / `screenTextures` / `mainOnGpu` = renders run on the window's device / can be drawn from the GPU / the loupe shows one now — see `docs/gpu-pipeline.md`, `loupeSteps` = how the loupe showed each photo it was stepped to, measured on the frames it drew: `{steps: [{photo, anyMs, anySource, fullMs, fullSource, sharpMs, dwellMs}], total, current}` — ms from the step to the first frame with anything of the photo, with a full-size picture (`embedded` camera JPEG, `cached` or `render`), and with LightCraft's own render; `dwellMs` is how long it stayed, the latest 256 steps; `total` counts every step finished since launch, a cursor that keeps rising when old steps leave the list; `thumbsMade` = photos given a grid thumbnail since launch (never lowered when old thumbnails are evicted, unlike `thumbTextures`); `previewCache` = the rendered-preview cache: `memEntries` / `memBytes` in memory, the disk cache's `diskHits`, `diskMisses`, `diskWrites` and `diskBudget` (bytes; all `null` without a library on disk), and `loupeEdge` (px, the loupe's longest edge, the size standard previews are built at)), status, memory (bytes per cache, see `library.memory`; plus stage caches — `budgetBytes`, `trimmed`, `sharedSourceBytes` (the one device copy of a big original) — and textures), `export: {running: {total, done, current} \| null, last}`, `notices` (warnings waiting to be shown, e.g. a damaged settings file, or once per session the drive holding the preview cache running low; OK = `button:noticeOk`, and the low-drive notice's `button:noticeSettings` opens Settings ▸ Performance), `quitPrompt` (why quitting was stopped: tasks that would be cut short are running — `button:quitAnyway` cancels them and quits, `button:quitCancel` keeps working — or unsaved changes: `button:quitRetry` / `button:quitAnyway` / `button:quitCancel`), `import: {done, total, imported, cancelled} \| null` (an import runs on a worker thread), `tasks` (other background work: `Find Missing Photos`, `Auto Import`), `activity` (every long-running task in flight, same shape as `activity.list` (including tasks waiting in line, which have no row); the activity stack in the top-left corner shows the running ones, and a row appears once its task is 0.5 s old, ids `activity:row:`, ✕ = `activity:cancel:`, `activity:more` expands past 3 rows), `fileDialogs` (commands waiting on a native file dialog, which runs off the UI thread; they run again with the answer when it closes), `copied` (the text the UI last put on the clipboard, `null` until something is copied) | | `ui.widgets` | `{filter?}` | On-screen widgets `{id, rect: [x, y, w, h]}` (screen points) | | `ui.clickWidget` / `ui.dragWidget` / `ui.hoverWidget` | `{id, count?, button?, fx?, fy?}` (`button: "right"` right-clicks; `count` is capped at 16) / `{id, toX?, toY?, dx?, dy?, steps?}` (steps are capped at 1000) / `{id, fx?, fy?}` | Real egui input on a widget (hover: the pointer rests on it, e.g. for preset/profile previews). `fx`/`fy` are fractions of the registered rect and may lie outside `[0,1]`; the resulting point must still be inside egui's clipped interaction rect, and a non-finite fraction or resolved point is rejected before any input is queued. Geometry comes from the latest completed layout; if the widget moves before the first event or before a press, or its latest clipped rect no longer contains the point, the request fails with an error instead of clicking another widget or retargeting. A target below an ordinary modal dialog may succeed as a no-op or a backdrop click, because egui routes that input to the dialog; a target covered by a non-modal overlay fails. The blocking library-problem/launch-list window is explicit: its dim takes the modal layer, but a background target fails instead of reporting a no-op success, and only that window's own controls (`button:library…`) pass. Its creation frame is shielded and redrawn with empty input like a prompt's, so background text/pointer input cannot act while the new modal areas settle. A quit prompt or settings notice is a real egui modal scope with a foreground backdrop. Only its own buttons (`button:quit…`, `button:noticeOk`) accept a `ui.clickWidget`; background targets fail, and background keystrokes, text/clipboard input, wheel/zoom input and AccessKit actions are dropped before panels see them. The prompt itself takes Tab/Shift+Tab, Enter/Space on the focused button, and Escape/Enter for the safe default Cancel; AccessKit Focus/Click works when targeted at a prompt button. Its first creation frame (including a Tasks→Unsaved or notice→next-notice transition) is shielded and redrawn with empty input, so a press/release in that frame, or a held press from before it, cannot act underneath it; a synthetic drag already in progress is canceled. Once settled, raw `ui.click`/`ui.drag`/`ui.pointer` and backdrop clicks are still delivered to the prompt backdrop as no-ops, and the prompt's own button clicks work normally. The area/layer check cannot see a different widget covering the point in the same layer. A `ui.clickWidget` whose widget disappears before its release also fails, after canceling the pointer press without a click or drag (the same rules apply when a click spans several host frames) | | `ui.move` / `ui.click` / `ui.drag` | `{x, y, count?, button?}` / `{x, y, toX, toY, steps?}` | Raw pointer input, screen points (the same click and step caps apply). In every pointer and scroll gesture a number other than `count` and `steps` must lie between −1,000,000 and 1,000,000, or the request is refused and queues nothing | @@ -106,8 +106,8 @@ filmstrip is visible. | `ui.zoomFactor` | `{factor}` | Set the interface scale (0.5–3; egui's zoom keys are off, Cmd+= / Cmd+- zoom the photo) | | `ui.screenshot` | `{path?, headless?}` | `{path, width, height}` once the frame (with finished renders) is captured. A `path` that did not exist when the request was admitted is written with create-new semantics and is never replaced if a file (including a newly imported original) appears there while the capture is queued; an existing ordinary file may be refreshed. `headless: true` draws the UI on the CPU (no compositor needed); a windowed capture that gets no frame within 2 s falls back to headless automatically. While the loupe still waits for a render, `ui.widgets {filter: "loupe:rendering"}` lists its "Rendering…" pill; `loupe:renderFailed` is the pill saying a render failed behind a stand-in; Compare and Reference panes have their own (`compare:rendering:`, `compare:renderFailed:`) | | `engine.execute {command: "app.export", params}` | export params (see `docs/mcp.md`), plus `preset`, `dir` / `path`, `ids`, `background`; `destinationMode: "sameAsOriginal"` writes each photo into its original's folder (+ `subfolder`) instead of `dir` | Writes the files and returns `{files}` (one `{path, width, height, bytes, sidecars}` per file, plus `gpuFallback` — why that render fell back from the GPU to the CPU — when it did; see `docs/gpu-pipeline.md`); with `background: true` (what the Export dialog and menus use) it returns `{background: true, total}` at once and the batch runs on a worker thread — poll `ui.inspect` → `export` | -| `engine.execute {command: "activity.list"}` | — | The long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first: `{tasks: [{id, kind, label, done, total, unit, detail, cancellable, cancelling, ageMs}]}`; `total` 0 = not known yet; `unit` is `count`, `bytes` or `percent`; `label` is English (the app shows it translated) | -| `engine.execute {command: "activity.cancel"}` | `{id}` or `{all: true}` | Asks the task (or every cancellable one) to stop at its next file or photo → `{cancelled: n}`; an unknown id (it may have just finished) or a task that can't be cancelled is an error | +| `engine.execute {command: "activity.list"}` | — | The long-running tasks in flight (imports, exports, preview builds, downloads, the face scan…), oldest first: `{tasks: [{id, kind, label, done, total, unit, detail, cancellable, cancelling, ageMs, waiting, place, lane}]}`, then the tasks waiting in line for one of their lane (`waiting: true`, `place` 1 = next in its lane, `lane: "previews"`, `done` and `total` 0; `queue: true` on `library.buildPreviews` / `library.smartPreviews` puts a build there instead of refusing it); `total` 0 = not known yet; `unit` is `count`, `bytes` or `percent`; `label` is English (the app shows it translated) | +| `engine.execute {command: "activity.cancel"}` | `{id}` or `{all: true}` | Asks the task (or every cancellable one) to stop at its next file or photo (a waiting task leaves the line and never runs; `all` empties it) → `{cancelled: n}`; an unknown id (it may have just finished) or a task that can't be cancelled is an error | | `ui.render` | `{id?, size?, path?}` | Render a photo (PNG to `path`), `{width, height}` | | `engine.execute {command: "slideshow.layout"}` | `{margins?, marginLeft?, …, zoomToFill?, strokeBorder?, castShadow?, backdropColor?, colorWash?, backgroundImage?, …}` (see `engine.commands`) | The slideshow's slide layout (Layout, Options, Backdrop), saved with the library; omitted keys keep their value, `{}` reads it; out-of-range numbers are clamped, a wrong type or unknown key is refused and nothing changes | | `engine.execute {command: "slideshow.overlays"}` | `{identityPlate?: {enabled?, text?, image?, size?, color?, opacity?, anchor?, offsetX?, offsetY?, relativeTo?, behind?}, ratingStars?: {enabled?, color?, size?, anchor?, …}, texts?: [{text?, size?, color?, opacity?, anchor?, offsetX?, offsetY?, relativeTo?, shadow?, shadowOpacity?, shadowOffset?, shadowRadius?, shadowAngle?}], addText?, removeText?, showWatermark?, watermark?}` (see `engine.commands`) | The overlays drawn on every slide, saved with the library: sizes and offsets are fractions of the slide's shorter side, anchors `topLeft`…`bottomRight` of the `slide` or the `photo`; text overlays expand tokens (`{caption}`, `{exposure}`, `{date}`, the file-naming tokens…; unknown tags show as typed); `watermark` takes the export watermark's keys. Replies with the settings and `warnings` |