From 012342d87e6c3421ded1b58a2458273cb407914d Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 4 Nov 2026 10:10:57 -0800 Subject: [PATCH] Keep explicit imported calls within their declared scope --- apps/photocraft-cli/src/actions.rs | 3 +- apps/photocraft-cli/tests/it/cli.rs | 54 +++++++++++++++++++++++ crates/engine/src/cmd/atn_cmds/convert.rs | 41 ++++++++++++----- crates/engine/src/cmd/atn_cmds/files.rs | 3 +- crates/engine/tests/it/atn_call_scopes.rs | 25 ++++++++++- 5 files changed, 113 insertions(+), 13 deletions(-) diff --git a/apps/photocraft-cli/src/actions.rs b/apps/photocraft-cli/src/actions.rs index 651aba5ba8..b25c1e2a73 100644 --- a/apps/photocraft-cli/src/actions.rs +++ b/apps/photocraft-cli/src/actions.rs @@ -137,7 +137,8 @@ pub fn load_actions_file(path: &Path, name: Option<&str>) -> Result<(Steps, Vec< .map(|u| format!("`{}` step {}: Photoshop's \"{}\" ({}) has no PhotoCraft equivalent yet", u.action, u.step + 1, u.name, u.event)) .chain(imp.warnings.iter().cloned()) .collect(); - photocraft_engine::atn_cmds::normalize_import(&mut imp, std::iter::empty()).map_err(|message| ActionsError::Atn { path: path.to_path_buf(), message })?; + photocraft_engine::atn_cmds::normalize_import(&mut imp, std::iter::empty(), false) + .map_err(|message| ActionsError::Atn { path: path.to_path_buf(), message })?; let play = vec![("actions.play".to_string(), json!({"action": imp.actions[selected].name}))]; Ok((play, imp.actions, warnings)) } diff --git a/apps/photocraft-cli/tests/it/cli.rs b/apps/photocraft-cli/tests/it/cli.rs index ddaa8d6252..ae291622a7 100644 --- a/apps/photocraft-cli/tests/it/cli.rs +++ b/apps/photocraft-cli/tests/it/cli.rs @@ -1938,3 +1938,57 @@ fn batch_refuses_ambiguous_nested_atn_calls_before_output() { assert!(String::from_utf8_lossy(&stderr).contains("ambiguous cross-set")); assert!(!output.exists()); } + +/// An explicit archive scope cannot fall back to a namesake in another physical set. +#[test] +fn batch_refuses_missing_or_ambiguous_explicit_atn_scopes_before_output() { + use photocraft_engine::{actions_cmds::Action, atn_cmds}; + use photocraft_psd::atn; + for failure in ["missing-target", "missing-set", "ambiguous-set"] { + for call in ["play", "shared", "then", "else"] { + let directory = tmp(&format!("nested-atn-scope-{failure}-{call}")); + let scope = if failure == "missing-set" { "Absent" } else { "A" }; + let file = directory.join("sets.atn"); + let finish = Action::new("Finish", vec![("layer.new.layer".into(), json!({}))]); + let other = Action::new("Other", Vec::new()); + let (id, params) = match call { + "play" => ("actions.play", json!({"action":"Finish","set":scope})), + "shared" => ("actions.conditional", json!({"if":"always","then":"Finish","else":null,"set":scope})), + "then" => ("actions.conditional", json!({"if":"always","then":"Finish","thenSet":scope,"else":"Finish","elseSet":"B"})), + _ => ("actions.conditional", json!({"if":"always","then":"Finish","thenSet":"B","else":"Finish","elseSet":scope})), + }; + let caller = Action::new("Caller", vec![(id.into(), params)]); + let group = |name: &str, actions: &[&Action]| { + let bytes = atn_cmds::export(name, actions, &[], false).unwrap().0; + atn::parse(&bytes).unwrap() + }; + let mut groups = vec![group("A", &[if failure == "ambiguous-set" { &finish } else { &other }])]; + if failure == "ambiguous-set" { + groups.push(group("A", &[&finish])); + } + groups.push(group("B", &[&finish, &caller])); + std::fs::write(&file, atn::write_sets(&groups).unwrap()).unwrap(); + let output = directory.join("out"); + let (mut stdout, mut stderr) = (Vec::new(), Vec::new()); + let args = [ + "batch".as_ref(), + "--in".as_ref(), + directory.as_os_str(), + "--out".as_ref(), + output.as_os_str(), + "--actions".as_ref(), + file.as_os_str(), + "--action".as_ref(), + "Caller".as_ref(), + ]; + assert_eq!(photocraft_cli::run(args, &mut stdout, &mut stderr), 1); + let error = match failure { + "missing-set" => "missing set", + "ambiguous-set" => "ambiguous action call set", + _ => "missing from set", + }; + assert!(String::from_utf8_lossy(&stderr).contains(error), "{call}: {}", String::from_utf8_lossy(&stderr)); + assert!(!output.exists()); + } + } +} diff --git a/crates/engine/src/cmd/atn_cmds/convert.rs b/crates/engine/src/cmd/atn_cmds/convert.rs index 3b5b26d930..87f832bf20 100644 --- a/crates/engine/src/cmd/atn_cmds/convert.rs +++ b/crates/engine/src/cmd/atn_cmds/convert.rs @@ -44,9 +44,14 @@ pub struct ImportedSet { } /// Give imported actions globally unique playback names while keeping calls bound to their physical set. -/// Explicit set references win over caller-local names; ambiguous cross-set calls are refused. +/// Explicit archive scopes never fall back to another set; external scopes stay unrewritten. /// The caller owns the uncommitted import, so a refusal never changes a live library. -pub fn normalize_import(imp: &mut Imported, reserved: impl IntoIterator) -> std::result::Result, String> { +/// `allow_external_calls` is false for a standalone CLI archive and true when importing into a session namespace. +pub fn normalize_import( + imp: &mut Imported, + reserved: impl IntoIterator, + allow_external_calls: bool, +) -> std::result::Result, String> { let mut set_for = vec![0usize; imp.actions.len()]; for (index, set) in imp.sets.iter().enumerate() { set_for.get_mut(set.actions.clone()).ok_or_else(|| "invalid imported set range".to_string())?.fill(index); @@ -87,14 +92,10 @@ pub fn normalize_import(imp: &mut Imported, reserved: impl IntoIterator( + sets: &[ImportedSet], + renamed: &'a [std::collections::HashMap], + scope: &str, + target: &str, + allow_external_calls: bool, +) -> std::result::Result, String> { + let mut matching = sets.iter().enumerate().filter(|(_, set)| set.name == scope); + let index = match matching.next() { + Some((index, _)) => index, + None if allow_external_calls => return Ok(None), + None => return Err(format!("action call references missing set `{scope}`")), + }; + if matching.next().is_some() { + return Err(format!("ambiguous action call set `{scope}`")); + } + renamed.get(index).and_then(|names| names.get(target)).map(Some).ok_or_else(|| format!("action call target `{target}` is missing from set `{scope}`")) +} + /// Retain an unsupported event's ID kind and descriptor for later export without executing it. fn photoshop_step(item: &AtnItem, label: String) -> (String, Value) { let descriptor = item.descriptor.as_ref().map(|d| photocraft_paint::tile::b64_encode(&d.to_bytes())); diff --git a/crates/engine/src/cmd/atn_cmds/files.rs b/crates/engine/src/cmd/atn_cmds/files.rs index 00bccafcd2..1288bf5d3a 100644 --- a/crates/engine/src/cmd/atn_cmds/files.rs +++ b/crates/engine/src/cmd/atn_cmds/files.rs @@ -94,7 +94,8 @@ pub(super) fn load(s: &mut Session, p: &Value) -> Result { if old_rows.checked_add(new_rows).is_none_or(|count| count > super::atn::MAX_SETS) { return Err(bad(cmd, "too many action set rows")); } - let names = super::normalize_import(&mut imp, s.actions.list.iter().filter(keep).map(|action| action.name.clone())).map_err(|error| bad(cmd, error))?; + let names = + super::normalize_import(&mut imp, s.actions.list.iter().filter(keep).map(|action| action.name.clone()), true).map_err(|error| bad(cmd, error))?; let keys = imp.function_keys.clone(); let steps: usize = imp.actions.iter().map(|action| action.steps.len()).sum(); let added = imp.actions; diff --git a/crates/engine/tests/it/atn_call_scopes.rs b/crates/engine/tests/it/atn_call_scopes.rs index 16e67b11c3..71616ab836 100644 --- a/crates/engine/tests/it/atn_call_scopes.rs +++ b/crates/engine/tests/it/atn_call_scopes.rs @@ -118,7 +118,7 @@ fn portable_conditional_branches_retain_independent_set_scopes() { let mut inherited = projected.clone(); inherited.actions[2].steps[0].1["thenSet"] = serde_json::Value::Null; inherited.actions[2].steps[0].1["set"] = json!("A"); - atn_cmds::normalize_import(&mut inherited, std::iter::empty()).unwrap(); + atn_cmds::normalize_import(&mut inherited, std::iter::empty(), false).unwrap(); assert_eq!(inherited.actions[2].steps[0].1["then"], "Finish", "null branch scope inherits the shared set, like the writer"); } let mut session = Session::new(); @@ -143,3 +143,26 @@ fn portable_conditional_shared_scope_keeps_the_existing_command_shape() { assert_eq!(imported.actions[0].steps[0].1, params); } } + +/// An out-of-archive scope still targets an existing library action after local names collide. +#[test] +fn imported_external_set_call_is_not_rewritten_to_an_archive_local_namesake() { + use photocraft_engine::atn_cmds; + let caller = Action::new("Caller", vec![("actions.play".into(), json!({"action":"Finish","set":"External"}))]); + let local = finish("From B"); + let bytes = atn_cmds::export("B", &[&local, &caller], &[], false).unwrap().0; + let mut deferred = atn_cmds::import(&bytes).unwrap(); + atn_cmds::normalize_import(&mut deferred, ["Finish".to_string()], true).unwrap(); + assert_ne!(deferred.actions[0].name, "Finish"); + assert_eq!(deferred.actions[1].steps[0].1, json!({"action":"Finish","set":"External"}), "deferred reference remains intact"); + let mut session = Session::new(); + session.execute("file.new", json!({"width":4,"height":4})).unwrap(); + let mut external = finish("From External"); + external.set = Some("External".into()); + session.actions.list.push(external); + session.execute("actions.load", json!({"data":photocraft_engine::paint::tile::b64_encode(&bytes)})).unwrap(); + let result = session.execute("actions.play", json!({"action":"Caller"})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + assert!(session.active().unwrap().doc.layers.iter().any(|layer| layer.name == "From External")); + assert!(!session.active().unwrap().doc.layers.iter().any(|layer| layer.name == "From B")); +}