From d10a9af00b5b8a87a70c1d7e123295e68ee168ce Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Fri, 16 Oct 2026 08:25:22 -0400 Subject: [PATCH 1/3] LR-LIB-SMARTALBUM: creating or giving a keyword no longer freezes the window while albums are counted MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In a large library with smart albums, the frame after an edit the album tally could not follow photo by photo counted every smart album over every photo on the UI thread: seconds, during which the window froze. Creating a keyword inside another one (and giving it to the selected photos) was such an edit, because Op::SetKeyword was classed as a broad op, so the view, the folder tree and the date groups were worked out again too. - The keyword list changes no photo and no rule, filter or sort reads it: Op::SetKeyword now records Aspects::KEYWORD_LIST instead of marking the catalog's change memory broad. The view and the albums' counts follow the edit from the photos it touched; only the keyword tree is made again. - A count of every photo that is still needed (an album's rules or photos changed, an edit to more than 256 photos, a new minute with an "in the last…" rule, a library opened) runs on a worker thread over a copy of the catalog. The sidebar keeps the counts it showed (none before the first count, and none of another library) and follows the edits made meanwhile once the count is in. AlbumTally::update only follows now; the caller decides where to count whole. Co-Authored-By: Claude --- crates/catalog/src/lib.rs | 21 +- crates/catalog/src/tally.rs | 19 +- crates/catalog/src/tests.rs | 6 + crates/engine/src/tests/view_follow.rs | 38 +++- crates/ui-egui/src/caches.rs | 242 ++++++++++++++++++++--- crates/ui-egui/src/headless.rs | 5 +- crates/ui-egui/src/lib.rs | 11 +- crates/ui-egui/src/panels/left/albums.rs | 6 +- docs/parity-checklist.md | 2 +- 9 files changed, 292 insertions(+), 58 deletions(-) diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 453b68a6972..3225284c5f7 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -316,6 +316,9 @@ impl Aspects { pub const ANALYSIS: Aspects = Aspects(1 << 7); /// Whether it is in the library at all: added, removed, deleted, restored, taken in from Local. pub const PRESENCE: Aspects = Aspects(1 << 8); + /// The keyword list (keywords on their own and their attributes): of no photo, and read by no rule, filter or + /// sort, only by what lists keywords (the keyword tree, export names). + pub const KEYWORD_LIST: Aspects = Aspects(1 << 9); /// Everything: the photo may count differently for any tally. pub const ALL: Aspects = Aspects(u16::MAX); @@ -340,9 +343,11 @@ struct Changes { touched: std::collections::VecDeque<(u64, PhotoId, Aspects)>, /// What the op being applied changes of its photo. now: Aspects, - /// The latest revision made by an op that changed more than photos of its own (an album, a stack, a keyword of - /// the list…): what it changed for which photos is not known. + /// The latest revision made by an op that changed more than photos of its own (an album, a stack…): what it + /// changed for which photos is not known. broad: u64, + /// The latest revision made by an op that changed the keyword list ([`Aspects::KEYWORD_LIST`]). + keyword_list: u64, /// Changes up to this revision are no longer all in `touched`. floor: u64, /// The revision the last op recorded here made. When the catalog's revision is another, it was set from @@ -589,7 +594,8 @@ impl Catalog { if !self.remembers(revision) { return None; } - Some(self.changes.touched.iter().filter(|(r, _, _)| *r > revision).fold(Aspects::NONE, |all, (_, _, a)| all.with(*a))) + let photos = self.changes.touched.iter().filter(|(r, _, _)| *r > revision).fold(Aspects::NONE, |all, (_, _, a)| all.with(*a)); + Some(if self.changes.keyword_list > revision { photos.with(Aspects::KEYWORD_LIST) } else { photos }) } /// Whether every change since the catalog was at `revision` is remembered photo by photo. @@ -653,9 +659,9 @@ impl Catalog { } fn apply_inner(&mut self, op: Op) -> Result { - // An op that changes one photo says which (`photo_mut`, and adding or removing it below). Every other kind - // can change what any photo matches or where it sorts: an album's photos or rules, a stack, a keyword's - // name. Listed kind by kind, so a new one has to be put on one side. + // An op that changes one photo says which (`photo_mut`, and adding or removing it below). Most other kinds + // can change what any photo matches or where it sorts: an album's photos or rules, a stack. The keyword + // list changes only lists of keywords. Listed kind by kind, so a new one has to be put on one side. match &op { // (a photo that comes, goes, or changes what it is to the library counts for every tally; so do the // rare kinds whose reach nobody has to think about) @@ -695,8 +701,9 @@ impl Catalog { | Op::SetStack { .. } | Op::SetLabelName { .. } | Op::SetBrowsed { .. } - | Op::SetKeyword { .. } | Op::SetFolderRecord { .. } => self.changes.broad = self.revision.saturating_add(1), + // (no photo matches, counts or sorts by it: only lists of keywords change) + Op::SetKeyword { .. } => self.changes.keyword_list = self.revision.saturating_add(1), } Ok(match op { Op::AddPhoto { photo } => { diff --git a/crates/catalog/src/tally.rs b/crates/catalog/src/tally.rs index e8fdc61979b..c6cfef295ad 100644 --- a/crates/catalog/src/tally.rs +++ b/crates/catalog/src/tally.rs @@ -3,8 +3,8 @@ //! A smart album's count asks every photo whether its rules hold. Asked again after every edit, that is a pass over //! the library for each smart album each time a keyword is given. [`AlbumTally`] remembers which photos each smart //! album holds, and after a small edit asks only the photos the edit touched ([`Catalog::touched_since`]). An op -//! that changes more than photos of its own (an album's rules or photos, a stack, the keyword list) has it counted -//! whole again, as before. +//! that changes more than photos of its own (an album's rules or photos, a stack) has to be counted whole again +//! ([`AlbumTally::of`]): the caller decides where (the app does it off the UI thread). use std::collections::{HashMap, HashSet}; @@ -168,27 +168,24 @@ impl AlbumTally { self.revision } - /// Bring the counts up to `cat` as it is now. `true` when that was done from the photos the ops since touched - /// (or nothing had changed), `false` when every photo was asked again. + /// Bring the counts up to `cat` as it is now from the photos the ops since touched. `true` when that was done (or + /// nothing had changed); `false` when it can't be, and every photo has to be asked again ([`AlbumTally::of`]): + /// the counts are then left as they were. /// /// `cat` has to be the catalog the counts were made of, further along. Another catalog is told apart only by - /// its revisions: a library that is loaded takes a range of its own (and then everything is counted again), but - /// two catalogs both counting from 0 look like one. + /// its revisions: a library that is loaded takes a range of its own (and then nothing is followed), but two + /// catalogs both counting from 0 look like one. pub fn update(&mut self, cat: &Catalog) -> bool { if self.revision == cat.revision { return true; } - let followed = match (cat.touched_since(self.revision), cat.aspects_since(self.revision)) { + match (cat.touched_since(self.revision), cat.aspects_since(self.revision)) { (Some(touched), Some(changed)) if touched.len() <= MAX_FOLLOWED => { self.follow(cat, &touched, changed); true } _ => false, - }; - if !followed { - *self = AlbumTally::of(cat); } - followed } /// The counts after ops that touched only `touched`: each smart album asks those photos again; an album of diff --git a/crates/catalog/src/tests.rs b/crates/catalog/src/tests.rs index bf67b249580..fa71eb69bec 100644 --- a/crates/catalog/src/tests.rs +++ b/crates/catalog/src/tests.rs @@ -960,6 +960,12 @@ fn history_handles_loaded_revisions_failed_batches_and_retention() { let before = c.revision; c.apply(Op::Batch { ops: vec![Op::SetRating { id: a, rating: 3 }, Op::RenameAlbum { id: album, name: "Journey".into() }] }).unwrap(); assert_eq!(c.touched_since(before), None); + // the keyword list changes no photo: what was touched stays known, and the list is said to have changed + let before = c.revision; + c.apply(Op::SetKeyword { path: "travel|Rome".into(), info: Some(Default::default()) }).unwrap(); + assert_eq!(c.touched_since(before), Some(vec![])); + assert_eq!(c.aspects_since(before), Some(Aspects::KEYWORD_LIST)); + assert_eq!(c.aspects_since(c.revision), Some(Aspects::NONE), "and from after it, not"); // more ops than are remembered: the oldest are answered with "anything" let long_ago = c.revision; for i in 0..9000u32 { diff --git a/crates/engine/src/tests/view_follow.rs b/crates/engine/src/tests/view_follow.rs index bc47d94c94b..88e365d554a 100644 --- a/crates/engine/src/tests/view_follow.rs +++ b/crates/engine/src/tests/view_follow.rs @@ -360,6 +360,35 @@ fn an_edit_to_many_photos_or_to_more_than_photos_is_worked_out_whole() { assert_eq!((s.view_followed, s.view_worked_out), (followed + 1, whole + 2)); } +/// A keyword created in the keyword list, inside another and given to the selected photo at once, changes no photo +/// but that one: the view and the albums' counts follow it from that photo instead of asking every photo again. +#[test] +fn a_keyword_created_inside_another_and_given_to_a_photo_is_followed_from_that_photo() { + use lightcraft_catalog::{AlbumId, tally::AlbumTally}; + let (mut s, ids, _, smart) = library(600); + let _ = s.visible_cloned(); + let mut tally = AlbumTally::of(&s.catalog); + let (followed, whole) = (s.view_followed, s.view_worked_out); + // (the second photo has no keywords: it is in the smart album of those) + let bare = ids[1]; + assert!(s.catalog.photo(bare).is_some_and(|p| p.meta.keywords.is_empty())); + let unkeyworded = tally.counts()[&AlbumId(smart)]; + s.execute("library.select", &json!({"ids": [bare.0]})).unwrap(); + s.execute("keyword.create", &json!({"name": "Rome", "parent": "travel", "addToSelected": true})).unwrap(); + let _ = s.visible_cloned(); + assert_eq!((s.view_followed, s.view_worked_out), (followed + 1, whole), "followed, not worked out whole"); + assert!(tally.update(&s.catalog), "the counts followed"); + assert_eq!(tally.counts()[&AlbumId(smart)], unkeyworded - 1, "the photo has a keyword now"); + // a keyword created on its own, for no photo: nothing else to follow + s.execute("keyword.create", &json!({"name": "Paris", "parent": "travel"})).unwrap(); + let _ = s.visible_cloned(); + assert_eq!((s.view_followed, s.view_worked_out), (followed + 2, whole)); + assert!(tally.update(&s.catalog)); + // and what was followed is what every photo says + assert_eq!(s.visible_cloned(), s.visible_in_full()); + assert_eq!(tally.counts()[&AlbumId(smart)], s.catalog.album_count(AlbumId(smart))); +} + #[test] fn the_albums_counts_followed_through_edits_are_the_counts_made_from_every_photo() { use lightcraft_catalog::tally::AlbumTally; @@ -402,7 +431,10 @@ fn the_albums_counts_followed_through_edits_are_the_counts_made_from_every_photo let moved = tally.revision() != s.catalog.revision; match (moved, tally.update(&s.catalog)) { (true, true) => followed += 1, - (true, false) => whole += 1, + (true, false) => { + tally = AlbumTally::of(&s.catalog); + whole += 1; + } // (an edit that was refused changed nothing: nothing to follow) (false, _) => {} } @@ -428,8 +460,10 @@ fn the_albums_counts_followed_through_edits_are_the_counts_made_from_every_photo let many: Vec = if many.len() >= 300 { many } else { s.visible_cloned().iter().take(300).map(|id| id.0).collect() }; if many.len() > 256 { s.execute("library.select", &json!({"ids": many})).unwrap(); + let before = shown(&tally); s.execute("photo.rate", &json!({"rating": 5})).unwrap(); assert!(!tally.update(&s.catalog), "more photos than are followed one by one"); - assert_eq!(shown(&tally), fresh(&s)); + assert_eq!(shown(&tally), before, "not followed: left as they were, to be counted again"); + assert_eq!(shown(&AlbumTally::of(&s.catalog)), fresh(&s)); } } diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 93fe551847f..13ab8031dd3 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -8,6 +8,31 @@ pub struct LibraryCounts { pub deleted: usize, } +/// The albums' counts as the sidebar shows them ([`Caches::album_counts`]). +pub(crate) struct AlbumCounts { + /// The library they are of ([`lightcraft_engine::Session::library_generation`]). + library: u64, + /// The minute they are of while a smart album asks about "the last N days" (else empty). + minute: String, + /// What follows edits to a photo or a few. + tally: lightcraft_catalog::tally::AlbumTally, + /// The counts as the panels take them. + shown: std::sync::Arc>, +} + +/// A count of every photo on a worker thread ([`Caches::album_counts`]). +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub(crate) struct AlbumRecount { + /// The library, minute and catalog revision it counts. + library: u64, + minute: String, + revision: u64, + /// The count, sent before the repaint is asked for, so the frame it wakes finds it. + done: std::sync::mpsc::Receiver>, + /// The thread, until it has let go of its copy of the catalog. + worker: std::thread::JoinHandle<()>, +} + /// The values the filter bar's pickers offer. #[derive(Clone, Debug, Default)] pub struct FilterValues { @@ -42,6 +67,9 @@ const READS_FILE: lightcraft_catalog::Aspects = lightcraft_catalog::Aspects::PRE const READS_META: lightcraft_catalog::Aspects = lightcraft_catalog::Aspects::PRESENCE.with(lightcraft_catalog::Aspects::META); +/// The keyword tree: the keywords photos carry, and the keyword list's own. +const READS_KEYWORDS: lightcraft_catalog::Aspects = READS_META.with(lightcraft_catalog::Aspects::KEYWORD_LIST); + const READS_PEOPLE: lightcraft_catalog::Aspects = READS_META.with(lightcraft_catalog::Aspects::ANALYSIS); const READS_CAPTURED: lightcraft_catalog::Aspects = lightcraft_catalog::Aspects::PRESENCE.with(lightcraft_catalog::Aspects::CAPTURED); @@ -62,7 +90,7 @@ impl Caches { } /// The library's keyword tree. pub fn keyword_tree(&mut self, cat: &lightcraft_catalog::Catalog) -> std::sync::Arc> { - let kept = self.keyword_tree.take().filter(|(r, _)| still_right(cat, *r, READS_META)).map(|(_, t)| t); + let kept = self.keyword_tree.take().filter(|(r, _)| still_right(cat, *r, READS_KEYWORDS)).map(|(_, t)| t); let t = kept.unwrap_or_else(|| std::sync::Arc::new(cat.keyword_tree())); self.keyword_tree = Some((cat.revision, t.clone())); t @@ -327,22 +355,32 @@ impl Caches { v } + /// How many photos each album of the library `library` ([`lightcraft_engine::Session::library_generation`]) + /// shows, `now` being the session clock ("in the last…" rules count back from it). + /// + /// An edit to a photo or a few is followed at once: a smart album asks only those photos again (a keyword + /// created and given to them too: the keyword list itself counts in no album). Anything more (an album's rules + /// or photos changed, a stack, an edit to many photos such as a keyword renamed across them, a new minute while + /// a smart album asks about "the last N days", another library) counts every photo again, seconds in a large + /// library. That count runs on a worker thread (natively) while the counts shown before stay (none the first + /// time, and none of another library); `ctx` repaints when it is done, and edits made meanwhile are followed + /// from it. pub fn album_counts( &mut self, cat: &lightcraft_catalog::Catalog, + library: u64, now: &str, + ctx: &egui::Context, ) -> std::sync::Arc> { let relative = cat.albums().any(|a| a.smart.as_ref().is_some_and(|f| f.depends_on_now())); let minute = if relative { now.get(..16).unwrap_or(now) } else { "" }; - // the counts of this minute, if there are any: an edit to a photo or a few is followed from them, a smart - // album asking only those photos again; anything more, or a new minute, is counted from every photo - let kept = self.album_counts.take().filter(|(of, _, _)| of == minute); - if let Some((_, tally, shown)) = &kept - && tally.revision() == cat.revision - { - let shown = shown.clone(); - self.album_counts = kept; - return shown; + self.collect_album_recount(library); + // (album ids start again in every library: another one's counts would be shown on this one's albums) + if self.album_counts.as_ref().is_some_and(|c| c.library != library) { + self.album_counts = None; + } + if let Some(counts) = self.album_counts.as_ref().filter(|c| c.minute == minute && c.tally.revision() == cat.revision) { + return counts.shown.clone(); } if relative { // "in the last N days" counts back from the session clock, as in the grid. (Within a minute an edit asks @@ -350,21 +388,87 @@ impl Caches { // far out as the counts already were between edits, and the next minute counts them all again.) lightcraft_catalog::rules::set_now(Some(now.to_string())); } - let tally = match kept { - Some((_, mut tally, _)) => { - if !tally.update(cat) { - self.album_count_scans += 1; + if let Some(counts) = self.album_counts.as_mut().filter(|c| c.minute == minute) + && counts.tally.update(cat) + { + counts.shown = std::sync::Arc::new(counts.tally.counts().clone()); + return counts.shown.clone(); + } + self.recount_albums(cat, library, minute, now, relative, ctx); + self.album_counts.as_ref().map(|c| c.shown.clone()).unwrap_or_default() + } + + /// A count of every photo is running ([`Caches::album_counts`]). + pub fn album_recount_running(&self) -> bool { + self.album_recount.as_ref().is_some_and(|job| !job.worker.is_finished()) + } + + /// Count every photo for [`Caches::album_counts`]: on a worker thread when one can be started, else here. + fn recount_albums(&mut self, cat: &lightcraft_catalog::Catalog, library: u64, minute: &str, now: &str, relative: bool, ctx: &egui::Context) { + // one at a time: what it finds is followed up to the catalog as it is by then, or counted again + let failed = self.album_recount_failed.as_ref().is_some_and(|(l, r, m)| *l == library && *r == cat.revision && m == minute); + if self.album_recount.is_some() || failed { + return; + } + self.album_count_scans += 1; + #[cfg(not(target_arch = "wasm32"))] + { + // (cheap: the copy shares the photos) + let (copy, ctx, now) = (cat.clone(), ctx.clone(), relative.then(|| now.to_string())); + let (tx, done) = std::sync::mpsc::channel(); + let spawned = std::thread::Builder::new().name("lc-album-counts".into()).spawn(move || { + let counted = lightcraft_engine::guard::catch("Counting the albums' photos", || { + lightcraft_catalog::rules::set_now(now); + lightcraft_catalog::tally::AlbumTally::of(©) + }); + let _ = tx.send(counted); + ctx.request_repaint(); + }); + match spawned { + Ok(worker) => { + self.album_recount = Some(AlbumRecount { library, minute: minute.to_string(), revision: cat.revision, done, worker }); + return; } - tally + Err(e) => log::warn!("album counts: can't start a thread ({e}); counting them here"), } - None => { - self.album_count_scans += 1; - lightcraft_catalog::tally::AlbumTally::of(cat) + } + #[cfg(target_arch = "wasm32")] + let _ = (now, relative, ctx); + // (`album_counts` has set the clock on this thread) + let counted = lightcraft_engine::guard::catch("Counting the albums' photos", || lightcraft_catalog::tally::AlbumTally::of(cat)); + self.finish_album_recount(library, cat.revision, minute.to_string(), counted); + } + + /// Take the worker's count once it is done; a count of another library is let go (its thread ends on its own). + fn collect_album_recount(&mut self, library: u64) { + let Some(job) = &self.album_recount else { return }; + if job.library != library { + self.album_recount = None; + return; + } + let counted = match job.done.try_recv() { + Ok(counted) => counted, + Err(std::sync::mpsc::TryRecvError::Empty) => return, + Err(std::sync::mpsc::TryRecvError::Disconnected) => { + log::error!("album counts: the count stopped without an answer"); + Err("stopped without an answer".to_string()) } }; - let shown = std::sync::Arc::new(tally.counts().clone()); - self.album_counts = Some((minute.to_string(), tally, shown.clone())); - shown + let Some(job) = self.album_recount.take() else { return }; + self.finish_album_recount(job.library, job.revision, job.minute, counted); + } + + /// The counts a count of every photo made are the ones shown. One that failed (already logged) leaves those + /// shown before, and isn't tried again for the same library, catalog and minute. + fn finish_album_recount(&mut self, library: u64, revision: u64, minute: String, counted: Result) { + match counted { + Ok(tally) => { + self.album_recount_failed = None; + let shown = std::sync::Arc::new(tally.counts().clone()); + self.album_counts = Some(AlbumCounts { library, minute, tally, shown }); + } + Err(_) => self.album_recount_failed = Some((library, revision, minute)), + } } } @@ -386,6 +490,27 @@ mod cache_tests { Op::AddAlbum { album: a } } + type Counts = std::sync::Arc>; + + /// [`super::Caches::album_counts`] of library `library` once a count of every photo it started is done and + /// taken. + fn counted_in(c: &mut super::Caches, cat: &Catalog, library: u64, now: &str) -> Counts { + let ctx = egui::Context::default(); + let t0 = std::time::Instant::now(); + loop { + let shown = c.album_counts(cat, library, now, &ctx); + if c.album_recount.is_none() { + return shown; + } + assert!(t0.elapsed() < std::time::Duration::from_secs(30), "the count is done"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + } + + fn counted(c: &mut super::Caches, cat: &Catalog, now: &str) -> Counts { + counted_in(c, cat, 0, now) + } + /// Smart-album counts: unchanged frames reuse them; metadata and rule changes and (for /// "in the last…" rules) the clock crossing into a new minute recompute them. #[test] @@ -398,23 +523,23 @@ mod cache_tests { cat.apply(smart(10, serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 3}]}))).unwrap(); cat.apply(smart(11, serde_json::json!({"rules": [{"field": "captureDate", "op": "inLast", "value": {"n": 1, "unit": "hours"}}]}))).unwrap(); let now = "2026-09-30T12:00:00"; - let n = c.album_counts(&cat, now); + let n = counted(&mut c, &cat, now); assert_eq!((n[&AlbumId(10)], n[&AlbumId(11)]), (1, 1)); assert_eq!(c.album_count_scans, 1); for _ in 0..10 { - c.album_counts(&cat, "2026-09-30T12:00:40"); + counted(&mut c, &cat, "2026-09-30T12:00:40"); } assert_eq!(c.album_count_scans, 1, "unchanged frames in the same minute don't rescan"); // a photo rated: followed from that photo, not counted from every one cat.apply(Op::SetRating { id: PhotoId(2), rating: 4 }).unwrap(); - assert_eq!(c.album_counts(&cat, now)[&AlbumId(10)], 2); + assert_eq!(counted(&mut c, &cat, now)[&AlbumId(10)], 2); assert_eq!(c.album_count_scans, 1); // rule change let rs: RuleSet = serde_json::from_value(serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 5}]})).unwrap(); cat.apply(Op::SetAlbumRules { id: AlbumId(10), rules: Box::new(Filter { rule_set: Some(rs), ..Default::default() }) }).unwrap(); - assert_eq!(c.album_counts(&cat, now)[&AlbumId(10)], 1); + assert_eq!(counted(&mut c, &cat, now)[&AlbumId(10)], 1); // an hour later the 11:59:30 photo has left "in the last hour", with no catalog change - assert_eq!(c.album_counts(&cat, "2026-09-30T13:00:10")[&AlbumId(11)], 0); + assert_eq!(counted(&mut c, &cat, "2026-09-30T13:00:10")[&AlbumId(11)], 0); assert_eq!(c.album_count_scans, 3, "new rules and a new minute are counted from every photo; the rating was not"); lightcraft_catalog::rules::set_now(None); } @@ -462,8 +587,69 @@ mod cache_tests { let mut c = super::Caches::default(); cat.apply(photo(1, "2026-09-30T11:59:30", 5)).unwrap(); cat.apply(smart(10, serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 3}]}))).unwrap(); - c.album_counts(&cat, "2026-09-30T12:00:00"); - c.album_counts(&cat, "2027-01-01T00:00:00"); + counted(&mut c, &cat, "2026-09-30T12:00:00"); + counted(&mut c, &cat, "2027-01-01T00:00:00"); assert_eq!(c.album_count_scans, 1); } + + /// Counting every photo again (an album's rules changed, an edit to many photos) takes seconds in a large + /// library: it runs off the UI thread, and the sidebar keeps the counts it showed until the new ones are ready. + #[test] + fn a_count_of_every_photo_runs_in_the_background_and_the_counts_shown_stay_meanwhile() { + let mut cat = Catalog::default(); + let mut c = super::Caches::default(); + for i in 0..3u64 { + cat.apply(photo(i + 1, "2026-09-30T11:00:00", if i == 0 { 5 } else { 1 })).unwrap(); + } + cat.apply(smart(10, serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 3}]}))).unwrap(); + let now = "2026-09-30T12:00:00"; + assert_eq!(counted(&mut c, &cat, now)[&AlbumId(10)], 1); + // new rules: every photo is asked again + let rs: RuleSet = serde_json::from_value(serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 1}]})).unwrap(); + cat.apply(Op::SetAlbumRules { id: AlbumId(10), rules: Box::new(Filter { rule_set: Some(rs), ..Default::default() }) }).unwrap(); + let ctx = egui::Context::default(); + assert_eq!(c.album_counts(&cat, 0, now, &ctx)[&AlbumId(10)], 1, "the frame after the change shows the counts it had"); + assert!(c.album_recount.is_some(), "and every photo is counted elsewhere"); + // done counting is said whether or not a frame has taken the count yet (a folded Albums section takes none) + let t0 = std::time::Instant::now(); + while c.album_recount_running() { + assert!(t0.elapsed() < std::time::Duration::from_secs(30), "the count ends"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + // a photo rated meanwhile: followed from what the count finds + cat.apply(Op::SetRating { id: PhotoId(3), rating: 0 }).unwrap(); + assert_eq!(counted(&mut c, &cat, now)[&AlbumId(10)], 2, "three photos rated at least 1, then one not"); + assert_eq!(c.album_count_scans, 2, "counted whole once for the new rules; the rating was followed"); + // the first time there is nothing to show yet: no count, rather than a wrong one + let mut fresh = super::Caches::default(); + assert!(fresh.album_counts(&cat, 0, now, &ctx).get(&AlbumId(10)).is_none()); + assert_eq!(counted(&mut fresh, &cat, now)[&AlbumId(10)], 2); + } + + /// Album ids start again in every library: once another library is open, the albums of the one before never + /// lend it their counts, nor does a count of that library still running when it closed. + #[test] + fn another_library_never_shows_the_counts_of_the_one_before() { + let library = |rated: &[u8]| { + let mut cat = Catalog::default(); + for (i, r) in rated.iter().enumerate() { + cat.apply(photo(i as u64 + 1, "2026-09-30T11:00:00", *r)).unwrap(); + } + cat.apply(smart(10, serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 3}]}))).unwrap(); + cat + }; + let (mut first, second) = (library(&[5, 1, 1]), library(&[5, 5, 1])); + let (mut c, ctx, now) = (super::Caches::default(), egui::Context::default(), "2026-09-30T12:00:00"); + assert_eq!(counted_in(&mut c, &first, 1, now)[&AlbumId(10)], 1); + assert!(c.album_counts(&second, 2, now, &ctx).get(&AlbumId(10)).is_none(), "nothing until its own are counted"); + assert_eq!(counted_in(&mut c, &second, 2, now)[&AlbumId(10)], 2); + // a count of the first library under way when the second opens is let go + let mut c = super::Caches::default(); + assert_eq!(counted_in(&mut c, &first, 1, now)[&AlbumId(10)], 1); + let rs: RuleSet = serde_json::from_value(serde_json::json!({"rules": [{"field": "rating", "op": "gte", "value": 1}]})).unwrap(); + first.apply(Op::SetAlbumRules { id: AlbumId(10), rules: Box::new(Filter { rule_set: Some(rs), ..Default::default() }) }).unwrap(); + assert_eq!(c.album_counts(&first, 1, now, &ctx)[&AlbumId(10)], 1); + assert!(c.album_recount.is_some(), "the first library is being counted"); + assert_eq!(counted_in(&mut c, &second, 2, now)[&AlbumId(10)], 2, "the second library's own count"); + } } diff --git a/crates/ui-egui/src/headless.rs b/crates/ui-egui/src/headless.rs index ab49563cbb8..3e122129b14 100644 --- a/crates/ui-egui/src/headless.rs +++ b/crates/ui-egui/src/headless.rs @@ -388,11 +388,12 @@ impl Headless { } } - /// Is anything still in progress (renders, file-system checks the sidebar waits for, queued - /// input)? + /// Is anything still in progress (renders, file-system checks the sidebar waits for, the albums' counts, + /// queued input)? pub fn busy(&self) -> bool { self.app.renderer.in_flight() > 0 || crate::panels::left::fs_cached_running(&self.view.ctx) > 0 + || self.app.caches.album_recount_running() || self.app.merge.busy() || self.app.scan.is_some() || self.app.sync.is_some() diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9db7035c1d0..8a5528f332a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -78,6 +78,7 @@ mod services; #[cfg(test)] use app::{import_tick_allowed, sam_download_ended, shot_ready}; pub(crate) use caches::key_of; +use caches::{AlbumCounts, AlbumRecount}; pub use caches::{FilterValues, LibraryCounts, RulesView}; use clock::AppClock; pub use clock::{monotonic_ms, now_ms}; @@ -570,10 +571,12 @@ pub struct Caches { counts: Option<(u64, LibraryCounts)>, date_groups: Option<(u64, std::sync::Arc>)>, filter_values: Option<(u64, std::sync::Arc)>, - /// The albums' counts: the minute they are of (while a smart album asks about "the last N days"), the tally - /// that follows edits, and the counts as the panels take them. - album_counts: - Option<(String, lightcraft_catalog::tally::AlbumTally, std::sync::Arc>)>, + /// The albums' counts as the sidebar shows them, with the tally that follows edits. + album_counts: Option, + /// A count of every photo running off the UI thread; the counts above are shown until it is done. + album_recount: Option, + /// The library, catalog revision and minute a count of every photo failed at: not tried again until one changes. + album_recount_failed: Option<(u64, u64, String)>, /// How often the album counts were made from every photo (tests check that unchanged frames, and edits to a /// photo or a few, don't). pub album_count_scans: usize, diff --git a/crates/ui-egui/src/panels/left/albums.rs b/crates/ui-egui/src/panels/left/albums.rs index 92498eb0233..3c732508bf5 100644 --- a/crates/ui-egui/src/panels/left/albums.rs +++ b/crates/ui-egui/src/panels/left/albums.rs @@ -63,9 +63,9 @@ fn albums_tree(app: &mut LightcraftApp, ui: &mut egui::Ui, all: &AlbumKids, pare } else { let sel = app.session.source == LibrarySource::Album(a.id); let icon = if a.is_smart() { Icon::SmartAlbum } else { Icon::Album }; - // cached: a smart album's count scans the catalog + // cached: a smart album's count scans the catalog (in the background: no number until it is known) let now = (app.session.clock)(); - let n = app.caches.album_counts(&app.session.catalog, &now).get(&a.id).copied().unwrap_or(0); + let n = app.caches.album_counts(&app.session.catalog, app.session.library_generation(), &now, ui.ctx()).get(&a.id).copied(); // the album B adds to is marked "+" let target = app.session.target_album.filter(|t| app.session.catalog.album(*t).is_some()).or_else(|| app.session.catalog.quick_collection()); @@ -74,7 +74,7 @@ fn albums_tree(app: &mut LightcraftApp, ui: &mut egui::Ui, all: &AlbumKids, pare let problems = app.caches.smart_album_problems(&app.session.catalog).get(&a.id).cloned().unwrap_or_default(); let label = if problems.is_empty() { label } else { format!("⚠ {label}") }; let mut resp = Row::new(&format!("album:{}", a.id.0), icon, &label) - .count(Some(n)) + .count(n) .selected(sel) .indent(indent) .sense(Sense::click_and_drag()) diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index 90cfc248f60..abd021aab3e 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -96,7 +96,7 @@ differences and missing bindings are in [ui-parity.md](ui-parity.md#shortcuts). | LR-LIB-BYDATE | Browse by date | P1 | ✅ | `cmd:library.filter` (`date`), `crates/ui-egui/src/panels/left.rs` (`date_row`), `crates/catalog/src/query.rs` (`date_groups`) | year → month → day tree with library-wide counts; a row filters the current source by that date. Active filters show as removable chips under the grid header (`crates/ui-egui/src/panels/chips.rs`, with “+N more” and Clear all), the header counts “N of M photos” (matching of the source's total), a badge on the top-bar filter icon counts them, and an empty result says no photos match the active filters | | LR-LIB-ALBUM | Albums | P0 | ✅ | `cmd:album.create`, `cmd:album.rename`, `cmd:album.delete`, `cmd:album.addPhotos`, `cmd:album.removePhotos`, `cmd:dialog.newAlbum`, `crates/engine/src/tests/albums_local.rs`, `crates/ui-egui/src/tests/panels.rs` | photos dragged from the grid onto an album row are added to it (LR-BEHAV-DRAGDROP); albums hold library photos (issue #684): `album.create {addSelected}`, `album.addPhotos` and `album.toggleTarget` (B) skip browsed Local photos and return `skipped` (a toast says so), a Local-only selection is an error and leaves Photo ▸ Add to Album, the grid's right-click Add to Album, a folder row's Add Selected Photos and a drop onto an album row off with the hint to Add to My Photos first (`button:contextAddToAlbum`, `button:contextAlbum:`); right-click a photo ▸ Add to Album lists the albums and ends with New Album…, which creates one holding the selection — also when the library has no album yet (issue #676; `button:contextNewAlbum`); New Album's "Include selected photos" (`check:albumIncludeSelected`, on by default; `dialog.newAlbum {includeSelected}`) leaves the selection out when unticked, and, as in Lightroom, is only shown when something is selected (never for a folder) | | LR-LIB-FOLDER | Folders of albums | P0 | ✅ | `cmd:album.create` (`folder`, `parent`), `cmd:album.move`, `cmd:album.reorder`, `cmd:album.sort`, `cmd:dialog.newAlbum` / `cmd:dialog.newFolder` / `cmd:dialog.smartAlbum` / `cmd:dialog.newSmartAlbum` (`parent`), `crates/ui-egui/src/panels/left.rs` (`albums_tree`, `folder_menu`, `disclosure_triangle`), `crates/ui-egui/src/tests/panels.rs` | Delete removes a folder and its nested albums as one undoable edit, keeps photos in the library and returns a deleted album view to All Photos (issue #501); folders nest and fold with the same disclosure triangle as Local / By Date / Folders / Keywords (`albumToggle:`; the row folds them too; open by default); right-click a folder ▸ New ▸ Create Album… / Create Smart Album… / Create Smart Album from Filter… / Create Folder… creates inside it (the `dialog.new*` commands take `parent`), opening the folders down to the new row; creating is only allowed inside folders; moving: drag an album or folder row onto a folder (outlined when allowed; a closed folder opens after 0.6 s under the pointer; the "Albums" header takes an item that sits in a folder back to the top level while it is dragged), the Move to menu or `album.move` — one undo step each; not onto a plain album, itself or something inside it; drop on the top / bottom half of an album or the edge of a folder to place it there by hand (`cmd:album.reorder`, a line shows the place; ordered per folder, folders stay first, new albums go after the ordered ones; right-click ▸ Sort Contents A–Z or + ▸ Sort Albums A–Z = `cmd:album.sort`) | -| LR-LIB-SMARTALBUM | Smart albums | P1 | ✅ | `cmd:album.createSmart`, `cmd:album.setRules`, `cmd:library.holdView`, `cmd:library.refresh`, `crates/catalog/src/query.rs`, `crates/ui-egui/src/panels/filterbar.rs`, `crates/ui-egui/src/lib.rs` (`album_counts`) | saved filters (rating/flag/label/kind/edited/keyword/camera/lens/date range/text/album) or a rule set from the rule editor (match all / any / none, nested groups; see LRC-LIB-SMARTCOLL), live; views and source counts with direct or nested relative-date rules expire on the session-clock minute; sidebar counts remain cached without building id lists; View ▸ Hold View Until Refreshed (`library.holdView`, off by default) keeps a photo that an edit or clock expiry made stop matching (a smart album, Picks, the filter bar) in the view until Refresh View, Reshuffle or another source, filter or sort, while newly matching photos enter at once | +| LR-LIB-SMARTALBUM | Smart albums | P1 | ✅ | `cmd:album.createSmart`, `cmd:album.setRules`, `cmd:library.holdView`, `cmd:library.refresh`, `crates/catalog/src/query.rs`, `crates/ui-egui/src/panels/filterbar.rs`, `crates/ui-egui/src/lib.rs` (`album_counts`) | saved filters (rating/flag/label/kind/edited/keyword/camera/lens/date range/text/album) or a rule set from the rule editor (match all / any / none, nested groups; see LRC-LIB-SMARTCOLL), live; views and source counts with direct or nested relative-date rules expire on the session-clock minute; sidebar counts remain cached without building id lists; an edit to a few photos is followed photo by photo (a keyword created in the keyword list too: no rule reads the list), and a count of every photo (an album's rules or photos changed, a stack, an edit to more than 256 photos) runs on a worker thread while the sidebar keeps the counts it showed (none before the first count), so the window doesn't freeze; View ▸ Hold View Until Refreshed (`library.holdView`, off by default) keeps a photo that an edit or clock expiry made stop matching (a smart album, Picks, the filter bar) in the view until Refresh View, Reshuffle or another source, filter or sort, while newly matching photos enter at once | | LR-LIB-SHARED-ALBUM | Shared albums | P2 | ⬜ | | needs a sharing service | | LR-LIB-OFFLINE | Keep album offline | P2 | 🚫 | | not applicable: local-first library | | LR-LIB-TARGET | Target album | P2 | ✅ | `cmd:album.setTarget`, `cmd:album.toggleTarget` | see LRC-LIB-COLLECTIONS | From 83f068807bf155d774241cabf6b89291093bc39f Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Sun, 25 Oct 2026 03:29:32 -0400 Subject: [PATCH 2/3] catalog: a failed keyword op no longer marks the keyword list as changed --- crates/catalog/src/lib.rs | 2 ++ crates/catalog/src/tests.rs | 7 +++++++ 2 files changed, 9 insertions(+) diff --git a/crates/catalog/src/lib.rs b/crates/catalog/src/lib.rs index 3225284c5f7..f9d37606cfd 100644 --- a/crates/catalog/src/lib.rs +++ b/crates/catalog/src/lib.rs @@ -628,6 +628,7 @@ impl Catalog { self.changes = Changes { floor: self.revision, seen: self.revision, ..Default::default() }; } let broad = self.changes.broad; + let keyword_list = self.changes.keyword_list; self.changes.torn = false; let inv = match self.apply_inner(op) { Ok(inv) => inv, @@ -649,6 +650,7 @@ impl Catalog { self.changes.touched.pop_back(); } self.changes.broad = broad; + self.changes.keyword_list = keyword_list; } return Err(e); } diff --git a/crates/catalog/src/tests.rs b/crates/catalog/src/tests.rs index fa71eb69bec..8f4dbbdb8f4 100644 --- a/crates/catalog/src/tests.rs +++ b/crates/catalog/src/tests.rs @@ -1006,6 +1006,13 @@ fn an_op_that_fails_leaves_no_touched_photos_behind() { assert_eq!(c.revision, start); assert_eq!(c.touched_since(start), Some(vec![])); assert_eq!(c.aspects_since(start), Some(Aspects::NONE)); + // a keyword op that fails, alone or inside a batch that is rolled back, does not say the keyword list changed + assert!(c.apply(Op::SetKeyword { path: " | ".into(), info: Some(Default::default()) }).is_err()); + assert_eq!(c.aspects_since(start), Some(Aspects::NONE)); + let ok = Op::SetKeyword { path: "travel|Rome".into(), info: Some(Default::default()) }; + assert!(c.apply(Op::Batch { ops: vec![ok, Op::SetRating { id: missing, rating: 1 }] }).is_err()); + assert_eq!(c.revision, start); + assert_eq!(c.aspects_since(start), Some(Aspects::NONE)); assert_eq!(c.photo(a).map(|p| p.rating), Some(0)); // a batch that ends in a failed removal of a photo that exists assert!(c.apply(Op::Batch { ops: vec![Op::RemovePhoto { id: b }, Op::RemovePhoto { id: b }] }).is_err()); From 9de93772a5f34ebe2c63f018bbfa1d514fe51944 Mon Sep 17 00:00:00 2001 From: Nathaniel Ledford Date: Fri, 30 Oct 2026 07:46:15 -0400 Subject: [PATCH 3/3] LR-LIB-SMARTALBUM: albums.list answers at once from the counts the sidebar keeps `albums.list` counted every smart album's photos on the UI thread (`AlbumTally::of`) before it answered: with 176 albums in a library of 844,425 photos the window did not respond for about 79 s. In the app the command now answers from the counts the sidebar keeps (counted on the `lc-album-counts` worker, followed through edits to a photo or a few): an album of chosen photos is counted from its list, a smart album's count is the kept one, and `countPending: true` says it is not of the catalog as it is now yet (the count made before, or 0). A session with no window (the CLI, the headless MCP server) counts once, keeps the counts and follows edits. --- crates/engine/src/album_counts.rs | 101 +++++++++++++++ crates/engine/src/cmd/query.rs | 33 ++++- crates/engine/src/lib.rs | 18 +++ crates/engine/src/tests.rs | 1 + crates/engine/src/tests/album_counts.rs | 120 +++++++++++++++++ crates/ui-egui/src/caches.rs | 35 ++++- crates/ui-egui/src/control.rs | 18 ++- crates/ui-egui/src/tests.rs | 1 + crates/ui-egui/src/tests/album_list.rs | 165 ++++++++++++++++++++++++ docs/control-protocol.md | 1 + docs/mcp.md | 6 + docs/parity-checklist.md | 3 +- docs/whats-new.md | 12 ++ 13 files changed, 503 insertions(+), 11 deletions(-) create mode 100644 crates/engine/src/album_counts.rs create mode 100644 crates/engine/src/tests/album_counts.rs create mode 100644 crates/ui-egui/src/tests/album_list.rs diff --git a/crates/engine/src/album_counts.rs b/crates/engine/src/album_counts.rs new file mode 100644 index 00000000000..3611c1cccb2 --- /dev/null +++ b/crates/engine/src/album_counts.rs @@ -0,0 +1,101 @@ +//! The photo counts `albums.list` answers with. +//! +//! Counting a smart album asks every photo whether its rules hold: seconds in a large library, and a window that does +//! it on its UI thread stops answering for that long. So a window offers the counts it keeps +//! ([`Session::offer_album_counts`]; they are counted on a worker thread) and `albums.list` counts nothing itself. +//! +//! With no window (the CLI, the MCP server, a script) there is no UI thread to stop, and the caller wants the numbers: +//! they are counted here, once, and kept. An edit to a photo or a few is followed photo by photo, as the sidebar's +//! are ([`AlbumTally::update`]); anything more counts every photo again. + +use std::collections::HashMap; +use std::sync::Arc; + +use lightcraft_catalog::tally::AlbumTally; +use lightcraft_catalog::{AlbumId, Catalog}; + +/// Every album's count, as `albums.list` takes them. +pub(crate) type Counts = Arc>; + +/// How far the counts a window keeps are from the catalog and the session clock as they are now. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CountsAge { + /// Of the catalog as it is now, and of this minute. + Current, + /// Of the catalog as it is now, but of an earlier minute: only a smart album whose rules ask about "the last N + /// days" (its own, or those of an album it tests) can have changed since. + ClockBehind, + /// Of an earlier catalog, or none yet: every smart album's count is behind. + Behind, +} + +/// Counts, and how current they are. +pub(crate) struct Answer { + pub counts: Counts, + pub age: CountsAge, +} + +/// The counts a session keeps for `albums.list`. +#[derive(Default)] +pub(crate) struct AlbumCounts { + /// What a window offered for the next `albums.list`. + offered: Option, + /// Counted here, when no window offers any. + kept: Option, + /// How often every photo was counted here (tests check that a repeated list, and an edit to a photo or a few, + /// don't). + pub scans: usize, +} + +/// The counts made here. +struct Kept { + /// The library they are of ([`Session::library_generation`]): album ids start again in every library. + library: u64, + /// The minute they are of while a smart album asks about "the last N days" (else empty). + minute: String, + tally: AlbumTally, + shown: Counts, +} + +impl AlbumCounts { + /// `albums.list` takes `counts` next, `age` being how far they are from the catalog and the clock as they are now. + pub fn offer(&mut self, counts: Counts, age: CountsAge) { + self.offered = Some(Answer { counts, age }); + } + + /// Nothing is offered any more. + pub fn withdraw(&mut self) { + self.offered = None; + } + + /// The counts for `albums.list`: the ones offered, else counted here (`now` is the session clock). + pub fn answer(&mut self, cat: &Catalog, library: u64, now: &str) -> Answer { + if let Some(offered) = self.offered.take() { + return offered; + } + let relative = cat.albums().any(|a| a.smart.as_ref().is_some_and(|f| f.depends_on_now())); + let minute = if relative { crate::clock_minute(now) } else { "" }; + if relative { + // "in the last N days" counts back from the session clock, as in the grid + lightcraft_catalog::rules::set_now(Some(now.to_string())); + } + let followed = self.kept.take().filter(|k| k.library == library && k.minute == minute).and_then(|mut k| { + if k.tally.revision() == cat.revision { + return Some(k); + } + k.tally.update(cat).then(|| { + k.shown = Arc::new(k.tally.counts().clone()); + k + }) + }); + let kept = followed.unwrap_or_else(|| { + self.scans += 1; + let tally = AlbumTally::of(cat); + let shown = Arc::new(tally.counts().clone()); + Kept { library, minute: minute.to_string(), tally, shown } + }); + let counts = kept.shown.clone(); + self.kept = Some(kept); + Answer { counts, age: CountsAge::Current } + } +} diff --git a/crates/engine/src/cmd/query.rs b/crates/engine/src/cmd/query.rs index a3926bc5144..8d11427b70f 100644 --- a/crates/engine/src/cmd/query.rs +++ b/crates/engine/src/cmd/query.rs @@ -7,7 +7,7 @@ use lightcraft_develop::{CONTROLS, controls}; use serde_json::{Value, json}; use super::{CommandSpec, always, bad, cmd, has_active}; -use crate::{LibrarySource, Session}; +use crate::{CountsAge, LibrarySource, Session}; pub fn photo_summary(p: &Photo) -> Value { json!({ @@ -38,21 +38,37 @@ pub fn photo_summary(p: &Photo) -> Value { /// instead of overflowing the stack. const MAX_ALBUM_DEPTH: usize = 64; -fn album_json(a: &Album, all: &[Album], counts: &HashMap, cat: &lightcraft_catalog::Catalog, depth: usize) -> Value { +/// The counts [`album_json`] shows a smart album with, and how far they are from the catalog and the clock as they are now. +struct AlbumCounts<'a> { + counts: &'a HashMap, + age: CountsAge, +} + +fn album_json(a: &Album, all: &[Album], counts: &AlbumCounts, cat: &lightcraft_catalog::Catalog, depth: usize) -> Value { let children: Vec = if depth < MAX_ALBUM_DEPTH { all.iter().filter(|c| c.parent == Some(a.id)).map(|c| album_json(c, all, counts, cat, depth + 1)).collect() } else { Vec::new() }; + // An album of chosen photos is counted from its list, at once; a smart album's rules are asked of every photo, so + // its count is the one kept. + let count = if a.is_smart() { counts.counts.get(&a.id).copied().unwrap_or(0) } else { cat.album_count(a.id) }; let mut v = json!({ "id": a.id.0, "name": a.name, "folder": a.folder, - "count": counts.get(&a.id).copied().unwrap_or(0), + "count": count, "cover": a.cover.map(|c| c.0), "children": children, }); if let Some(rules) = &a.smart { + // Behind the catalog (an edit counted by every photo is under way), or behind the clock for an album whose rules + // ask about "the last N days": the count is the one before (0 before any), and the real one is being worked out. + v["countPending"] = json!(match counts.age { + CountsAge::Current => false, + CountsAge::ClockBehind => crate::filter_depends_on_clock(rules, cat), + CountsAge::Behind => true, + }); v["smart"] = json!(true); v["rules"] = serde_json::to_value(rules).unwrap_or_default(); v["rulesText"] = json!(rules.describe_with(cat)); @@ -152,11 +168,14 @@ pub fn specs() -> Vec { .unwrap_or_default(); Ok(json!({"exif": exif, "xmp": xmp})) }), - cmd!(query "albums.list", "List Albums", [], None, "{}", always, |s, _| { + cmd!(query "albums.list", "List Albums", [], None, "{} → [{id, name, folder, count, cover, children, smart?, rules?, rulesText?, problems?, countPending?}] — a smart album's `count` comes from the counts kept (`countPending: true`: not of the catalog as it is now yet, the ones before or 0)", always, |s, _| { let all: Vec = s.catalog.albums().cloned().collect(); - // every album counted in one pass, so a smart album tested by others is worked out once - let counts = lightcraft_catalog::tally::AlbumTally::of(&s.catalog); - Ok(Value::Array(all.iter().filter(|a| a.parent.is_none()).map(|a| album_json(a, &all, counts.counts(), &s.catalog, 0)).collect())) + // counted nowhere here when a window keeps the counts; else every album in one pass, so a smart album tested + // by others is worked out once, and kept + let (now, library) = ((s.clock)(), s.library_generation()); + let counted = s.album_counts.answer(&s.catalog, library, &now); + let counts = AlbumCounts { counts: &counted.counts, age: counted.age }; + Ok(Value::Array(all.iter().filter(|a| a.parent.is_none()).map(|a| album_json(a, &all, &counts, &s.catalog, 0)).collect())) }), cmd!(query "photo.inspect", "Inspect Photo", [], None, "{id?}", always, |s, p| { let id = photo_arg(s, p, "photo.inspect")?; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index acaa1807009..7109a5a45bc 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -15,6 +15,7 @@ extern crate lightcraft_denoise_core as lightcraft_denoise; pub mod activity; +mod album_counts; #[cfg(not(target_arch = "wasm32"))] pub mod apple_photos; pub mod availability; @@ -85,6 +86,7 @@ pub mod walk; use std::sync::Arc; +pub use album_counts::CountsAge; pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command}; pub use errors::{AiModel, ErrorKind}; pub use fonts::{CRAFT_FONTS, CraftFont}; @@ -226,6 +228,8 @@ static LIBRARY_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64: pub struct Session { library_generation: u64, + /// The counts `albums.list` answers with. + album_counts: album_counts::AlbumCounts, /// Auto Sync: edits to the active photo also change the other selected photos (the settings /// that changed, nothing else). pub auto_sync: bool, @@ -444,9 +448,23 @@ impl Session { self.library_generation } + /// The next `albums.list` answers with `counts` and counts nothing itself: a window that keeps the albums' counts + /// (counted off its UI thread) offers them with how far they are from the catalog and the clock as they are now, + /// and `albums.list` marks the smart albums whose count is behind as pending. + /// [`Session::withdraw_album_counts`] takes the offer back once the command has run. + pub fn offer_album_counts(&mut self, counts: Arc>, age: CountsAge) { + self.album_counts.offer(counts, age); + } + + /// Take back what [`Session::offer_album_counts`] offered, if `albums.list` didn't use it. + pub fn withdraw_album_counts(&mut self) { + self.album_counts.withdraw(); + } + pub fn new() -> Session { Session { library_generation: LIBRARY_GEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed), + album_counts: album_counts::AlbumCounts::default(), auto_sync: false, catalog: Catalog::new(), source: LibrarySource::All, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ae03859d21f..9f817c6269d 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2,6 +2,7 @@ use serde_json::{Value, json}; use crate::{Selection, Session, command_specs}; +mod album_counts; mod album_order; mod album_remove; mod albums_local; diff --git a/crates/engine/src/tests/album_counts.rs b/crates/engine/src/tests/album_counts.rs new file mode 100644 index 00000000000..9f7ec9e6944 --- /dev/null +++ b/crates/engine/src/tests/album_counts.rs @@ -0,0 +1,120 @@ +//! `albums.list` and the smart albums' counts: a window offers the counts it keeps and the command counts nothing +//! (listing them pending when they aren't of the catalog as it is now); a session with no window counts every photo +//! once and follows edits to a few. + +use std::sync::{Arc, Mutex}; + +use lightcraft_catalog::{AlbumId, Op, Photo, PhotoId, Source}; +use serde_json::{Value, json}; + +use crate::{CountsAge, Session}; + +fn photo(id: u64, captured: &str, rating: u8) -> Op { + let mut p = Photo::new(PhotoId(id), Source::Demo { scene: 0 }, &format!("p{id}.jpg"), "JPEG", 60, 40, "2026-01-01T00:00:00"); + p.captured = Some(captured.into()); + p.rating = rating; + Op::AddPhoto { photo: Box::new(p) } +} + +fn library(ratings: &[u8]) -> Session { + let mut s = Session::new(); + for (i, r) in ratings.iter().enumerate() { + s.catalog.apply(photo(i as u64 + 1, "2026-09-30T11:59:30", *r)).unwrap(); + } + s +} + +fn listed(s: &mut Session, id: u64) -> Value { + let list = s.execute("albums.list", &json!({})).unwrap(); + list.as_array().unwrap().iter().find(|a| a["id"] == id).cloned().unwrap() +} + +fn smart(s: &mut Session, name: &str, rules: Value) -> u64 { + s.execute("album.createSmart", &json!({"name": name, "rules": rules})).unwrap()["id"].as_u64().unwrap() +} + +/// Without a window the command counts every photo once, keeps the counts, and follows an edit to a photo from them. +#[test] +fn without_a_window_the_albums_are_counted_once_and_edits_to_a_photo_are_followed() { + let mut s = library(&[5, 1, 1, 4]); + let good = smart(&mut s, "Good", json!({"rating": 4})); + let picked = s.execute("album.create", &json!({"name": "Picked", "addSelected": false})).unwrap()["id"].as_u64().unwrap(); + s.execute("library.select", &json!({"ids": [1, 2]})).unwrap(); + s.execute("album.addPhotos", &json!({"id": picked, "ids": [1, 2]})).unwrap(); + assert_eq!(s.album_counts.scans, 0); + + let a = listed(&mut s, good); + assert_eq!((a["count"].as_u64(), a["countPending"].as_bool()), (Some(2), Some(false)), "{a}"); + assert_eq!(listed(&mut s, picked)["count"], 2); + assert_eq!(s.album_counts.scans, 1); + listed(&mut s, good); + assert_eq!(s.album_counts.scans, 1, "listed again: nothing changed, nothing counted"); + + s.execute("library.select", &json!({"ids": [2]})).unwrap(); + s.execute("photo.rate", &json!({"ids": [2], "rating": 5})).unwrap(); + assert_eq!(listed(&mut s, good)["count"], 3, "the edit is in the count"); + assert_eq!(s.album_counts.scans, 1, "followed from the photo it touched"); + + s.execute("album.setRules", &json!({"id": good, "rules": {"rating": 5}})).unwrap(); + let a = listed(&mut s, good); + assert_eq!((a["count"].as_u64(), a["countPending"].as_bool()), (Some(2), Some(false)), "{a}"); + assert_eq!(s.album_counts.scans, 2, "new rules ask every photo again"); + assert_eq!(a["count"].as_u64().unwrap(), s.catalog.album_count(AlbumId(good)) as u64); +} + +/// The counts a window offers are used as they are, once, with nothing counted here; a smart album is pending when the +/// window says they aren't of the catalog as it is now, or (for an album asking about "the last N days") of this minute. +#[test] +fn counts_a_window_offers_are_listed_with_nothing_counted_here() { + let mut s = library(&[5, 1, 1, 4]); + s.clock = Box::new(|| "2026-09-30T12:00:00".to_string()); + let good = smart(&mut s, "Good", json!({"rating": 4})); + let recent_rules = json!({"ruleSet": {"rules": [{"field": "captureDate", "op": "inLast", "value": {"n": 1, "unit": "hours"}}]}}); + let recent = smart(&mut s, "Recent", recent_rules); + let offered = Arc::new(std::collections::HashMap::from([(AlbumId(good), 7), (AlbumId(recent), 8)])); + let counts_and_flags = |s: &mut Session| -> Vec<(u64, bool)> { + let list = s.execute("albums.list", &json!({})).unwrap(); + list.as_array().unwrap().iter().map(|a| (a["count"].as_u64().unwrap(), a["countPending"].as_bool().unwrap())).collect() + }; + + s.offer_album_counts(offered.clone(), CountsAge::Behind); + assert_eq!(counts_and_flags(&mut s), [(7, true), (8, true)]); + assert_eq!(s.album_counts.scans, 0, "nothing is counted for an offer"); + + s.offer_album_counts(offered.clone(), CountsAge::Current); + assert_eq!(counts_and_flags(&mut s), [(7, false), (8, false)]); + assert_eq!(s.album_counts.scans, 0); + + // a count of an earlier minute is behind only for the album whose rules ask about the clock + s.offer_album_counts(offered, CountsAge::ClockBehind); + assert_eq!(counts_and_flags(&mut s), [(7, false), (8, true)]); + assert_eq!(s.album_counts.scans, 0); + + // used once: the next answer is the session's own + assert_eq!(counts_and_flags(&mut s), [(2, false), (4, false)]); + assert_eq!(s.album_counts.scans, 1); + + // and an offer not used is taken back + s.offer_album_counts(Arc::new(Default::default()), CountsAge::Behind); + s.withdraw_album_counts(); + assert_eq!(counts_and_flags(&mut s), [(2, false), (4, false)]); +} + +/// "In the last hour" counts back from the session clock: the counts kept are of its minute, so an hour later they +/// are counted again though the catalog didn't change. +#[test] +fn counts_of_albums_asking_about_the_last_hour_follow_the_session_clock() { + let mut s = library(&[1]); + let now = Arc::new(Mutex::new("2026-09-30T12:00:00".to_string())); + let clock = now.clone(); + s.clock = Box::new(move || clock.lock().unwrap().clone()); + let rules = json!({"ruleSet": {"rules": [{"field": "captureDate", "op": "inLast", "value": {"n": 1, "unit": "hours"}}]}}); + let recent = smart(&mut s, "Recent", rules); + assert_eq!(listed(&mut s, recent)["count"], 1); + assert_eq!(listed(&mut s, recent)["count"], 1); + assert_eq!(s.album_counts.scans, 1, "the same minute"); + *now.lock().unwrap() = "2026-09-30T13:00:10".into(); + assert_eq!(listed(&mut s, recent)["count"], 0, "an hour later the photo is out of it"); + assert_eq!(s.album_counts.scans, 2); + lightcraft_catalog::rules::set_now(None); +} diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 13ab8031dd3..db718c265c3 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -372,8 +372,7 @@ impl Caches { now: &str, ctx: &egui::Context, ) -> std::sync::Arc> { - let relative = cat.albums().any(|a| a.smart.as_ref().is_some_and(|f| f.depends_on_now())); - let minute = if relative { now.get(..16).unwrap_or(now) } else { "" }; + let (relative, minute) = Self::album_clock(cat, now); self.collect_album_recount(library); // (album ids start again in every library: another one's counts would be shown on this one's albums) if self.album_counts.as_ref().is_some_and(|c| c.library != library) { @@ -398,6 +397,38 @@ impl Caches { self.album_counts.as_ref().map(|c| c.shown.clone()).unwrap_or_default() } + /// Whether a smart album asks about "the last N days", and the minute the counts are of then (else empty). + fn album_clock<'a>(cat: &lightcraft_catalog::Catalog, now: &'a str) -> (bool, &'a str) { + let relative = cat.albums().any(|a| a.smart.as_ref().is_some_and(|f| f.depends_on_now())); + (relative, if relative { now.get(..16).unwrap_or(now) } else { "" }) + } + + /// [`Caches::album_counts`] for the `albums.list` command, with how far they are from the catalog and the clock as + /// they are now: the command answers at once from them (marking the albums that are behind), and never counts a + /// photo on the UI thread. + pub fn album_counts_for_list( + &mut self, + cat: &lightcraft_catalog::Catalog, + library: u64, + now: &str, + ctx: &egui::Context, + ) -> (std::sync::Arc>, lightcraft_engine::CountsAge) { + use lightcraft_engine::CountsAge; + let counts = self.album_counts(cat, library, now, ctx); + let (_, minute) = Self::album_clock(cat, now); + let age = match self.album_counts.as_ref() { + Some(c) if c.library == library && c.tally.revision() == cat.revision => { + if c.minute == minute { + CountsAge::Current + } else { + CountsAge::ClockBehind + } + } + _ => CountsAge::Behind, + }; + (counts, age) + } + /// A count of every photo is running ([`Caches::album_counts`]). pub fn album_recount_running(&self) -> bool { self.album_recount.as_ref().is_some_and(|job| !job.worker.is_finished()) diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index caacbc59088..449e6c42e9e 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -318,6 +318,22 @@ pub(crate) fn widget_target_visible(ctx: &egui::Context, hit: Option Result { + if id != "albums.list" { + return app.run(id, params); + } + let now = (app.session.clock)(); + let (counts, age) = app.caches.album_counts_for_list(&app.session.catalog, app.session.library_generation(), &now, ctx); + app.session.offer_album_counts(counts, age); + let r = app.run(id, params); + app.session.withdraw_album_counts(); + r +} + /// Dispatch one control request: run engine commands, list menus/widgets, inspect state, queue /// file drops and synthetic input, capture screenshots, or return an error for an unknown or /// invalid request. Requests that need fresh widget geometry are queued as `Outcome` values. @@ -329,7 +345,7 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest "engine.execute" | "ui.menu.invoke" | "command" => { let Some(id) = s("command").or(s("id")) else { return err("missing `command`") }; let params = p.get("params").cloned().filter(|v| !v.is_null()).unwrap_or(json!({})); - let r = app.run(id, params); + let r = run_command(app, ctx, id, params); ctx.request_repaint(); wrap(r) } diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 3a102a29a90..b4be41656c3 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -1,4 +1,5 @@ mod activity; +mod album_list; mod album_picker; mod album_remove; mod appearance; diff --git a/crates/ui-egui/src/tests/album_list.rs b/crates/ui-egui/src/tests/album_list.rs new file mode 100644 index 00000000000..9037a1736ef --- /dev/null +++ b/crates/ui-egui/src/tests/album_list.rs @@ -0,0 +1,165 @@ +//! `albums.list` answers at once from the counts the sidebar keeps: it never counts a smart album's photos on the UI +//! thread (in a large library that is seconds in which the window doesn't answer). A count that isn't of the catalog +//! as it is now is listed as pending (`countPending`), and the ones the sidebar follows through small edits are current +//! at once. + +use std::time::{Duration, Instant}; + +use lightcraft_catalog::{AlbumId, Op, Photo, PhotoId, Source}; +use serde_json::{Value, json}; + +use crate::control::{ControlRequest, Outcome}; +use crate::{LightcraftApp, Services}; + +/// A library of `photos` photos rated 0 to 5 in turn, and no frame drawn: nothing has counted its albums yet. +fn app(photos: u64) -> LightcraftApp { + let mut session = lightcraft_engine::Session::new(); + for i in 1..=photos { + let mut p = Photo::new(PhotoId(i), Source::Demo { scene: 0 }, &format!("p{i}.jpg"), "JPEG", 60, 40, "2026-01-01T00:00:00"); + p.rating = (i % 6) as u8; + session.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap(); + } + LightcraftApp::new(session, Services { png: None, ..Default::default() }) +} + +/// `albums.list` as the control channel runs it. +fn list(app: &mut LightcraftApp, ctx: &egui::Context) -> Vec { + let (req, _) = ControlRequest::new("engine.execute", json!({"command": "albums.list"})); + let Outcome::Done(reply) = crate::control::handle(app, ctx, &req) else { panic!("expected a reply") }; + assert_eq!(reply["ok"], true, "{reply}"); + reply["result"].as_array().unwrap().clone() +} + +fn run(app: &mut LightcraftApp, command: &str, params: Value) -> Value { + app.run(command, params).unwrap_or_else(|e| panic!("{command}: {e}")) +} + +fn album(listed: &[Value], id: u64) -> &Value { + listed.iter().find(|a| a["id"] == id).unwrap_or_else(|| panic!("no album {id} in {listed:?}")) +} + +/// Ask again until the smart album `id` is no longer pending (its count of every photo is done and taken). +fn settled(app: &mut LightcraftApp, ctx: &egui::Context, id: u64) -> Vec { + let t0 = Instant::now(); + loop { + let listed = list(app, ctx); + if album(&listed, id)["countPending"] == false { + return listed; + } + assert!(t0.elapsed() < Duration::from_secs(60), "the count of every photo ends"); + std::thread::sleep(Duration::from_millis(1)); + } +} + +fn smart(app: &mut LightcraftApp, name: &str, rules: Value) -> u64 { + run(app, "album.createSmart", json!({"name": name, "rules": rules}))["id"].as_u64().unwrap() +} + +fn count_of(app: &LightcraftApp, id: u64) -> u64 { + app.session.catalog.album_count(AlbumId(id)) as u64 +} + +/// The first answer lists every album without counting the smart albums' photos (they are pending, and counted on a +/// worker); an album of chosen photos is exact at once; the next answers are current, and no photo is counted again. +#[test] +fn the_albums_are_listed_at_once_with_the_smart_albums_counts_pending_until_counted() { + let mut app = app(3000); + let ctx = egui::Context::default(); + let four = smart(&mut app, "Four stars or more", json!({"rating": 4})); + let five = smart(&mut app, "Five stars", json!({"rating": 5})); + let picked = run(&mut app, "album.create", json!({"name": "Picked", "addSelected": false}))["id"].as_u64().unwrap(); + run(&mut app, "library.select", json!({"ids": [1, 2, 3]})); + run(&mut app, "album.addPhotos", json!({"id": picked, "ids": [1, 2, 3]})); + assert_eq!(app.caches.album_count_scans, 0, "nothing counted yet"); + + let first = list(&mut app, &ctx); + for id in [four, five] { + assert_eq!(album(&first, id)["countPending"], true, "a smart album's count isn't known at the first answer: {first:?}"); + assert_eq!(album(&first, id)["count"], 0, "no count of an earlier catalog to show"); + } + assert_eq!(album(&first, picked)["count"], 3, "an album of chosen photos is counted from its list"); + assert!(album(&first, picked).get("countPending").is_none(), "it has nothing to wait for"); + assert_eq!(app.caches.album_count_scans, 1, "every photo is being counted, once, elsewhere"); + + let settled = settled(&mut app, &ctx, four); + assert_eq!(album(&settled, four)["count"], count_of(&app, four)); + assert_eq!(album(&settled, five)["count"], count_of(&app, five)); + assert_eq!(album(&settled, five)["countPending"], false); + assert_eq!(app.caches.album_count_scans, 1, "the answers since counted nothing"); +} + +/// An edit to a photo is followed from the counts kept, so the answer is current at once; new rules count every photo +/// again on the worker, and until that is done the answer lists the count it had, pending. +#[test] +fn an_edit_to_a_photo_is_followed_and_new_rules_leave_the_old_count_pending() { + let mut app = app(3000); + let ctx = egui::Context::default(); + let four = smart(&mut app, "Four stars or more", json!({"rating": 4})); + list(&mut app, &ctx); + let before = album(&settled(&mut app, &ctx, four), four)["count"].as_u64().unwrap(); + assert_eq!(before, count_of(&app, four)); + + // a photo rated 5: one more + run(&mut app, "library.select", json!({"ids": [2]})); + run(&mut app, "photo.rate", json!({"ids": [2], "rating": 5})); + let after = list(&mut app, &ctx); + assert_eq!(album(&after, four)["countPending"], false, "a small edit is followed at once"); + assert_eq!(album(&after, four)["count"].as_u64().unwrap(), before + 1); + assert_eq!(app.caches.album_count_scans, 1, "without counting every photo again"); + + // new rules: the count shown stays the one before until the new one is made + run(&mut app, "album.setRules", json!({"id": four, "rules": {"rating": 5}})); + let changed = list(&mut app, &ctx); + assert_eq!(album(&changed, four)["countPending"], true, "{changed:?}"); + assert_eq!(album(&changed, four)["count"].as_u64().unwrap(), before + 1, "the count of the rules before"); + let done = settled(&mut app, &ctx, four); + assert_eq!(album(&done, four)["count"], count_of(&app, four)); + assert_eq!(app.caches.album_count_scans, 2, "every photo was counted again, for the new rules only"); +} + +/// A new minute puts only the albums whose rules ask about "the last N days" behind (the catalog didn't change, so the +/// other counts are exact), and they are counted again on the worker like any other count behind. +#[test] +fn a_new_minute_leaves_only_the_albums_asking_about_the_last_hour_pending() { + let mut app = app(300); + let ctx = egui::Context::default(); + let clock_at = |app: &mut LightcraftApp, now: &'static str| app.session.clock = Box::new(move || now.to_string()); + clock_at(&mut app, "2026-09-30T12:00:00"); + let four = smart(&mut app, "Four stars or more", json!({"rating": 4})); + let rules = json!({"ruleSet": {"rules": [{"field": "captureDate", "op": "inLast", "value": {"n": 1, "unit": "hours"}}]}}); + let recent = smart(&mut app, "Recent", rules); + list(&mut app, &ctx); + let first = settled(&mut app, &ctx, recent); + assert_eq!((album(&first, four)["countPending"].as_bool(), album(&first, recent)["countPending"].as_bool()), (Some(false), Some(false))); + assert_eq!(app.caches.album_count_scans, 1); + + clock_at(&mut app, "2026-09-30T12:01:10"); + let later = list(&mut app, &ctx); + assert_eq!(album(&later, four)["countPending"], false, "no rule of it asks about the clock: {later:?}"); + assert_eq!(album(&later, recent)["countPending"], true, "its count is of the minute before: {later:?}"); + let done = settled(&mut app, &ctx, recent); + assert_eq!(album(&done, recent)["count"], count_of(&app, recent)); + assert_eq!(app.caches.album_count_scans, 2, "every photo was counted again for the new minute"); + lightcraft_catalog::rules::set_now(None); +} + +/// In a large library with many smart albums the answer comes in a fraction of the time it takes to count the albums +/// once (what it did, on the UI thread, before). +#[test] +fn listing_the_albums_of_a_large_library_takes_a_fraction_of_counting_them() { + let mut app = app(60_000); + let ctx = egui::Context::default(); + for i in 0..12 { + smart(&mut app, &format!("Rated {i}"), json!({"rating": i % 5 + 1})); + } + let counted = Instant::now(); + let tally = lightcraft_catalog::tally::AlbumTally::of(&app.session.catalog); + let counting = counted.elapsed(); + assert_eq!(tally.counts().len(), 12); + + let listed = Instant::now(); + let first = list(&mut app, &ctx); + let listing = listed.elapsed(); + assert!(first.iter().all(|a| a["countPending"] == true), "{first:?}"); + assert!(listing < counting / 2, "listing took {listing:?}, counting every album once takes {counting:?}"); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 36294c78756..9bf79b721ba 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -98,6 +98,7 @@ filmstrip is visible. | `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: "albums.list"}` | — | The albums as a tree: `[{id, name, folder, count, cover, children}]`, a smart album also with `smart`, `rules`, `rulesText`, `problems` and `countPending`. It answers at once and counts no photo on the UI thread: an album of chosen photos is counted from its list, and a smart album's `count` is the one the sidebar keeps (counted on a worker thread, followed through edits to a photo or a few). `countPending: true` says that count isn't of the library as it is now yet: it is the count made before (0 when there is none) while the app counts every photo again (after new rules, an edit to many photos, or a library just opened; and, for an album whose rules ask about "the last N days" (its own, or those of an album it tests), each time the clock moves into a new minute — the other albums stay exact then). Ask again a moment later: the album's `countPending` is `false` once its count is done. While a library has such an album and counting every photo takes longer than a minute, that album stays pending, and so does every smart album after an edit made during the count; a count that failed (it is logged) stays pending until the library changes. The app answers this way (also to `lightcraft-cli snapshot --script`, where `ui.settle` first waits for the count); `lightcraft-cli run` without `--connect` and the headless MCP server have no window to keep up: they count every photo once, keep the counts and follow edits, so their answers are never pending | | `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` | diff --git a/docs/mcp.md b/docs/mcp.md index 2c155e72c07..8dbcec3013e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -232,6 +232,12 @@ sequence in a folder, or an AV1 video (no audio). It runs in the background and `cmd_slideshow_exportStatus` gives the result (`pages`, `files`, or `frames` / `samples` / `seconds` for video) or the error. With `wait: true` the call blocks and replies with the result. +`cmd_albums_list` lists the albums with their photo counts. Connected to the desktop app it answers at once from the +counts the sidebar keeps, and a smart album whose count isn't of the library as it is now yet (it is being counted +again after new rules, an edit to many photos or a library just opened, or, for an album asking about "the last N days" +itself or through an album it tests, a new minute) has `countPending: true` with the count made before (0 if none): ask +again a moment later. Headless, the counts are made on the first call, kept, and never pending. + ### Preview-only raws after an update A raw LightCraft couldn't decode when it was imported is shown from its embedded preview diff --git a/docs/parity-checklist.md b/docs/parity-checklist.md index abd021aab3e..c84eb2ed05c 100644 --- a/docs/parity-checklist.md +++ b/docs/parity-checklist.md @@ -1,6 +1,6 @@ # Lightroom parity checklist -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-25 · **Change:** minor (LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-30 · **Change:** minor (LR-LIB-SMARTALBUM: `albums.list` answers at once from the counts the sidebar keeps and marks a smart album's count pending while every photo is counted again; LR-BEHAV-TITLEBAR: a double-click follows the system setting, and a panel over the bar keeps the window still; KEYC-METADATA, LRC-LIB-KEYWORDS: ⌥0 / ⌥⇧0 go to the next / previous keyword set; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings; KEYC-METADATA: ⌘K / Ctrl+K Add Keywords; LRC-DEV-HISTOGRAM-DRAG: the histogram's five tonal zones — hover for the value, drag to adjust the Basic control the press locked, double-click to reset; LR-VIEW-HISTOGRAM note updated; MENU-BAR: on macOS a menu item that yields its key to a focused text field or to shortcut recording really lets it go; LR-MERGE-HDR / LR-MERGE-PANO: Lanczos-3 warps; LR-IMP-LOCAL: browsing from the sidebar records the folder; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LR-IMP-ADD-DIALOG: hierarchical import album destination reconciled with main, #2362; KEY-SLIDER-NUDGE: vertical wheel nudges need a click or drag in the row; leaving it disarms them; LR-EDIT-OPTICS-PROFILE: Fujifilm nine-knot lens tables read at the plain radius; LR-VIEW-ZOOM: only a full-size drag within 20 ms clears a slow-drag verdict; LRC-LIB-LIBFOLDERS, LR-BEHAV-BG-TASKS: Synchronize Folder's scan shows its folder listing and stops it on ✕; LRC-LIB-LIBFOLDERS: Synchronize Folder says a folder is up to date; LR-LIB-STACK: filmstrip stack badge click; LRC-LIB-REFVIEW / CATALOG-SWITCH: Escape preserves edits; catalog-local pins; deleted and malformed references refused; LRC-LIB-COMPARE: the Info panel labels the active photo while culling, #2398; KEYC-RATING: `\` shows / hides the Filter Bar in the grids; LR-VIEW-PHOTOGRID: the grid reads only the photos an import batch or an edit touched, not the whole list; earlier: LRC-PRINT-PAGE: Print Page Options; LR-META-XMP: fewer false unimported-XMP warnings) · **Target:** Adobe Lightroom Classic 15.5 / Lightroom 9.6 The measured, row-by-row checklist: one row per Lightroom feature, menu item and shortcut, what we have and what is missing. It answers *does the feature exist?* (feature breadth). Whether it is good @@ -959,3 +959,4 @@ Latin stays upright. Advanced Japanese composition remains open. Regression cove | 2026-10-23 | patch | LR-BEHAV-ACCESS: the name field of New Album, New Smart Album, Rename and the other one-field dialogs takes the keyboard focus once when the dialog opens instead of every frame, so Tab and Shift+Tab reach the check box, Cancel and OK; status unchanged (🟡) | | 2026-10-22 | minor | LR-CROP-AUTO: Auto straighten turns by at most 10° and only on at least 3 agreeing lines, and says when it finds nothing to level by; measured on 68 photos straightened by hand and 300 left as shot, unwanted turns of more than 1° fell from 79 to 19 of the 300. Downgraded ✅ → 🟡: it still leaves most tilted photos alone | | 2026-10-23 | patch | LRC-LIB-FILTERBAR: showing an album (`library.source`) while the filter holds an album drops the filter's album, as showing a library folder already dropped its folder filter; before, the old album stayed in the filter unseen (the filter bar has no album chip) and narrowed the next source such as All Photos; the row's note says so; status unchanged (✅) | +| 2026-10-30 | patch | LR-LIB-SMARTALBUM: `albums.list` answers at once from the counts the sidebar keeps (counted on a worker thread) instead of counting every smart album's photos on the UI thread, and marks a smart album's count `countPending` while every photo is counted again; a session with no window (the CLI, the headless MCP server) counts once, keeps the counts and follows edits; status unchanged (✅) | diff --git a/docs/whats-new.md b/docs/whats-new.md index c6c25920034..656ed97d001 100644 --- a/docs/whats-new.md +++ b/docs/whats-new.md @@ -1,5 +1,17 @@ # What's new in LightCraft +## 2026-10-30 + +### `albums.list` no longer freezes the window in a large library +- The `albums.list` command (also reached as `cmd_albums_list` through MCP when connected to the app) used to count every + smart album's photos on the window's thread before it answered: with many smart albums in a large library, seconds + in which the window did not respond. It now answers at once from the counts the Albums list in the sidebar keeps. + A smart album whose count is not of the library as it is now yet (new rules, an edit to many photos, a library just + opened, or a new minute for an album asking about “the last N days”, itself or through an album it tests) has + `countPending: true`, with the count made before (0 if there is none); ask again a moment later. A script or MCP + client with no window (`lightcraft-cli run`, the headless MCP server) gets the counts counted once and kept, followed + through edits to a few photos instead of counted again with every call. + ## 2026-10-24 ### Relative-date filters and smart albums follow the clock