From a5636fa3e75dec68bf0ff481369a5e8f9ce43928 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Sun, 1 Nov 2026 01:14:25 -0800 Subject: [PATCH] Preserve embedded Batch action scopes in droplets --- crates/engine/src/cmd/actions_cmds.rs | 152 ++++++++++++------- crates/engine/src/cmd/actions_cmds/tests.rs | 45 ++++++ crates/engine/src/cmd/automate_cmds/tests.rs | 95 ++++++++++++ 3 files changed, 240 insertions(+), 52 deletions(-) diff --git a/crates/engine/src/cmd/actions_cmds.rs b/crates/engine/src/cmd/actions_cmds.rs index d32f0892501..396579462a7 100644 --- a/crates/engine/src/cmd/actions_cmds.rs +++ b/crates/engine/src/cmd/actions_cmds.rs @@ -14,7 +14,7 @@ //! step, because the outer `actions.play` id would otherwise hide a recorded `file.*` command from //! the top-level check. -use std::collections::BTreeSet; +use std::collections::{BTreeSet, VecDeque}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -235,78 +235,126 @@ pub fn playback_plan(s: &Session, p: &Value) -> Result<(Action, usize)> { Ok((action, from)) } -/// The actions that `steps` call through Play Action, Batch and Conditional steps, followed -/// transitively, in list order, so a droplet can run without the Actions panel that made it -/// (#2794, #6804). Effective inline Batch steps are followed too. Index references become names, which resolve -/// without the rest of the list. A target that doesn't resolve is left alone: it fails at -/// playback, as it would have before. +/// Capture transitive Play Action, Conditional and Batch dependencies for a standalone droplet +/// (#2794, #6804). Ordinary references become names; normalized copies keep source-list order. +/// A named Batch with its own action list selects an untouched source copy at an exported index, +/// after the ordinary copies. Inline embedded bodies retain their own references. Missing +/// targets remain deferred failures, as before. pub fn called_actions(list: &[Action], steps: &mut [(String, Value)]) -> Vec { - /// Follow saved calls and effective inline Batch steps without changing their serialized shape. - fn targets(list: &[Action], steps: &mut [(String, Value)], depth: usize, queue: &mut Vec<(usize, usize)>) { + /// Visit calls in the current namespace, leaving embedded inline Batch scopes untouched. + fn visit_calls(steps: &mut [(String, Value)], f: &mut impl FnMut(&str, &mut Value, bool)) { let mut pending: Vec<_> = steps.iter_mut().rev().map(|(id, params)| (id.clone(), params)).collect(); while let Some((id, params)) = pending.pop() { - match id.as_str() { - "actions.play" | "file.automate.batch" => { - if id == "file.automate.batch" { - let inline = - if params.get("steps").is_some() { Some("steps") } else { params.get("action").is_some_and(Value::is_array).then_some("action") }; - if let Some(key) = inline { - // A present invalid `steps` still wins over `action`, just as at runtime. - let Some(steps) = params.get_mut(key).and_then(Value::as_array_mut) else { continue }; - for step in steps.iter_mut().rev() { - let call = match step { - Value::Array(a) => { - let Some(id) = a.first().and_then(Value::as_str).map(str::to_owned) else { continue }; - a.get_mut(1).map(|params| (id, params)) - } - Value::Object(o) => { - let Some(id) = o.get("command").or_else(|| o.get("id")).and_then(Value::as_str).map(str::to_owned) else { - continue; - }; - o.get_mut("params").map(|params| (id, params)) - } - // String steps and omitted params use `{}`, with no action target. - _ => None, - }; - if let Some(call) = call { - pending.push(call); - } + let scoped = id == "file.automate.batch" && params.get("calledActions").is_some_and(|v| !v.is_null()); + if id == "file.automate.batch" { + let inline = if params.get("steps").is_some() { Some("steps") } else { params.get("action").is_some_and(Value::is_array).then_some("action") }; + if let Some(key) = inline { + if scoped { + continue; + } + // A present invalid `steps` still wins over `action`, just as at runtime. + let Some(steps) = params.get_mut(key).and_then(Value::as_array_mut) else { continue }; + for step in steps.iter_mut().rev() { + let call = match step { + Value::Array(a) => { + let Some(id) = a.first().and_then(Value::as_str).map(str::to_owned) else { continue }; + a.get_mut(1).map(|params| (id, params)) } - continue; + Value::Object(o) => { + let Some(id) = o.get("command").or_else(|| o.get("id")).and_then(Value::as_str).map(str::to_owned) else { continue }; + o.get_mut("params").map(|params| (id, params)) + } + // String steps and omitted params use `{}`, with no action target. + _ => None, + }; + if let Some(call) = call { + pending.push(call); } } - let Ok(i) = resolve(list, params, &id) else { continue }; + continue; + } + } + f(&id, params, scoped); + } + } + /// Capture ordinary calls transitively, but retain an untouched source for scoped named Batch. + fn targets(list: &[Action], steps: &mut [(String, Value)], depth: usize, queue: &mut VecDeque<(usize, usize)>, scoped: &mut BTreeSet) { + if depth > 16 { + return; + } + visit_calls(steps, &mut |id, params, own_actions| match id { + "actions.play" | "file.automate.batch" => { + let Ok(i) = resolve(list, params, id) else { return }; + if own_actions { + scoped.insert(i); + } else { if let (Some(action), Some(obj)) = (list.get(i), params.as_object_mut()) { obj.insert("action".into(), json!(action.name)); } - queue.push((i, depth)); + queue.push_back((i, depth)); } - // Conditional branches only take names, so there is nothing to rewrite. - "actions.conditional" => { - for key in ["then", "else"] { - let Some(name) = params.get(key).and_then(Value::as_str) else { continue }; - if let Some(i) = list.iter().position(|a| a.name == name) { - queue.push((i, depth)); - } + } + "actions.conditional" => { + for key in ["then", "else"] { + let Some(name) = params.get(key).and_then(Value::as_str) else { continue }; + if let Some(i) = list.iter().position(|a| a.name == name) { + queue.push_back((i, depth)); } } - _ => {} } - } + _ => {} + }); } - let mut queue = Vec::new(); - targets(list, steps, 1, &mut queue); + let mut queue = VecDeque::new(); + let mut scoped = BTreeSet::new(); + targets(list, steps, 1, &mut queue, &mut scoped); let mut found = std::collections::BTreeMap::new(); - while let Some((i, depth)) = queue.pop() { - // Playback stops at 16 levels, so deeper calls never run. + // Visit shallow calls first, so a deeper path cannot hide a reachable dependency. + while let Some((i, depth)) = queue.pop_front() { if depth > 16 || found.contains_key(&i) { continue; } let Some(mut action) = list.get(i).cloned() else { continue }; - targets(list, &mut action.steps, depth + 1, &mut queue); + targets(list, &mut action.steps, depth + 1, &mut queue, &mut scoped); found.insert(i, action); } - found.into_values().collect() + let mut found: Vec<_> = found.into_values().collect(); + let mut originals = Vec::new(); + let mut slots = std::collections::BTreeMap::new(); + for i in scoped { + if let Some(action) = list.get(i) { + slots.insert(i, found.len() + originals.len()); + originals.push(action.clone()); + } + } + // A named Batch selects from the caller before switching to its embedded list. Its source + // must keep raw references, even when normal Play needs a normalized copy of the same action. + let final_len = found.len() + originals.len(); + let mut remap = |id: &str, params: &mut Value, scoped: bool| { + if !matches!(id, "actions.play" | "file.automate.batch") { + return; + } + if scoped + && let Ok(i) = resolve(list, params, id) + && let Some(slot) = slots.get(&i) + { + params["action"] = json!(slot); + return; + } + // Appended source copies must not make an originally missing numeric target valid. + if let Some(i) = params.get("action").and_then(num).and_then(|i| usize::try_from(i).ok()) + && i >= list.len() + && i < final_len + { + params["action"] = json!(final_len); + } + }; + visit_calls(steps, &mut remap); + for action in &mut found { + visit_calls(&mut action.steps, &mut remap); + } + found.extend(originals); + found } fn always(_: &Session) -> std::result::Result<(), String> { diff --git a/crates/engine/src/cmd/actions_cmds/tests.rs b/crates/engine/src/cmd/actions_cmds/tests.rs index caddcaa8924..1dee64b4fad 100644 --- a/crates/engine/src/cmd/actions_cmds/tests.rs +++ b/crates/engine/src/cmd/actions_cmds/tests.rs @@ -1176,3 +1176,48 @@ fn arrange_that_cannot_move_is_a_noop_in_playback() { assert_eq!(played["ran"], 0, "{played}"); assert!(played["failed"].is_object(), "{played}"); } + +/// A deep route cannot consume the only visit to a dependency reachable near the root. +#[test] +fn called_actions_keeps_dependencies_reachable_by_a_shallow_route() { + let mut list = vec![Action::new("Leaf", Vec::new()), Action::new("Shared", vec![("actions.play".into(), json!({"action": "Leaf"}))])]; + for i in 0..15 { + let next = if i == 14 { "Shared".to_string() } else { format!("D{}", i + 1) }; + list.push(Action::new(format!("D{i}"), vec![("actions.play".into(), json!({"action": next}))])); + } + let mut steps = vec![("file.automate.batch".into(), json!({"action": "Shared"})), ("actions.play".into(), json!({"action": "D0"}))]; + let called = called_actions(&list, &mut steps); + assert!(called.iter().any(|a| a.name == "Leaf")); + assert_eq!(called.len(), list.len()); +} + +/// Extra source copies cannot turn deferred missing indices into valid action calls. +#[test] +fn scoped_source_slots_do_not_bind_previously_missing_references() { + let list = vec![ + Action::new("Leaf", Vec::new()), + Action::new("Shared", vec![("actions.play".into(), json!({"action": 0}))]), + Action::new("Bad", vec![("actions.play".into(), json!({"action": 3}))]), + ]; + let mut steps = vec![ + ("actions.play".into(), json!({"action": "Shared"})), + ("file.automate.batch".into(), json!({"action": "Shared", "calledActions": []})), + ("actions.play".into(), json!({"action": "Bad"})), + ]; + for id in ["actions.play", "file.automate.batch"] { + for action in [json!(3), json!(3.25), json!(-1), json!("Missing"), json!(null)] { + steps.push((id.into(), json!({"action": action}))); + if id == "file.automate.batch" { + steps.push((id.into(), json!({"action": action, "calledActions": []}))); + } + } + } + let called = called_actions(&list, &mut steps); + assert_eq!(called.len(), 4); + assert_eq!(called.last(), list.get(1), "the raw source keeps its own indices"); + for (id, params) in &steps[3..] { + assert!(resolve(&called, params, id).is_err(), "{id}: {params}"); + } + let bad = called.iter().find(|a| a.name == "Bad").unwrap(); + assert!(resolve(&called, &bad.steps[0].1, "actions.play").is_err()); +} diff --git a/crates/engine/src/cmd/automate_cmds/tests.rs b/crates/engine/src/cmd/automate_cmds/tests.rs index 398ff2843a0..e47e4a3218f 100644 --- a/crates/engine/src/cmd/automate_cmds/tests.rs +++ b/crates/engine/src/cmd/automate_cmds/tests.rs @@ -424,6 +424,101 @@ fn droplets_carry_the_actions_their_play_steps_call() { assert_eq!(r["files"].as_array().unwrap().len(), inputs.len(), "{r}"); } +/// Embedded Batch lists own their references; a named source is still selected from the caller. +#[test] +fn droplets_preserve_batch_action_namespaces() { + use crate::actions_cmds::Action; + let dir = tmp("droplet-scopes"); + let input = images(&dir, 1, 40, 20).remove(0); + for kind in ["inline", "named", "mixed", "mixed-two", "caller-null"] { + let mut maker = Session::new(); + let mut source = Action::new("Source", vec![("actions.play".into(), json!({"action": 1})), ("file.close".into(), json!({}))]); + source.disabled.insert(1); + source.dialogs.insert(0); + source.set = Some("Captured".into()); + maker.actions.list = vec![Action::new("Gap", Vec::new()), Action::new("Outside", Vec::new()), source.clone()]; + let embedded = vec![ + Action::new("LocalGap", Vec::new()), + Action::new("Inside", vec![("image.imageRotation.90cw".into(), json!({}))]), + Action::new("Outside", Vec::new()), + ]; + let inner = format!("{dir}/{kind}-inner"); + let mut batch = json!({"input": [input], "output": inner, "format": "png", "calledActions": embedded}); + if kind == "inline" || kind == "caller-null" { + batch["steps"] = json!([["actions.play", {"action": 1}]]); + } else { + batch["action"] = json!("Source"); + } + if kind == "caller-null" { + batch["calledActions"] = Value::Null; + } + let mut steps = Vec::new(); + if kind.starts_with("mixed") { + steps.push(json!(["actions.play", {"action": "Source"}])); + } + steps.push(json!(["file.automate.batch", batch])); + let other = format!("{dir}/{kind}-other"); + if kind == "mixed-two" { + let mut second = batch.clone(); + second["output"] = json!(other); + second["calledActions"][1]["steps"] = json!([]); + steps.push(json!(["file.automate.batch", second])); + } + let path = maker + .execute( + "file.automate.createDroplet", + json!({"path": format!("{dir}/{kind}"), "steps": steps, "format": "png", "output": format!("{dir}/{kind}-out"), "shim": false}), + ) + .unwrap()["path"] + .clone(); + let saved: Value = serde_json::from_slice(&std::fs::read(path.as_str().unwrap()).unwrap()).unwrap(); + if kind == "inline" { + assert_eq!(saved["action"]["steps"][0][1], batch, "embedded inline steps are unchanged"); + assert!(saved.get("calledActions").is_none(), "embedded references do not capture enclosing actions"); + } else if kind != "caller-null" { + let captured: Vec = serde_json::from_value(saved["calledActions"].clone()).unwrap(); + assert_eq!(captured.last(), Some(&source), "one untouched source retains its references and flags"); + assert_eq!(captured.len(), if kind.starts_with("mixed") { 3 } else { 1 }); + } + let r = Session::new().execute("file.automate.runDroplet", json!({"droplet": path, "input": [input]})).unwrap(); + assert_eq!(r["errors"], json!([]), "{kind}: {r}"); + let out = photocraft_codecs::decode(&std::fs::read(format!("{inner}/img0.png")).unwrap()).unwrap(); + assert_eq!(out.dimensions(), if kind == "caller-null" { (40, 20) } else { (20, 40) }, "{kind}"); + if kind == "mixed-two" { + assert_eq!(photocraft_codecs::decode(&std::fs::read(format!("{other}/img0.png")).unwrap()).unwrap().dimensions(), (40, 20)); + } + } +} + +/// Untouched scoped variants count toward the existing 4096-record playback limit. +#[test] +fn droplet_scoped_variants_keep_the_existing_action_limit() { + use crate::actions_cmds::Action; + let dir = tmp("droplet-scope-limit"); + let input = images(&dir, 1, 2, 1).remove(0); + for count in [4095, 4096] { + let mut maker = Session::new(); + maker.actions.list = (0..count).map(|i| Action::new(format!("A{i}"), Vec::new())).collect(); + let mut steps: Vec<_> = (0..count).map(|i| json!(["actions.play", {"action": i}])).collect(); + steps.push( + json!(["file.automate.batch", {"action": 0, "calledActions": [], "input": [input], "output": format!("{dir}/{count}-inner"), "format": "png"}]), + ); + let output = format!("{dir}/{count}-out"); + let path = maker + .execute("file.automate.createDroplet", json!({"path": format!("{dir}/{count}"), "steps": steps, "output": output, "format": "png", "shim": false})) + .unwrap()["path"] + .clone(); + let result = Session::new().execute("file.automate.runDroplet", json!({"droplet": path, "input": [input]})); + if count == 4095 { + assert_eq!(result.unwrap()["errors"], json!([])); + assert!(std::path::Path::new(&output).exists()); + } else { + assert!(result.unwrap_err().to_string().contains("4096")); + assert!(!std::path::Path::new(&output).exists()); + } + } +} + #[test] fn droplets_carry_the_actions_their_conditional_steps_call() { use crate::actions_cmds::Action;