LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust
Issue #182: library.select and id queries reject a photo id that is not in the library
wstockf7c0b9e49f6b
diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rsindex 57632ea82..950dc421e 100644--- a/crates/engine/src/cmd/library.rs+++ b/crates/engine/src/cmd/library.rs@@ -356,36 +356,50 @@ pub fn specs() -> Vec<CommandSpec> {}),// ---- selection- cmd!("library.select", "Select Photos", [], None, "{ids: [id], active?: id, mode?: replace|add|toggle|range}", always, |s, p| {- let ids = ids_param(p).unwrap_or_default();- let mode = str_param(p, "mode").unwrap_or("replace");- s.end_interaction()?;- match mode {- "replace" => {- s.selection =- Selection { ids: ids.clone(), active: p.get("active").and_then(Value::as_u64).map(PhotoId).or(ids.first().copied()) };+ cmd!(+ "library.select",+ "Select Photos",+ [],+ None,+ "{ids: [id], active?: id, mode?: replace|add|toggle|range} — every id must be a photo of the library",+ always,+ |s, p| {+ let ids = ids_param(p).unwrap_or_default();+ let active = p.get("active").and_then(Value::as_u64).map(PhotoId);+ let mode = str_param(p, "mode").unwrap_or("replace");+ // An id that is not in the library is an error, and the selection stays as it was:+ // selecting it would otherwise report success and leave the session with no usable+ // active photo (#182).+ if let Some(id) = ids.iter().chain(active.as_ref()).find(|id| s.catalog.photo(**id).is_none()) {+ return Err(bad("library.select", format!("no such photo {}", id.0)));}- "add" => {- for id in ids {- if !s.selection.contains(id) {- s.selection.ids.push(id);+ s.end_interaction()?;+ match mode {+ "replace" => {+ s.selection = Selection { ids: ids.clone(), active: active.or(ids.first().copied()) };+ }+ "add" => {+ for id in ids {+ if !s.selection.contains(id) {+ s.selection.ids.push(id);+ }+ s.selection.active = Some(id);}- s.selection.active = Some(id);}- }- "toggle" => ids.into_iter().for_each(|id| s.selection.toggle(id)),- "range" => {- let vis = s.visible_cloned();- if let Some(id) = ids.first() {- s.selection.extend_to(*id, &vis);+ "toggle" => ids.into_iter().for_each(|id| s.selection.toggle(id)),+ "range" => {+ let vis = s.visible_cloned();+ if let Some(id) = ids.first() {+ s.selection.extend_to(*id, &vis);+ }}+ other => return Err(bad("library.select", format!("unknown mode `{other}`"))),}- other => return Err(bad("library.select", format!("unknown mode `{other}`"))),+ s.active_mask = None;+ s.active_spot = None;+ Ok(json!({"selected": s.selection.ids.len()}))}- s.active_mask = None;- s.active_spot = None;- Ok(json!({"selected": s.selection.ids.len()}))- }),+ ),cmd!("library.selectAll", "Select All", ["Edit"], Some("Cmd+A"), "{}", always, |s, _| {let vis = s.visible_cloned();s.selection = Selection { active: s.selection.active.filter(|a| vis.contains(a)).or(vis.first().copied()), ids: vis };diff --git a/crates/engine/src/cmd/query.rs b/crates/engine/src/cmd/query.rsindex e7ffde143..3b794e38a 100644--- a/crates/engine/src/cmd/query.rs+++ b/crates/engine/src/cmd/query.rs@@ -48,8 +48,13 @@ fn album_json(a: &Album, all: &[Album], cat: &lightcraft_catalog::Catalog) -> Vav}+/// The photo a query is about: `id` when given (which must be in the library), else the active one.fn photo_arg(s: &Session, p: &Value, c: &str) -> crate::Result<PhotoId> {- p.get("id").and_then(Value::as_u64).map(PhotoId).or(s.active()).ok_or_else(|| bad(c, "no photo"))+ match p.get("id").and_then(Value::as_u64).map(PhotoId) {+ Some(id) if s.catalog.photo(id).is_some() => Ok(id),+ Some(id) => Err(bad(c, format!("no such photo {}", id.0))),+ None => s.active().ok_or_else(|| bad(c, "no photo")),+ }}pub fn specs() -> Vec<CommandSpec> {diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex d005d5082..3978258fe 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -817,3 +817,36 @@ fn face_job_follows_rotate_right() {let (pw, ph) = ((r.x1 - r.x0) * h, (r.y1 - r.y0) * w);assert!((pw - ph).abs() < 1e-6 * w.max(h), "square in rotated pixels: {pw} × {ph}");}++/// Selecting an id that is not in the library is an error, and the selection stays as it was+/// (#182: `select_photos {"ids": [9999]}` answered `selected: 1` and the session lost its photo).+#[test]+fn selecting_an_unknown_photo_is_an_error_and_keeps_the_selection() {+ let mut s = demo();+ let vis = s.visible_cloned();+ s.execute("library.select", &json!({"ids": [vis[0].0]})).unwrap();+ let before = s.selection.clone();+ for p in [+ json!({"ids": [9999]}),+ json!({"ids": [9999], "active": 9999}),+ json!({"ids": [vis[1].0], "active": 9999}),+ json!({"ids": [vis[1].0, 9999]}),+ json!({"ids": [9999], "mode": "add"}),+ json!({"ids": [9999], "mode": "toggle"}),+ json!({"ids": [9999], "mode": "range"}),+ ] {+ let e = s.execute("library.select", &p).unwrap_err().to_string();+ assert!(e.contains("no such photo 9999"), "{p}: {e}");+ assert_eq!(s.selection, before, "{p}");+ }+ assert_eq!(s.active(), Some(vis[0]));+ assert!(s.execute("develop.get", &json!({})).is_ok());+ // queries about an explicit id check it too+ for c in ["develop.get", "photo.inspect", "photo.allMetadata", "history.list"] {+ let e = s.execute(c, &json!({"id": 9999})).unwrap_err().to_string();+ assert!(e.contains("no such photo 9999"), "{c}: {e}");+ assert!(s.execute(c, &json!({"id": vis[1].0})).is_ok(), "{c}");+ }+ // an empty selection is still allowed+ assert_eq!(s.execute("library.select", &json!({"ids": []})).unwrap()["selected"], 0);+}diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rsindex c613bf373..ca6ed2b8c 100644--- a/crates/mcp/src/tests.rs+++ b/crates/mcp/src/tests.rs@@ -205,3 +205,24 @@ fn resources() {}assert_eq!(rpc(&mut s, 99, "resources/read", json!({"uri": "lightcraft://nope"}))["error"]["code"], -32002);}++/// `select_photos` with an id that is not in the library is a tool error, and the photo that was+/// active stays active (#182).+#[test]+fn select_photos_rejects_unknown_ids_and_keeps_the_active_photo() {+ let mut b = Headless::demo();+ let first = b.session.visible_cloned()[0];+ let r = call_tool(&mut b, "select_photos", &json!({"ids": [first.0]}));+ assert!(!r.is_error, "{r:?}");+ let r = call_tool(&mut b, "select_photos", &json!({"ids": [9999]}));+ assert!(r.is_error, "{r:?}");+ assert!(r.content[0]["text"].as_str().unwrap().contains("no such photo 9999"), "{r:?}");+ assert_eq!(b.session.active(), Some(first));+ let r = call_tool(&mut b, "get_develop", &json!({}));+ assert!(!r.is_error, "{r:?}");+ let r = call_tool(&mut b, "get_develop", &json!({"id": 9999}));+ assert!(r.is_error, "{r:?}");+ let r = call_tool(&mut b, "set_develop", &json!({"id": 9999, "values": {"light.exposure": 1.0}}));+ assert!(r.is_error, "{r:?}");+ assert_eq!(b.session.active(), Some(first));+}diff --git a/docs/mcp.md b/docs/mcp.mdindex 0e0e14b14..7e8154060 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -81,7 +81,7 @@ During development you can also point the client at `cargo run --release -p ligh| `run_command {command, params?}` | Run any command by id || `import {paths, album?, mode?, destination?, organize?, rename?}` | Import files/folders (folders are scanned recursively); the first new photo becomes active. `mode: "copy"` copies into `destination` (default: the library's Originals/), `mode: "move"` moves there (each original and its XMP sidecars are removed from the source only after the copy is verified and catalogued; duplicates and failures keep their sources; the result's `moved` / `kept` list what moved and what stayed, and why; undo leaves the moved files at the destination), filed by `organize`: `date` (YYYY/YYYY-MM-DD), `month`, `flat` or a folder template such as `{date:%Y}/{date:%Y%m%d}` (→ `2026/20260114`; capture date, else the import date; always inside the destination), and named by the `rename` template (`run_command photo.renameTokens` lists the tags) || `query_photos {filter?, sort?, offset?, limit?}` | Photos in the current view (or matching a catalog `Filter`) |-| `select_photos {ids, active?, mode?}` | Set the selection / active photo |+| `select_photos {ids, active?, mode?}` | Set the selection / active photo. Every id (and `active`) must be in the library: an unknown id is a tool error (`no such photo 9999`) and the selection and active photo are left as they were || `list_controls {section?}` | Every develop slider: id (`light.exposure`…), range, default, current value || `get_develop {id?}` | Full develop-settings JSON || `set_develop {id?, values?, settings?, label?}` | `values`: `{controlId: number}`; `settings`: partial develop JSON deep-merged. Undoable |