Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Allow automation to edit embedded Smart Object contents (#1882)

Harrison O'Connor-Hoover9e36825d2d4b
diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs
index 6d160bd6b..1e13eef0b 100644
--- a/crates/automation/src/workspace.rs
+++ b/crates/automation/src/workspace.rs
@@ -169,7 +169,16 @@ pub fn authorize_engine_command(id: &str, params: &Value) -> Result<(), Automati
if id.starts_with("file.") && !safe_file_command {
return Err(command_error(id));
}
- if (id.starts_with("layer.smartObjects.") && id != "layer.smartObjects.convertToSmartObject")
+ // Contents commands re-check the resolved source in the engine before any disk read.
+ // Photoshop's embedded linked-layer blocks count as in-memory sources too.
+ let in_memory_smart_command = matches!(
+ id,
+ "layer.smartObjects.convertToSmartObject"
+ | "layer.smartObjects.editContents"
+ | "layer.smartObjects.convertToLayers"
+ | "layer.smartObjects.saveContents"
+ );
+ if (id.starts_with("layer.smartObjects.") && !in_memory_smart_command)
|| matches!(
id,
"pattern.import"
@@ -217,7 +226,9 @@ fn params_contain_ambient_path(id: &str, params: &Value) -> bool {
let keys: &[&str] = match id {
"image.adjustments.colorLookup" | "layer.newAdjustmentLayer.colorLookup" | "layer.setAdjustment" => &["file"],
"filter.distort.displace" => &["mapPath"],
- "layer.quickExportAsPng" | "layer.exportAs" | "image.applyDataSet" => &["path"],
+ "layer.quickExportAsPng" | "layer.exportAs" | "image.applyDataSet" | "layer.smartObjects.editContents" | "layer.smartObjects.convertToLayers" => {
+ &["path"]
+ }
"image.mode.rgb" | "image.mode.grayscale" | "image.mode.cmyk" | "image.mode.lab" => &["profile"],
"edit.assignProfile" | "edit.convertToProfile" | "edit.profileInfo" | "view.proofSetup" | "view.gamutWarning" => &["profile"],
"edit.colorSettings" => &["workingRgb", "workingCmyk", "workingGray"],
@@ -526,6 +537,9 @@ mod tests {
"file.export.saveForWebLegacy",
"pattern.import",
"layer.smartObjects.exportContents",
+ "layer.smartObjects.replaceContents",
+ "layer.smartObjects.relinkToFile",
+ "layer.smartObjects.convertToLinked",
"measurementLog.export",
"layer.videoLayers.reloadFrame",
"edit.colorSettings",
@@ -533,6 +547,12 @@ mod tests {
assert!(authorize_engine_command(id, &serde_json::json!({})).is_err());
}
assert!(authorize_engine_command("file.new", &serde_json::json!({})).is_ok());
+ for id in ["layer.smartObjects.editContents", "layer.smartObjects.convertToLayers", "layer.smartObjects.saveContents"] {
+ assert!(authorize_desktop_engine_command(id, &serde_json::json!({"layer": 19})).is_ok(), "{id}");
+ }
+ for id in ["layer.smartObjects.editContents", "layer.smartObjects.convertToLayers"] {
+ assert!(authorize_engine_command(id, &serde_json::json!({"path": "/outside/source.psb"})).is_err(), "{id}");
+ }
// The UI-level examples in docs/control-protocol.md.
for id in ["view.zoomIn", "window.theme.pro", "edit.search"] {
assert!(authorize_desktop_engine_command(id, &serde_json::json!({})).is_ok(), "{id}");
diff --git a/crates/automation/tests/mcp.rs b/crates/automation/tests/mcp.rs
index 42a411269..143c10cff 100644
--- a/crates/automation/tests/mcp.rs
+++ b/crates/automation/tests/mcp.rs
@@ -565,6 +565,68 @@ async fn filesystem_policy_rejects_absolute_and_escaping_paths_before_effects()
cleanup(&base);
}
+/// The template workflow stays in memory, including saving nested contents back to the parent.
+#[tokio::test(flavor = "multi_thread")]
+async fn embedded_smart_objects_can_be_edited_saved_and_unpacked_without_file_authority() {
+ let client = connect(PhotocraftMcp::headless()).await;
+ let run = async |id: &str, params: Value| json_of(&call(&client, "command_run", json!({"id": id, "params": params})).await);
+ json_of(&call(&client, "doc_new", json!({"width": 16, "height": 12, "background": "white"})).await);
+ run("layer.smartObjects.convertToSmartObject", json!({})).await;
+ let outer = run("layer.smartObjects.convertToSmartObject", json!({})).await["layer"].clone();
+ // An explicit target works even with a regular pixel layer selected.
+ run("layer.new.layer", json!({"name": "Other layer"})).await;
+ assert_eq!(run("layer.smartObjects.editContents", json!({"layer": outer})).await["document"], 1);
+ assert_eq!(run("layer.smartObjects.editContents", json!({})).await["document"], 2);
+ run("layer.setProps", json!({"name": "Edited photo", "opacity": 0.5})).await;
+ assert_eq!(run("layer.smartObjects.saveContents", json!({})).await["updated"], true);
+ json_of(&call(&client, "doc_close", json!({})).await);
+ run("layer.smartObjects.saveContents", json!({})).await;
+ json_of(&call(&client, "doc_close", json!({})).await);
+ assert_eq!(json_of(&call(&client, "session_list", json!({})).await)["documents"].as_array().unwrap().len(), 1);
+
+ // Reopening the saved nested source proves both in-memory parent updates survived closing.
+ run("layer.smartObjects.editContents", json!({"layer": outer})).await;
+ run("layer.smartObjects.editContents", json!({})).await;
+ let doc = json_of(&call(&client, "doc_inspect", json!({})).await);
+ assert_eq!(doc["layers"][0]["name"], "Edited photo");
+ assert_eq!(doc["layers"][0]["opacity"], 0.5);
+ json_of(&call(&client, "doc_close", json!({})).await);
+ json_of(&call(&client, "doc_close", json!({})).await);
+ let unpacked = run("layer.smartObjects.convertToLayers", json!({"layer": outer})).await["layer"].clone();
+ run("layer.smartObjects.convertToLayers", json!({"layer": unpacked})).await;
+ let doc = json_of(&call(&client, "doc_inspect", json!({})).await);
+ assert!(doc["layers"].as_array().unwrap().iter().all(|l| l["kind"] == "Pixel"));
+ client.cancel().await.unwrap();
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn smart_object_commands_refuse_real_linked_files_without_changing_the_session() {
+ use photocraft_engine::doc::{LayerContent, SmartSource};
+
+ let dir = tmp("linked-smart-object");
+ let original = write_image(&dir, "external.png", photocraft_codecs::Format::Png);
+ let mut session = photocraft_engine::Session::new();
+ session.execute("file.new", json!({"width": 16, "height": 8, "background": "white"})).unwrap();
+ let layer = session.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap()["layer"].clone();
+ let state = session.active_mut().unwrap();
+ let LayerContent::Smart(smart) = &mut std::sync::Arc::make_mut(&mut state.doc).layers[0].content else { panic!("smart object") };
+ smart.source = SmartSource::Linked { path: dir.join("external.png").to_string_lossy().into_owned() };
+ std::fs::write(dir.join("parent.pcraft"), photocraft_engine::smart_cmds::encode_source(&state.doc).unwrap()).unwrap();
+ let client = connect(headless_in(&dir)).await;
+ json_of(&call(&client, "doc_open", json!({"path": "parent.pcraft"})).await);
+ let before = json_of(&call(&client, "doc_inspect", json!({})).await);
+ for id in ["layer.smartObjects.editContents", "layer.smartObjects.convertToLayers"] {
+ let response = call(&client, "command_run", json!({"id": id, "params": {"layer": layer}})).await;
+ assert_eq!(response.is_error, Some(true));
+ assert!(text(&response).contains("ambient filesystem paths"), "{}", text(&response));
+ assert_eq!(json_of(&call(&client, "doc_inspect", json!({})).await), before);
+ assert_eq!(json_of(&call(&client, "session_list", json!({})).await)["documents"].as_array().unwrap().len(), 1);
+ }
+ assert_eq!(std::fs::read(dir.join("external.png")).unwrap(), original);
+ client.cancel().await.unwrap();
+ cleanup(&dir);
+}
+
// ---------------------------------------------------------------------------
// Bridge mode against a fake control server
// ---------------------------------------------------------------------------
diff --git a/crates/engine/src/smart_cmds.rs b/crates/engine/src/smart_cmds.rs
index 02cf6268b..4e589a642 100644
--- a/crates/engine/src/smart_cmds.rs
+++ b/crates/engine/src/smart_cmds.rs
@@ -78,17 +78,44 @@ fn read_file(path: &str) -> Option<Vec<u8>> {
/// The source file of a smart object: embedded bytes, the PSD's embedded linked-layer data (PSD
/// import keeps the placed layer's uuid as the path), or a linked file on disk.
pub fn source_bytes(meta: &Metadata, src: &SmartSource) -> Option<(String, Arc<Vec<u8>>)> {
+ embedded_source_bytes(meta, src).or_else(|| match src {
+ SmartSource::Linked { path } => read_file(path).map(|b| (base_name(path), Arc::new(b))),
+ SmartSource::Embedded { .. } => None,
+ })
+}
+
+/// Memory-only resolution also covers Photoshop's embedded files addressed by a `Linked` UUID.
+fn embedded_source_bytes(meta: &Metadata, src: &SmartSource) -> Option<(String, Arc<Vec<u8>>)> {
match src {
SmartSource::Embedded { file_name, bytes } => Some((file_name.clone(), bytes.clone())),
- SmartSource::Linked { path } => {
- if let Some(f) = photocraft_io::linked::find_linked_file(meta, path) {
- return Some((f.file_name, Arc::new(f.bytes)));
- }
- read_file(path).map(|b| (base_name(path), Arc::new(b)))
- }
+ SmartSource::Linked { path } => photocraft_io::linked::find_linked_file(meta, path).map(|f| (f.file_name, Arc::new(f.bytes))),
}
}
+/// The actual path is stored in the document, not in the command's params. Recheck it before
+/// reading, reusing embedded PSD bytes rather than parsing their global blocks a second time.
+fn authorized_source_bytes(s: &Session, cmd: &str, meta: &Metadata, src: &SmartSource) -> Result<Option<(String, Arc<Vec<u8>>)>> {
+ if let Some(source) = embedded_source_bytes(meta, src) {
+ return Ok(Some(source));
+ }
+ let SmartSource::Linked { path } = src else { return Ok(None) };
+ if let Some(gate) = s.authorize {
+ gate(cmd, &json!({"path": path}))?;
+ }
+ Ok(read_file(path).map(|b| (base_name(path), Arc::new(b))))
+}
+
+/// Recheck a source's actual path before an untrusted command reads it: the path lives in the
+/// document, not in the command's params. Embedded PSD UUIDs never reach the filesystem.
+fn authorize_source(s: &Session, cmd: &str, doc: &Document, src: &SmartSource) -> Result<()> {
+ if let (Some(gate), SmartSource::Linked { path }) = (s.authorize, src)
+ && embedded_source_bytes(&doc.metadata, src).is_none()
+ {
+ gate(cmd, &json!({"path": path}))?;
+ }
+ Ok(())
+}
+
/// A decoded, composited source in its own pixel space (`bounds` starts at the origin).
#[derive(Clone, Debug)]
pub struct SourceImage {
@@ -698,7 +725,9 @@ fn edit_contents(s: &mut Session, p: &Value) -> Result<Value> {
s.set_active(index);
return Ok(json!({"document": index, "parentLayer": id.0}));
}
- let (name, bytes) = source_bytes(&st.doc.metadata, &smart(&st.doc, id)?.source).ok_or_else(|| other("the smart object's contents are unavailable"))?;
+ let source = &smart(&st.doc, id)?.source;
+ let (name, bytes) = authorized_source_bytes(s, "layer.smartObjects.editContents", &st.doc.metadata, source)?
+ .ok_or_else(|| other("the smart object's contents are unavailable"))?;
let mut child = decode_source(&name, &bytes)?;
// Bundles keep their document id; each open copy needs its own.
child.id = DocId::fresh();
@@ -867,11 +896,11 @@ fn move_filter(s: &mut Session, p: &Value) -> Result<Value> {
// ---------- enablement ----------
-/// Whether smart-filter command `spec` can run with `p`: its precondition is checked on an
+/// Whether smart-filter or contents command `spec` can run with `p`: its precondition is checked on an
/// explicit `"layer"` of the active document (the layer it then edits) rather than on the
/// active layer, which stays active (#466). `None` for other commands or without that target.
pub(crate) fn target_enabled(s: &mut Session, spec: &CommandSpec, p: &Value) -> Option<std::result::Result<(), String>> {
- if !spec.id.starts_with("layer.smartFilter.") {
+ if !spec.id.starts_with("layer.smartFilter.") && !matches!(spec.id, "layer.smartObjects.editContents" | "layer.smartObjects.convertToLayers") {
return None;
}
let target = LayerId(p.get("layer")?.as_u64()?);
diff --git a/crates/engine/src/smart_cmds/tests.rs b/crates/engine/src/smart_cmds/tests.rs
index 0d3ca1e02..0253d551e 100644
--- a/crates/engine/src/smart_cmds/tests.rs
+++ b/crates/engine/src/smart_cmds/tests.rs
@@ -734,6 +734,185 @@ fn convert_to_layers_conforms_the_contents_to_the_document_mode_and_depth() {
assert!(matches!(&active_layer(&s).content, LayerContent::Raster(px) if px.format().mode == fmt.mode && px.format().sample == fmt.sample));
}
+fn deny_contents_paths(cmd: &str, p: &Value) -> Result<()> {
+ if matches!(cmd, "layer.smartObjects.editContents" | "layer.smartObjects.convertToLayers" | "layer.smartObjects.saveContents") && p.get("path").is_some() {
+ return Err(other(format!("source path refused: {cmd}: {}", p["path"])));
+ }
+ Ok(())
+}
+
+#[test]
+fn automation_smart_contents_accepts_memory_sources_and_explicit_targets() {
+ for (depth, psd_uuid) in [(8, false), (16, true), (32, false)] {
+ let mut s = session(depth);
+ paint(&mut s);
+ let id = convert(&mut s);
+ if psd_uuid {
+ s.edit("PSD source", |doc, _| {
+ let SmartSource::Embedded { file_name, bytes } = smart(doc, LayerId(id))?.source.clone() else { panic!() };
+ let linked = photocraft_io::linked::LinkedFile { uuid: "embedded-id".into(), file_name, bytes: bytes.to_vec() };
+ doc.metadata.psd_global_blocks.push((*b"8BIM", *b"lnk2", Arc::new(photocraft_io::linked::encode_linked_file(&linked))));
+ smart_mut(doc, LayerId(id))?.source = SmartSource::Linked { path: linked.uuid };
+ Ok(())
+ })
+ .unwrap();
+ }
+ // An explicit smart-object target must work while a pixel layer is selected.
+ let raster = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap();
+ s.authorize = Some(deny_contents_paths);
+ let child = s.execute("layer.smartObjects.editContents", json!({"layer": id})).unwrap()["document"].as_u64().unwrap() as usize;
+ assert_eq!(s.active().unwrap().doc.depth.bits(), depth as u32);
+ assert!(s.active().unwrap().path.is_none());
+ assert_eq!(s.documents()[0].active_layer, Some(LayerId(raster)));
+ s.close(child).unwrap();
+ let r = s.execute("layer.smartObjects.convertToLayers", json!({"layer": id})).unwrap();
+ assert!(matches!(s.active().unwrap().doc.layer(LayerId(r["layer"].as_u64().unwrap())).unwrap().content, LayerContent::Raster(_)));
+ }
+}
+
+fn contents_file() -> std::path::PathBuf {
+ let doc = Document::with_background(
+ "source",
+ Size::new(4, 4),
+ photocraft_doc::ColorMode::Rgb,
+ photocraft_doc::SampleType::U8,
+ photocraft_color::Color::rgb(1.0, 0.0, 0.0),
+ );
+ let path = std::env::temp_dir().join(format!("pcraft-contents-{}-{}.pcraft", std::process::id(), doc.id.0));
+ std::fs::write(&path, encode_source(&doc).unwrap()).unwrap();
+ path
+}
+
+#[test]
+fn automation_smart_contents_refuses_disk_sources_before_changes() {
+ let path = contents_file();
+ let source_bytes = std::fs::read(&path).unwrap();
+ for cmd in ["layer.smartObjects.editContents", "layer.smartObjects.convertToLayers"] {
+ let mut s = session(8);
+ paint(&mut s);
+ let id = convert(&mut s);
+ let sibling = s
+ .edit("linked sources", |doc, _| {
+ let source = SmartSource::Linked { path: path.to_string_lossy().into_owned() };
+ smart_mut(doc, LayerId(id))?.source = source.clone();
+ let mut cache = Surface::new(doc.pixel_format());
+ cache.fill_rect(Rect::new(0, 0, 4, 4), &[0.0, 0.0, 1.0, 1.0]);
+ let sibling = Layer::new("linked sibling", LayerContent::Smart(SmartObject::new(source, Affine::IDENTITY, Some(cache))));
+ let sid = sibling.id;
+ doc.layers.insert(0, sibling);
+ Ok(sid)
+ })
+ .unwrap();
+ s.authorize = Some(deny_contents_paths);
+ let before = s.active().unwrap().doc.clone();
+ let revision = s.active().unwrap().revision;
+ let history = s.active().unwrap().history.entries().len();
+ let error = s.execute(cmd, json!({"layer": id})).unwrap_err().to_string();
+ assert!(error.contains("source path refused") && error.contains(path.to_str().unwrap()), "{error}");
+ assert!(Arc::ptr_eq(&before, &s.active().unwrap().doc));
+ assert_eq!((s.documents().len(), s.active().unwrap().revision, s.active().unwrap().history.entries().len()), (1, revision, history));
+
+ // Human commands retain their linked-file behavior. Returning to an already-open child
+ // reads no source, and saving it updates only its parent layer, never a linked sibling.
+ s.authorize = None;
+ let r = s.execute(cmd, json!({"layer": id})).unwrap();
+ if cmd.ends_with("editContents") {
+ let child = r["document"].as_u64().unwrap() as usize;
+ s.set_active(0);
+ s.authorize = Some(deny_contents_paths);
+ let again = s.execute(cmd, json!({"layer": id})).unwrap();
+ assert_eq!(again["document"], r["document"]);
+ assert_eq!(s.documents().len(), 2);
+ s.execute("image.adjustments.invert", json!({})).unwrap();
+ s.execute("layer.smartObjects.saveContents", json!({})).unwrap();
+ assert!(!s.active().unwrap().is_dirty());
+ let parent = &s.documents()[0].doc;
+ assert!(matches!(smart(parent, LayerId(id)).unwrap().source, SmartSource::Embedded { .. }));
+ assert_eq!(smart(parent, sibling).unwrap().cache.as_ref().unwrap().rgba(1, 1), [0.0, 0.0, 1.0, 1.0]);
+ s.close(child).unwrap();
+ } else {
+ assert_eq!(s.active().unwrap().doc.layer(LayerId(r["layer"].as_u64().unwrap())).unwrap().surface().unwrap().rgba(-5, 6), [1.0, 0.0, 0.0, 1.0]);
+ }
+ }
+ assert_eq!(std::fs::read(&path).unwrap(), source_bytes, "committing contents does not overwrite the linked file");
+ std::fs::remove_file(path).unwrap();
+}
+
+#[test]
+fn automation_smart_contents_checks_nested_reads_at_nontrivial_placements() {
+ let path = contents_file();
+ for (scale, psd_uuid, allowed) in [(1.0, false, true), (1.5, false, false), (1.5, true, true)] {
+ let mut inner = Document::new("inner", Size::new(4, 4), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8);
+ let source_path = if psd_uuid {
+ let linked =
+ photocraft_io::linked::LinkedFile { uuid: "nested-id".into(), file_name: "source.pcraft".into(), bytes: std::fs::read(&path).unwrap() };
+ inner.metadata.psd_global_blocks.push((*b"8BIM", *b"lnk2", Arc::new(photocraft_io::linked::encode_linked_file(&linked))));
+ linked.uuid
+ } else {
+ path.to_string_lossy().into_owned()
+ };
+ let mut cache = Surface::new(inner.pixel_format());
+ cache.fill_rect(Rect::new(0, 0, 4, 4), &[0.0, 0.0, 1.0, 1.0]);
+ let nested =
+ Layer::new("nested", LayerContent::Smart(SmartObject::new(SmartSource::Linked { path: source_path }, Affine::IDENTITY, Some(cache.clone()))));
+ inner.layers.push(Layer::group("group", vec![nested]));
+ let mut parent = Document::new("parent", Size::new(8, 8), inner.mode, inner.depth);
+ parent.layers.push(Layer::new(
+ "outer",
+ LayerContent::Smart(SmartObject::new(
+ SmartSource::Embedded { file_name: "inner.pcraft".into(), bytes: Arc::new(encode_source(&inner).unwrap()) },
+ Affine { m: [scale, 0.0, 0.0, scale, 0.0, 0.0] },
+ Some(cache),
+ )),
+ ));
+ let mut s = Session::new();
+ s.add_document(parent, None);
+ s.authorize = Some(deny_contents_paths);
+ let before = s.active().unwrap().doc.clone();
+ let r = s.execute("layer.smartObjects.convertToLayers", json!({}));
+ if !allowed {
+ assert!(r.unwrap_err().to_string().contains("source path refused"));
+ assert!(Arc::ptr_eq(&before, &s.active().unwrap().doc));
+ assert_eq!(s.active().unwrap().revision, 1);
+ } else {
+ r.unwrap();
+ let sm = s
+ .active()
+ .unwrap()
+ .doc
+ .walk()
+ .into_iter()
+ .find_map(|(_, _, l)| match &l.content {
+ LayerContent::Smart(sm) => Some(sm),
+ _ => None,
+ })
+ .unwrap();
+ assert_eq!(sm.cache.as_ref().unwrap().rgba(1, 1), if psd_uuid { [1.0, 0.0, 0.0, 1.0] } else { [0.0, 0.0, 1.0, 1.0] });
+ }
+ }
+ std::fs::remove_file(path).unwrap();
+}
+
+#[test]
+fn automation_smart_contents_malformed_embedded_sources_leave_documents_unchanged() {
+ for cmd in ["layer.smartObjects.editContents", "layer.smartObjects.convertToLayers"] {
+ let mut s = session(8);
+ paint(&mut s);
+ let id = convert(&mut s);
+ s.edit("bad source", |doc, _| {
+ smart_mut(doc, LayerId(id))?.source = SmartSource::Embedded { file_name: "broken.psd".into(), bytes: Arc::new(b"8BPS".to_vec()) };
+ Ok(())
+ })
+ .unwrap();
+ s.authorize = Some(deny_contents_paths);
+ let before = s.active().unwrap().doc.clone();
+ let revision = s.active().unwrap().revision;
+ assert!(s.execute(cmd, json!({})).is_err());
+ assert!(Arc::ptr_eq(&before, &s.active().unwrap().doc));
+ assert_eq!((s.documents().len(), s.active().unwrap().revision), (1, revision));
+ }
+}
+
#[test]
fn inspect_reports_the_smart_source() {
// A PSD placed layer: its file in the global `lnk2` block, the layer linked to its uuid.
diff --git a/crates/engine/src/smart_cmds/unpack.rs b/crates/engine/src/smart_cmds/unpack.rs
index 320f5b880..8ddfa3d8b 100644
--- a/crates/engine/src/smart_cmds/unpack.rs
+++ b/crates/engine/src/smart_cmds/unpack.rs
@@ -12,14 +12,15 @@ use photocraft_color::BlendMode;
use photocraft_doc::{Document, Group, Layer, LayerContent, LayerId, Metadata, SmartObject, SmartSource};
use serde_json::{Value, json};
-use super::{decode_source, detach_psd, other, placement, shift_layer, smart, source_bytes};
+use super::{authorize_source, authorized_source_bytes, decode_source, detach_psd, other, placement, shift_layer, smart};
use crate::commands::layer_param;
use crate::{EngineError, Result, Session};
/// The smart object's contents as layers in `doc`'s colour model, profile and depth, still in
/// source pixel coordinates. A Background becomes a normal layer (it can't sit above others).
-fn contents(doc: &Document, sm: &SmartObject, intent: Intent, bpc: bool) -> Result<Vec<Layer>> {
- let (name, bytes) = source_bytes(&doc.metadata, &sm.source).ok_or_else(|| other("the smart object's contents are unavailable (missing linked file?)"))?;
+fn contents(s: &Session, doc: &Document, sm: &SmartObject, intent: Intent, bpc: bool) -> Result<Vec<Layer>> {
+ let (name, bytes) = authorized_source_bytes(s, "layer.smartObjects.convertToLayers", &doc.metadata, &sm.source)?
+ .ok_or_else(|| other("the smart object's contents are unavailable (missing linked file?)"))?;
let mut src = decode_source(&name, &bytes)?;
let mode = doc.pixel_format().mode;
if src.pixel_format().mode != mode || src.icc_profile != doc.icc_profile {
@@ -63,7 +64,7 @@ fn embed_nested(meta: &Metadata, l: &mut Layer) {
/// Moves unpacked layers from source pixels to where the smart object placed them: an exact
/// shift for whole-pixel moves, else its transform (type, shapes and nested smart objects stay
/// live; Distort and Perspective need them rasterized, as Free Transform does).
-fn place(doc: &Document, sm: &SmartObject, layers: &mut [Layer]) -> Result<()> {
+fn place(s: &Session, doc: &Document, sm: &SmartObject, layers: &mut [Layer]) -> Result<()> {
if sm.warp.as_ref().is_some_and(|w| !w.is_identity()) {
return Err(other("a warped smart object can't be converted to layers; rasterize it instead (Layer › Smart Objects › Rasterize)"));
}
@@ -74,6 +75,17 @@ fn place(doc: &Document, sm: &SmartObject, layers: &mut [Layer]) -> Result<()> {
layers.iter_mut().for_each(|l| shift_layer(l, e.round() as i32, f.round() as i32));
return Ok(());
}
+ // Unlike a whole-pixel shift, this path re-renders nested smart objects from their sources.
+ // Check every read before transforming anything; refresh_text keeps errors as fallback pixels.
+ if s.authorize.is_some() {
+ let mut pending: Vec<&Layer> = layers.iter().collect();
+ while let Some(l) = pending.pop() {
+ if let LayerContent::Smart(sm) = &l.content {
+ authorize_source(s, "layer.smartObjects.convertToLayers", doc, &sm.source)?;
+ }
+ pending.extend(l.children().into_iter().flatten());
+ }
+ }
let h = placement(sm);
let affine = sm.perspective.is_none().then_some(sm.transform);
for l in layers {
@@ -160,8 +172,8 @@ pub(super) fn convert_to_layers(s: &mut Session, p: &Value) -> Result<Value> {
let doc = &st.doc;
let so = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
let sm = smart(doc, id)?;
- let mut layers = contents(doc, sm, intent, bpc)?;
- place(doc, sm, &mut layers)?;
+ let mut layers = contents(s, doc, sm, intent, bpc)?;
+ place(s, doc, sm, &mut layers)?;
let discarded = sm.smart_filters.len();
let out = unpacked(so, layers);
let (new_id, group) = (out.id, out.is_group());
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 52190b73b..edbfef1a5 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -1452,6 +1452,140 @@ mod tests {
}
}
+ fn deny_smart_object_paths(id: &str, params: &Value) -> photocraft_engine::Result<()> {
+ // The production policy lives in the automation crate. This gate exercises the control
+ // session's state-derived path check without adding that dependency to the UI crate.
+ if matches!(id, "layer.smartObjects.editContents" | "layer.smartObjects.convertToLayers" | "layer.smartObjects.saveContents")
+ && params.get("path").and_then(Value::as_str).is_some()
+ {
+ Err(photocraft_engine::EngineError::Other("ambient smart-object path denied".into()))
+ } else {
+ Ok(())
+ }
+ }
+
+ fn smart_control_app() -> (PhotocraftApp, egui::Context, photocraft_doc::LayerId) {
+ let services = crate::Services {
+ automation_authorize: Some(deny_smart_object_paths),
+ automation_command: Some(Box::new(|id, params| deny_smart_object_paths(id, params).map_err(|e| e.to_string()))),
+ ..Default::default()
+ };
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);
+ app.run("file.new", json!({"width": 8, "height": 6, "background": "transparent"})).unwrap();
+ app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();
+ let id = app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap()["layer"].as_u64().unwrap();
+ (app, egui::Context::default(), photocraft_doc::LayerId(id))
+ }
+
+ #[test]
+ fn control_edits_nested_embedded_smart_objects_and_converts_an_explicit_target() {
+ use photocraft_doc::{LayerContent, SmartSource};
+ use std::cell::RefCell;
+ use std::rc::Rc;
+ use std::sync::Arc;
+
+ let (mut app, ctx, smart) = smart_control_app();
+ // Embed this one-smart-layer document inside the outer object: two Edit Contents
+ // requests must reach the raster layer, as in a nested product-photo template.
+ let nested = photocraft_engine::smart_cmds::encode_source(&app.session.active().unwrap().doc).unwrap();
+ app.session
+ .edit("Nested fixture", |doc, _| {
+ let LayerContent::Smart(sm) = &mut doc.layer_mut(smart).unwrap().content else { panic!("smart fixture") };
+ sm.source = SmartSource::Embedded { file_name: "product.pcraft".into(), bytes: Arc::new(nested) };
+ Ok(())
+ })
+ .unwrap();
+ let other = app.run("layer.new.layer", json!({"name": "Unrelated"})).unwrap()["layer"].as_u64().unwrap();
+ assert_ne!(app.session.active().unwrap().active_layer, Some(smart));
+ for expected_document in [1, 2] {
+ let r = call(&mut app, &ctx, "engine.execute", json!({"command": "layer.smartObjects.editContents", "params": {"layer": smart.0}}));
+ assert_eq!(r["ok"], true, "{r}");
+ assert_eq!(r["result"]["document"], expected_document, "{r}");
+ assert!(app.session.active().unwrap().path.is_none(), "contents open in memory");
+ assert!(app.session.authorize.is_none(), "the request gate must not remain installed");
+ }
+ let r = call(&mut app, &ctx, "engine.execute", json!({"command": "edit.fill", "params": {"color": "#0000ff"}}));
+ assert_eq!(r["ok"], true, "{r}");
+ for expected_documents in [2, 1] {
+ let r = call(&mut app, &ctx, "engine.execute", json!({"command": "layer.smartObjects.saveContents"}));
+ assert_eq!(r["ok"], true, "{r}");
+ let r = call(&mut app, &ctx, "engine.execute", json!({"command": "file.close"}));
+ assert_eq!(r["ok"], true, "{r}");
+ assert_eq!(app.session.documents().len(), expected_documents);
+ }
+ assert_eq!(app.session.active().unwrap().active_layer, Some(photocraft_doc::LayerId(other)));
+ assert_eq!(photocraft_compose::flatten(&app.session.active().unwrap().doc).px[0], [0.0, 0.0, 1.0, 1.0]);
+ let r = call(&mut app, &ctx, "engine.execute", json!({"command": "layer.smartObjects.convertToLayers", "params": {"layer": smart.0}}));
+ assert_eq!(r["ok"], true, "{r}");
+ assert!(app.session.active().unwrap().doc.layer(photocraft_doc::LayerId(other)).is_some(), "the unrelated active layer remains");
+ assert!(app.session.authorize.is_none());
+
+ let written = Rc::new(RefCell::new(Vec::new()));
+ let output = written.clone();
+ app.services.export =
+ Some(Box::new(|doc, _, _| photocraft_engine::smart_cmds::encode_source(doc).map(|bytes| (bytes, Vec::new())).map_err(|e| e.to_string())));
+ app.services.automation_write = Some(Box::new(move |path, bytes| {
+ output.borrow_mut().push((path.to_string(), bytes.to_vec()));
+ Ok(())
+ }));
+ app.services.write = Some(Box::new(|_, _| Err("ambient writer used".into())));
+ let r = call(&mut app, &ctx, "app.save", json!({"path": "out/template.pcraft"}));
+ assert_eq!(r["ok"], true, "{r}");
+ let written = written.borrow();
+ assert_eq!(written.len(), 1);
+ assert_eq!(written[0].0, "out/template.pcraft");
+ let saved = photocraft_engine::smart_cmds::decode_source(&written[0].0, &written[0].1).unwrap();
+ assert_eq!(photocraft_compose::flatten(&saved).px[0], [0.0, 0.0, 1.0, 1.0]);
+ }
+
+ #[test]
+ fn control_refuses_linked_smart_objects_in_commands_and_actions_but_local_editing_still_works() {
+ use photocraft_doc::{LayerContent, SmartSource};
+ use std::sync::Arc;
+
+ let (mut app, ctx, smart) = smart_control_app();
+ let path = std::env::temp_dir().join(format!("pc-control-smart-linked-{}.pcraft", std::process::id()));
+ let st = app.session.active().unwrap();
+ let LayerContent::Smart(sm) = &st.doc.layer(smart).unwrap().content else { panic!("smart fixture") };
+ let SmartSource::Embedded { bytes, .. } = &sm.source else { panic!("embedded fixture") };
+ std::fs::write(&path, bytes.as_slice()).unwrap();
+ app.session
+ .edit("Linked fixture", |doc, _| {
+ let LayerContent::Smart(sm) = &mut doc.layer_mut(smart).unwrap().content else { panic!("smart fixture") };
+ sm.source = SmartSource::Linked { path: path.to_string_lossy().into_owned() };
+ Ok(())
+ })
+ .unwrap();
+ app.run("layer.new.layer", json!({"name": "Unrelated"})).unwrap();
+ let before = app.session.active().unwrap().doc.clone();
+ let active = app.session.active().unwrap().active_layer;
+ for command in ["layer.smartObjects.editContents", "layer.smartObjects.convertToLayers"] {
+ let r = call(&mut app, &ctx, "engine.execute", json!({"command": command, "params": {"layer": smart.0}}));
+ assert_eq!(r["ok"], false, "{r}");
+ assert!(r["error"].as_str().unwrap().contains("ambient smart-object path denied"), "{r}");
+ app.session.actions.list =
+ vec![photocraft_engine::actions_cmds::Action { name: "Linked contents".into(), steps: vec![(command.into(), json!({"layer": smart.0}))] }];
+ let r = call(&mut app, &ctx, "engine.execute", json!({"command": "actions.play", "params": {"action": "Linked contents"}}));
+ assert_eq!(r["ok"], true, "{r}");
+ assert_eq!(r["result"]["ran"], 0, "{r}");
+ assert_eq!(r["result"]["failed"]["id"], command, "{r}");
+ assert_eq!(app.session.documents().len(), 1);
+ assert!(Arc::ptr_eq(&app.session.active().unwrap().doc, &before), "a refused operation must not edit the document");
+ assert_eq!(app.session.active().unwrap().active_layer, active);
+ assert!(app.session.authorize.is_none(), "a refused request must restore the local session");
+ }
+ // A synthetic thumbnail action uses the same temporary authorization as control calls.
+ app.automation_input = true;
+ let error = crate::menus::invoke(&mut app, &ctx, "layer.smartObjects.editContents", json!({"layer": smart.0})).unwrap_err();
+ assert!(error.contains("ambient smart-object path denied"), "{error}");
+ assert!(app.session.authorize.is_none());
+ app.automation_input = false;
+ app.run("layer.smartObjects.editContents", json!({"layer": smart.0})).unwrap();
+ assert_eq!(app.session.documents().len(), 2, "a human can still open the existing linked file");
+ assert_eq!(photocraft_compose::flatten(&app.session.active().unwrap().doc).px[0], [1.0, 0.0, 0.0, 1.0]);
+ std::fs::remove_file(path).unwrap();
+ }
+
#[test]
fn actions_play_checks_each_step_over_control() {
let services = crate::Services { automation_authorize: Some(deny_ambient_file), ..Default::default() };
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 6bef0c47f..45dab6570 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -128,6 +128,17 @@ UI-level commands (`view.zoomIn`, `window.theme.pro`, `edit.search`, …) are al
Commands that read or write files by path, instead of through the automation roots, are refused with "automation command `…` uses ambient filesystem paths and is disabled; use capability-scoped document methods". That covers every `file.*` command except `file.new`, the `file.close*` commands and a few path-free ones such as `file.fileInfo`, so `file.open`, `file.save`, `file.saveAs` and `file.saveACopy` always fail here: open and save with `app.open` / `app.save`. Path parameters of other commands (`layer.exportAs {path}`, `filter.distort.displace {mapPath}`, preset imports, and plug-in install/reload) are refused the same way. `prefs.set` rejects whole-preference updates and file-backed sections (`colorSettings`, `scriptEvents`, `historyLog`, `plugIns` and `scratchDisks`) so automation cannot configure ambient file access indirectly. The desktop app also refuses `image.mode.*`, which can load the colour profiles set in its preferences. The rules are in `crates/automation/src/workspace.rs`.
+Embedded Smart Objects can be opened with `layer.smartObjects.editContents {layer?}` or
+unpacked with `layer.smartObjects.convertToLayers {layer?}`. This includes Photoshop sources
+stored by UUID in the document's embedded linked-layer blocks. Sources requiring a disk read
+remain refused, including nested linked objects that need re-rendering during unpacking.
+In the opened contents document, use `layer.smartObjects.saveContents {}` to update the parent
+in memory, or close the dirty contents document. For nested objects, save from the deepest
+contents outward. `app.save` exports the active document to a scoped file; it is not a substitute
+for Save Contents. Save the parent document to disk when the edits are complete. These rules
+also apply to recorded actions and synthetic UI input; interactive desktop commands retain
+their usual file access. Source replacement, relinking and export commands remain restricted.
+
`type.editText` starts inline editing of the active type layer and selects all its text, like
double-clicking its thumbnail in Layers. Text input, Commit and Cancel use the existing Type tool
editing session; non-type layers return an error without changing the tool or document.
diff --git a/docs/mcp.md b/docs/mcp.md
index 523aa7a82..bb820a74a 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -32,6 +32,15 @@ Tool execution failures return `isError:true`. A worker panic becomes a tool err
existing poisoned-session recovery keeps serving. Invalid JSON lines receive `-32700` with
`id:null`; the next line is still processed.
+Embedded Smart Objects support `command_run` with `layer.smartObjects.editContents` and
+`layer.smartObjects.convertToLayers`, optionally targeting `params.layer`. Use
+`layer.smartObjects.saveContents` in an opened contents document to update its parent in memory;
+save nested contents from the inside outward, then `doc_save` the parent to a scoped path.
+`doc_save` on a contents document exports that document rather than updating its parent.
+No filesystem root is needed for the in-memory commands. External linked sources that require
+a file read remain refused. See the [control policy](control-protocol.md#engine-commands)
+for the shared restrictions.
+
`photocraft://document` and `photocraft://commands` return live JSON matching `doc_inspect`
and `command_list`. Resource reads are uncached; tool/resource catalogs are private and cached
for ten minutes. List/read responses include the MCP 2026-07-28 result/cache fields.