Skip to content

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

automation: export layers, data sets and CSVs through the granted roots (#3216) (#3230)

Gert Pellin - GPEb0e555c60f6c
diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rs
index 9993652e4..fe8c62717 100644
--- a/apps/photocraft-cli/src/lib.rs
+++ b/apps/photocraft-cli/src/lib.rs
@@ -45,7 +45,7 @@ USAGE:
[--automation-read-root <dir>] [--automation-write-root <dir>]
Keep one headless session open and answer JSON lines ({\"id\",\"method\",\"params\"}) on stdio,
or on 127.0.0.1:<port>. Methods: engine.execute, jobs.list/cancel, engine.commands,
- doc.open/new/place/save/inspect/render/select/close, session.list, batch, methods
+ doc.open/new/place/save/exportLayers/exportDataSets/importDataSets/inspect/render/select/close, session.list, batch, methods
(docs/control-protocol.md#headless-server).
photocraft-cli <subcommand> --help (or -h) prints this text. A flag the subcommand doesn't take is
diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs
index 481fbc238..028ca09f1 100644
--- a/crates/automation/src/headless.rs
+++ b/crates/automation/src/headless.rs
@@ -9,7 +9,7 @@ use photocraft_format::PcraftWriter;
use photocraft_io::ExportOptions;
use serde_json::{Value, json};
-use crate::workspace::{authorize_engine_command, authorize_engine_step};
+use crate::workspace::{ExportSequence, authorize_engine_command, authorize_engine_step};
use crate::{AuthorizedWorkspace, AutomationError, files};
fn untrusted(filesystem: Filesystem) -> Headless {
@@ -134,6 +134,85 @@ impl Headless {
Ok(file_cmds::place_bytes(&mut self.session, name, bytes, None, &Value::Object(opts))?)
}
+ /// Export each exported layer of a document as its own file beneath the write root: the
+ /// capability-scoped `file.export.layersToFiles`, which takes an ambient `dir` and is
+ /// therefore refused in automation (#3216). The bytes come from the command's own core, so
+ /// both paths write the same files. The write capability refuses to overwrite a file that
+ /// already exists, where the ambient command would, and it creates the directory before the
+ /// export runs, so a refused export can leave an empty directory behind — never a file.
+ pub fn export_layers(&mut self, index: Option<usize>, dir: &str, params: &Value) -> Result<Value, AutomationError> {
+ let i = self.doc_index(index)?;
+ if self.session.active_index() != Some(i) && !self.session.set_active(i) {
+ return Err(AutomationError::BadRequest(format!("no document at index {i}")));
+ }
+ if matches!(&self.filesystem, Filesystem::TrustedLocal) {
+ let mut opts = params.as_object().cloned().unwrap_or_default();
+ opts.insert("dir".into(), json!(dir));
+ return self.command_run("file.export.layersToFiles", Value::Object(opts));
+ }
+ self.sync_jobs();
+ let workspace = match &self.filesystem {
+ Filesystem::Workspace(workspace) => workspace,
+ _ => return Err(AutomationError::BadRequest("automation filesystem access is not granted: write authority is absent".into())),
+ };
+ let mut outputs = workspace.export_sequence(dir)?;
+ let written = file_cmds::export_layers_with(&self.session, params, |name, bytes| {
+ outputs.write(name, bytes).map_err(|e| photocraft_engine::EngineError::Other(e.to_string()))
+ });
+ exported(dir, written, &mut outputs)
+ }
+
+ /// Export each data set of a document as its own flattened file beneath the write root: the
+ /// capability-scoped `file.export.dataSetsAsFiles` (#3216). As in the command, the whole
+ /// batch is planned first and colliding names are refused before any file is written; the
+ /// directory itself is created before that, so a refused batch can leave it empty behind.
+ pub fn export_data_sets(&mut self, index: Option<usize>, dir: &str, params: &Value) -> Result<Value, AutomationError> {
+ let i = self.doc_index(index)?;
+ if self.session.active_index() != Some(i) && !self.session.set_active(i) {
+ return Err(AutomationError::BadRequest(format!("no document at index {i}")));
+ }
+ if matches!(&self.filesystem, Filesystem::TrustedLocal) {
+ let mut opts = params.as_object().cloned().unwrap_or_default();
+ opts.insert("dir".into(), json!(dir));
+ return self.command_run("file.export.dataSetsAsFiles", Value::Object(opts));
+ }
+ self.sync_jobs();
+ let workspace = match &self.filesystem {
+ Filesystem::Workspace(workspace) => workspace,
+ _ => return Err(AutomationError::BadRequest("automation filesystem access is not granted: write authority is absent".into())),
+ };
+ let mut outputs = workspace.export_sequence(dir)?;
+ let written = photocraft_engine::export_data_sets_with(&self.session, params, |name, bytes| {
+ outputs.write(name, bytes).map_err(|e| photocraft_engine::EngineError::Other(e.to_string()))
+ });
+ exported(dir, written, &mut outputs)
+ }
+
+ /// Import a data set CSV from the read root: the capability-scoped
+ /// `file.import.variableDataSets`, which takes an ambient `path` and is therefore refused
+ /// in automation (#3216). The file is read beneath the root the way `open` reads one and
+ /// handed to the command's own parser over the text it already has.
+ pub fn import_data_sets(&mut self, index: Option<usize>, path: &str, params: &Value) -> Result<Value, AutomationError> {
+ let i = self.doc_index(index)?;
+ if self.session.active_index() != Some(i) && !self.session.set_active(i) {
+ return Err(AutomationError::BadRequest(format!("no document at index {i}")));
+ }
+ if matches!(&self.filesystem, Filesystem::TrustedLocal) {
+ let mut opts = params.as_object().cloned().unwrap_or_default();
+ opts.insert("path".into(), json!(path));
+ return self.command_run("file.import.variableDataSets", Value::Object(opts));
+ }
+ let text = match &self.filesystem {
+ Filesystem::Workspace(workspace) => {
+ let bytes = workspace.read(path)?;
+ String::from_utf8(bytes).map_err(|e| AutomationError::BadRequest(format!("automation read `{path}` is not valid UTF-8: {e}")))?
+ }
+ _ => return Err(AutomationError::BadRequest("automation filesystem access is not granted: read authority is absent".into())),
+ };
+ self.sync_jobs();
+ Ok(photocraft_engine::import_data_sets_text(&mut self.session, &text, params)?)
+ }
+
/// Save (`.pcraft` or any export format by extension). With no path,
/// saves to the document's own path.
pub fn save(&mut self, index: Option<usize>, path: Option<&Path>, format: Option<&str>, opts: &ExportOptions) -> Result<Value, AutomationError> {
@@ -310,3 +389,20 @@ impl Headless {
}
}
}
+
+/// Common tail of the two capability-scoped exports: the sequence keeps what it wrote, or drops
+/// every file it created, so a half-finished export never looks like a finished one.
+fn exported(dir: &str, written: photocraft_engine::Result<Vec<String>>, outputs: &mut ExportSequence) -> Result<Value, AutomationError> {
+ match written {
+ Ok(names) => {
+ outputs.commit();
+ let files: Vec<String> = names.iter().map(|name| format!("{dir}/{name}")).collect();
+ let count = files.len();
+ Ok(json!({"files": files, "count": count}))
+ }
+ Err(error) => {
+ outputs.cleanup()?;
+ Err(error.into())
+ }
+ }
+}
diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs
index 4ba197a53..d513bfa88 100644
--- a/crates/automation/src/rpc.rs
+++ b/crates/automation/src/rpc.rs
@@ -10,7 +10,10 @@
//! - `session.list`, `doc.open {path}`, `doc.new {…file.new params}`,
//! `doc.place {path, scale?, fit?, center?, index?}` (#2810: the read root is the scope,
//! the counterpart of the refused ambient `file.placeEmbedded`),
-//! `doc.save {path?, format?, quality?, index?}`, `doc.inspect {index?}`,
+//! `doc.exportLayers {dir, format?, prefix?, visibleOnly?, quality?, index?}`,
+//! `doc.exportDataSets {dir, format?, dataSets?, naming?, index?}`,
+//! `doc.importDataSets {path, delimiter?, index?}` (#3216: the same treatment for the export
+//! and CSV half of #2810), `doc.save {path?, format?, quality?, index?}`, `doc.inspect {index?}`,
//! `doc.render {index?, maxSide?, path?}` (writes a PNG to `path`, else
//! returns it base64-encoded), `doc.select {index}`, `doc.close {index?}`
//! - `batch {steps: [{command, params?, wait?} | {method, params?}], stopOnError?}`
@@ -42,6 +45,9 @@ pub const METHODS: &[&str] = &[
"doc.place",
"doc.new",
"doc.save",
+ "doc.exportLayers",
+ "doc.exportDataSets",
+ "doc.importDataSets",
"doc.inspect",
"doc.render",
"doc.select",
@@ -100,11 +106,10 @@ impl Headless {
}
"doc.place" => {
let path = str_of(&p, "path").ok_or_else(|| bad("doc.place needs `path`"))?;
- let index = p.get("index").and_then(Value::as_u64).map(|i| i as usize);
let mut opts = p.as_object().cloned().unwrap_or_default();
opts.remove("path");
opts.remove("index");
- self.place(index, path, &Value::Object(opts))
+ self.place(index_of(&p), path, &Value::Object(opts))
}
"doc.new" => self.command_run("file.new", p),
"doc.save" => {
@@ -119,6 +124,21 @@ impl Headless {
let path = str_of(&p, "path").map(PathBuf::from);
self.save(index_of(&p), path.as_deref(), str_of(&p, "format"), &opts)
}
+ "doc.exportLayers" | "doc.exportDataSets" => {
+ let dir = str_of(&p, "dir").ok_or_else(|| bad(format!("{method} needs `dir`")))?;
+ let mut opts = p.as_object().cloned().unwrap_or_default();
+ opts.remove("dir");
+ opts.remove("index");
+ let opts = Value::Object(opts);
+ if method == "doc.exportLayers" { self.export_layers(index_of(&p), dir, &opts) } else { self.export_data_sets(index_of(&p), dir, &opts) }
+ }
+ "doc.importDataSets" => {
+ let path = str_of(&p, "path").ok_or_else(|| bad("doc.importDataSets needs `path`"))?;
+ let mut opts = p.as_object().cloned().unwrap_or_default();
+ opts.remove("path");
+ opts.remove("index");
+ self.import_data_sets(index_of(&p), path, &Value::Object(opts))
+ }
"doc.inspect" => self.inspect(index_of(&p)),
"doc.render" => {
let max = match p.get("maxSide") {
@@ -622,6 +642,81 @@ mod tests {
std::fs::remove_dir_all(base).unwrap();
}
+ #[test]
+ fn doc_export_layers_writes_only_beneath_the_write_root() {
+ let base = std::env::temp_dir().join(format!("pc-doc-export-layers-{}", std::process::id()));
+ let root = base.join("workspace");
+ std::fs::create_dir_all(&root).unwrap();
+ let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap());
+ h.handle("doc.new", json!({"width": 12, "height": 8, "background": "white", "name": "card"})).unwrap();
+ h.handle("engine.execute", json!({"command": "layer.new.layer", "params": {"name": "Badge"}})).unwrap();
+
+ let out = root.join("out");
+ let exported = h.handle("doc.exportLayers", json!({"dir": out.to_string_lossy(), "format": "png", "prefix": "card"})).unwrap();
+ assert_eq!(exported["count"].as_u64(), Some(2), "{exported}");
+ let mut names: Vec<String> = std::fs::read_dir(&out).unwrap().map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()).collect();
+ names.sort();
+ assert_eq!(names.len(), 2, "{exported}");
+ for name in names {
+ assert!(name.starts_with("card_") && name.ends_with(".png"), "{name}");
+ let bytes = std::fs::read(out.join(&name)).unwrap();
+ assert_eq!(photocraft_codecs::decode(&bytes).unwrap().dimensions(), (12, 8), "{name}");
+ }
+ // Outside the write root nothing is created, not even the directory.
+ let escaped = base.join("escaped");
+ let refused = h.handle("doc.exportLayers", json!({"dir": escaped.to_string_lossy()})).unwrap_err().to_string();
+ assert!(refused.contains("must be inside the automation root"), "{refused}");
+ assert!(!escaped.exists());
+ // The ambient command keeps its refusal for the very same directory.
+ let ambient =
+ h.handle("engine.execute", json!({"command": "file.export.layersToFiles", "params": {"dir": out.to_string_lossy()}})).unwrap_err().to_string();
+ assert!(ambient.contains("ambient filesystem paths"), "{ambient}");
+ // Release directory capabilities before cleanup on Windows.
+ drop(h);
+ std::fs::remove_dir_all(base).unwrap();
+ }
+
+ #[test]
+ fn doc_export_data_sets_refuse_collisions_and_import_reads_the_root() {
+ let base = std::env::temp_dir().join(format!("pc-doc-data-sets-{}", std::process::id()));
+ let root = base.join("workspace");
+ std::fs::create_dir_all(&root).unwrap();
+ let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap());
+ h.handle("doc.new", json!({"width": 8, "height": 8, "background": "white", "name": "card"})).unwrap();
+ let inspected = h.handle("doc.inspect", json!({})).unwrap();
+ let layer = inspected["layers"][0]["id"].as_u64().expect("the layer id");
+ h.handle("engine.execute", json!({"command": "image.variables.define", "params": {"defs": [{"name": "show", "layer": layer, "type": "visibility"}]}}))
+ .unwrap();
+ h.handle(
+ "engine.execute",
+ json!({"command": "image.variables.dataSets", "params": {"dataSets": [
+ {"name": "one", "values": [{"variable": "show", "kind": "visibility", "value": true}]},
+ {"name": "two", "values": [{"variable": "show", "kind": "visibility", "value": false}]},
+ ]}}),
+ )
+ .unwrap();
+
+ let sets = root.join("sets");
+ let exported = h.handle("doc.exportDataSets", json!({"dir": sets.to_string_lossy(), "format": "png"})).unwrap();
+ assert_eq!(exported["count"].as_u64(), Some(2), "{exported}");
+ assert_eq!(std::fs::read_dir(&sets).unwrap().count(), 2, "{exported}");
+ // Colliding names are refused as in the command, before any file is written.
+ let clash = root.join("clash");
+ let refused = h.handle("doc.exportDataSets", json!({"dir": clash.to_string_lossy(), "naming": "{document}"})).unwrap_err().to_string();
+ assert!(refused.contains("{index}"), "{refused}");
+ assert_eq!(std::fs::read_dir(&clash).unwrap().count(), 0, "no file of the refused batch");
+ // A CSV from the read root, and one outside it.
+ std::fs::write(root.join("sets.csv"), "Data Set,show\none,true\ntwo,false\n").unwrap();
+ let imported = h.handle("doc.importDataSets", json!({"path": "sets.csv"})).unwrap();
+ assert_eq!(imported["imported"].as_u64(), Some(2), "{imported}");
+ std::fs::write(base.join("outside.csv"), "Data Set,show\none,true\n").unwrap();
+ let outside = h.handle("doc.importDataSets", json!({"path": base.join("outside.csv").to_string_lossy()})).unwrap_err().to_string();
+ assert!(outside.contains("must be inside the automation root"), "{outside}");
+ // Release directory capabilities before cleanup on Windows.
+ drop(h);
+ std::fs::remove_dir_all(base).unwrap();
+ }
+
#[test]
fn trusted_local_render_keeps_full_size_behavior() {
let mut h = Headless::trusted_local();
diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs
index 43d106e2a..afababe64 100644
--- a/crates/automation/src/server.rs
+++ b/crates/automation/src/server.rs
@@ -71,6 +71,60 @@ pub struct PlaceParams {
pub center: Option<[f64; 2]>,
}
+#[derive(Debug, Default, Deserialize, JsonSchema)]
+#[serde(deny_unknown_fields)]
+pub struct ExportLayersParams {
+ /// Directory beneath the configured automation write root: relative (forward slashes) or absolute.
+ pub dir: String,
+ /// Document index from `session_list` (default: the active document).
+ #[serde(default)]
+ pub index: Option<usize>,
+ /// Export format (default png).
+ #[serde(default)]
+ pub format: Option<String>,
+ /// Filename prefix (default: the document name).
+ #[serde(default)]
+ pub prefix: Option<String>,
+ /// Export only the layers that are visible (default true).
+ #[serde(default, rename = "visible_only")]
+ pub visible_only: Option<bool>,
+ /// Encoder quality, 0..12, for the formats that take one.
+ #[serde(default)]
+ pub quality: Option<f64>,
+}
+
+#[derive(Debug, Default, Deserialize, JsonSchema)]
+#[serde(deny_unknown_fields)]
+pub struct ExportDataSetsParams {
+ /// Directory beneath the configured automation write root: relative (forward slashes) or absolute.
+ pub dir: String,
+ /// Document index from `session_list` (default: the active document).
+ #[serde(default)]
+ pub index: Option<usize>,
+ /// Export format (default png).
+ #[serde(default)]
+ pub format: Option<String>,
+ /// Only these data sets, by name; default every one of them.
+ #[serde(default, rename = "data_sets")]
+ pub data_sets: Option<Vec<String>>,
+ /// Filename template with `{name}`, `{index}` and `{document}` (default `{name}`).
+ #[serde(default)]
+ pub naming: Option<String>,
+}
+
+#[derive(Debug, Default, Deserialize, JsonSchema)]
+#[serde(deny_unknown_fields)]
+pub struct ImportDataSetsParams {
+ /// Path beneath the configured automation read root: relative (forward slashes) or absolute.
+ pub path: String,
+ /// Document index from `session_list` (default: the active document).
+ #[serde(default)]
+ pub index: Option<usize>,
+ /// Field delimiter (default `,`).
+ #[serde(default)]
+ pub delimiter: Option<String>,
+}
+
#[derive(Debug, Default, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct NewParams {
@@ -566,6 +620,80 @@ impl PhotocraftMcp {
self.run_command("file.placeEmbedded".into(), bridge_params, true).await
}
+ #[tool(
+ description = "Export each exported layer of the document as its own file beneath the write root (the capability-scoped Layers to Files). A file that already exists is an error, not an overwrite."
+ )]
+ async fn doc_export_layers(&self, Parameters(p): Parameters<ExportLayersParams>) -> Result<CallToolResult, McpError> {
+ let mut opts = serde_json::Map::new();
+ if let Some(v) = p.format {
+ opts.insert("format".into(), json!(v));
+ }
+ if let Some(v) = p.prefix {
+ opts.insert("prefix".into(), json!(v));
+ }
+ if let Some(v) = p.visible_only {
+ opts.insert("visibleOnly".into(), json!(v));
+ }
+ if let Some(v) = p.quality {
+ opts.insert("quality".into(), json!(v));
+ }
+ let opts = Value::Object(opts);
+ // Bridge mode runs the app on this machine, which writes its own paths like any command.
+ let mut bridge_params = opts.clone();
+ if let Some(o) = bridge_params.as_object_mut() {
+ o.insert("dir".into(), Value::String(p.dir.clone()));
+ }
+ let (dir, index) = (p.dir, p.index);
+ if let Some(r) = self.headless_op(move |h| h.export_layers(index, &dir, &opts)).await {
+ return to_result(r);
+ }
+ self.run_command("file.export.layersToFiles".into(), bridge_params, true).await
+ }
+
+ #[tool(
+ description = "Export every data set of the document as its own flattened file beneath the write root (the capability-scoped Export Data Sets). The batch is planned first, so colliding filenames are refused before any file is written."
+ )]
+ async fn doc_export_data_sets(&self, Parameters(p): Parameters<ExportDataSetsParams>) -> Result<CallToolResult, McpError> {
+ let mut opts = serde_json::Map::new();
+ if let Some(v) = p.format {
+ opts.insert("format".into(), json!(v));
+ }
+ if let Some(v) = p.data_sets {
+ opts.insert("dataSets".into(), json!(v));
+ }
+ if let Some(v) = p.naming {
+ opts.insert("naming".into(), json!(v));
+ }
+ let opts = Value::Object(opts);
+ let mut bridge_params = opts.clone();
+ if let Some(o) = bridge_params.as_object_mut() {
+ o.insert("dir".into(), Value::String(p.dir.clone()));
+ }
+ let (dir, index) = (p.dir, p.index);
+ if let Some(r) = self.headless_op(move |h| h.export_data_sets(index, &dir, &opts)).await {
+ return to_result(r);
+ }
+ self.run_command("file.export.dataSetsAsFiles".into(), bridge_params, true).await
+ }
+
+ #[tool(description = "Import a data set CSV from the read root into the document (the capability-scoped Import Variable Data Sets).")]
+ async fn doc_import_data_sets(&self, Parameters(p): Parameters<ImportDataSetsParams>) -> Result<CallToolResult, McpError> {
+ let mut opts = serde_json::Map::new();
+ if let Some(v) = p.delimiter {
+ opts.insert("delimiter".into(), json!(v));
+ }
+ let opts = Value::Object(opts);
+ let mut bridge_params = opts.clone();
+ if let Some(o) = bridge_params.as_object_mut() {
+ o.insert("path".into(), Value::String(p.path.clone()));
+ }
+ let (path, index) = (p.path, p.index);
+ if let Some(r) = self.headless_op(move |h| h.import_data_sets(index, &path, &opts)).await {
+ return to_result(r);
+ }
+ self.run_command("file.import.variableDataSets".into(), bridge_params, true).await
+ }
+
#[tool(description = "Create a new document (defaults: 1920x1080 RGB 8-bit white).")]
async fn doc_new(&self, Parameters(p): Parameters<NewParams>) -> Result<CallToolResult, McpError> {
let mut params = serde_json::Map::new();
diff --git a/crates/automation/tests/mcp.rs b/crates/automation/tests/mcp.rs
index abcc3b0c9..32dae06af 100644
--- a/crates/automation/tests/mcp.rs
+++ b/crates/automation/tests/mcp.rs
@@ -80,6 +80,9 @@ async fn lists_expected_tools() {
"doc_open",
"doc_new",
"doc_place",
+ "doc_export_layers",
+ "doc_export_data_sets",
+ "doc_import_data_sets",
"doc_save",
"doc_export",
"doc_inspect",
@@ -651,6 +654,68 @@ async fn doc_place_is_capability_scoped() {
cleanup(&base);
}
+/// #3216: the export half of #2810. The write root scopes both exports, the read root the CSV,
+/// and the three ambient commands keep their refusal.
+#[tokio::test(flavor = "multi_thread")]
+async fn doc_exports_and_data_set_import_are_capability_scoped() {
+ let base = tmp("export");
+ let root = base.join("workspace");
+ std::fs::create_dir_all(&root).unwrap();
+ let client = connect(headless_in(&root)).await;
+
+ json_of(&call(&client, "doc_new", json!({"width": 10, "height": 6, "background": "white", "name": "card"})).await);
+ let inspected = json_of(&call(&client, "doc_inspect", json!({})).await);
+ let layer = inspected["layers"][0]["id"].clone();
+ json_of(
+ &call(&client, "command_run", json!({"id": "image.variables.define", "params": {"defs": [{"name": "show", "layer": layer, "type": "visibility"}]}}))
+ .await,
+ );
+ json_of(
+ &call(
+ &client,
+ "command_run",
+ json!({"id": "image.variables.dataSets", "params": {"dataSets": [
+ {"name": "one", "values": [{"variable": "show", "kind": "visibility", "value": true}]},
+ {"name": "two", "values": [{"variable": "show", "kind": "visibility", "value": false}]},
+ ]}}),
+ )
+ .await,
+ );
+
+ let layers = call(&client, "doc_export_layers", json!({"dir": "layers", "prefix": "card"})).await;
+ assert_ne!(layers.is_error, Some(true), "{}", text(&layers));
+ assert_eq!(json_of(&layers)["count"], 1, "{}", text(&layers));
+ assert_eq!(std::fs::read_dir(root.join("layers")).unwrap().count(), 1);
+ let sets = call(&client, "doc_export_data_sets", json!({"dir": "sets", "format": "png"})).await;
+ assert_ne!(sets.is_error, Some(true), "{}", text(&sets));
+ assert_eq!(json_of(&sets)["count"], 2, "{}", text(&sets));
+ assert_eq!(std::fs::read_dir(root.join("sets")).unwrap().count(), 2);
+ // A colliding template is refused before any file of the batch is written.
+ let clash = call(&client, "doc_export_data_sets", json!({"dir": "clash", "naming": "{document}"})).await;
+ assert_eq!(clash.is_error, Some(true), "{}", text(&clash));
+ assert_eq!(std::fs::read_dir(root.join("clash")).unwrap().count(), 0);
+ // A CSV from the read root.
+ std::fs::write(root.join("sets.csv"), "Data Set,show\none,true\n").unwrap();
+ let imported = call(&client, "doc_import_data_sets", json!({"path": "sets.csv"})).await;
+ assert_ne!(imported.is_error, Some(true), "{}", text(&imported));
+ assert_eq!(json_of(&imported)["imported"], 1, "{}", text(&imported));
+
+ // Outside the roots nothing happens at all.
+ let escaped = call(&client, "doc_export_layers", json!({"dir": base.join("escaped").to_string_lossy()})).await;
+ assert_eq!(escaped.is_error, Some(true), "{}", text(&escaped));
+ assert!(!base.join("escaped").exists());
+ std::fs::write(base.join("outside.csv"), "Data Set,show\none,true\n").unwrap();
+ let outside = call(&client, "doc_import_data_sets", json!({"path": base.join("outside.csv").to_string_lossy()})).await;
+ assert_eq!(outside.is_error, Some(true), "{}", text(&outside));
+ for command in ["file.export.layersToFiles", "file.export.dataSetsAsFiles", "file.import.variableDataSets"] {
+ let refused = call(&client, "command_run", json!({"id": command, "params": {}})).await;
+ assert_eq!(refused.is_error, Some(true), "{command}");
+ assert!(text(&refused).contains("ambient filesystem paths"), "{}", text(&refused));
+ }
+ client.cancel().await.unwrap();
+ 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() {
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index 32298b895..490a44a9a 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -1114,13 +1114,24 @@ fn flatten_all_masks(s: &mut Session) -> Result<Value> {
fn layers_to_files(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "file.export.layersToFiles";
let dir = str_param(p, "dir", cmd).or_else(|_| str_param(p, "output", cmd))?.to_string();
+ let names = export_layers_with(s, p, |name, bytes| write_file(&join(&dir, name), bytes))?;
+ let files: Vec<String> = names.iter().map(|name| join(&dir, name)).collect();
+ Ok(json!({"files": files}))
+}
+
+/// The bodies of `file.export.layersToFiles`, streamed to `write` as a single-component filename
+/// plus its bytes: one file per exported layer (top to bottom, like Photoshop's numbering),
+/// encoded but never touched as a path. Automation writes exactly these bytes beneath its write
+/// root (#3216), so the two paths cannot drift. Returns the filenames written, in order.
+pub fn export_layers_with(s: &Session, p: &Value, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result<Vec<String>> {
+ let cmd = "file.export.layersToFiles";
let format = p.get("format").and_then(Value::as_str).unwrap_or("png").trim_start_matches('.').to_ascii_lowercase();
let visible_only = p.get("visibleOnly").and_then(Value::as_bool).unwrap_or(true);
let save = SaveOpts::from_params(s, p, cmd)?;
let d = s.active().ok_or(EngineError::NoDocument)?;
let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name));
let doc = d.doc.clone();
- let mut files = Vec::new();
+ let mut written = Vec::new();
// Top-level layers (groups export merged), top to bottom like Photoshop's numbering.
let layers: Vec<&Layer> = doc.layers.iter().rev().filter(|l| l.visible || !visible_only).collect();
for (i, l) in layers.iter().enumerate() {
@@ -1132,11 +1143,12 @@ fn layers_to_files(s: &mut Session, p: &Value) -> Result<Value> {
only.visible = true;
only.clipped = false;
one.layers = vec![only];
- let path = join(&dir, &format!("{}_{:04}_{}.{format}", sanitize(&prefix), i, sanitize(&l.name)));
- save_doc(&one, &path, save)?;
- files.push(path);
+ let name = format!("{}_{:04}_{}.{format}", sanitize(&prefix), i, sanitize(&l.name));
+ let (bytes, _warnings) = encode(&one, &name, save)?;
+ write(&name, &bytes)?;
+ written.push(name);
}
- Ok(json!({"files": files}))
+ Ok(written)
}
/// Adjustment layers that can be represented as an RGB-only LUT, in document stack order.
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 29ea119e1..17539ab30 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -114,6 +114,7 @@ pub mod type_mask_cmds;
pub mod type_spell_cmds;
pub mod type_styles_cmds;
mod variables_cmds;
+pub use variables_cmds::{export_data_sets_with, import_data_sets_text};
pub mod vector_cmds;
mod video_cmds;
pub use video_cmds::render_video_with;
diff --git a/crates/engine/src/variables_cmds.rs b/crates/engine/src/variables_cmds.rs
index 507861090..f42b74484 100644
--- a/crates/engine/src/variables_cmds.rs
+++ b/crates/engine/src/variables_cmds.rs
@@ -276,10 +276,16 @@ fn resolve_set(s: &Session, p: &Value, cmd: &str) -> Result<(DataSet, usize)> {
/// variable, else text. The first column may be a data-set name (header empty or `DataSet`).
fn import_data_sets(s: &mut Session, p: &Value) -> Result<Value> {
let path = p.get("path").and_then(Value::as_str).ok_or_else(|| bad("file.import.variableDataSets", "need `path`"))?;
- let delim = p.get("delimiter").and_then(Value::as_str).and_then(|d| d.bytes().next()).unwrap_or(b',');
let text = std::fs::read_to_string(path).map_err(|e| EngineError::Other(format!("read `{path}`: {e}")))?;
+ import_data_sets_text(s, &text, p)
+}
+
+/// The body of `file.import.variableDataSets` over CSV text already read: automation reads the
+/// file beneath its read root and hands the text over (#3216).
+pub fn import_data_sets_text(s: &mut Session, text: &str, p: &Value) -> Result<Value> {
+ let delim = p.get("delimiter").and_then(Value::as_str).and_then(|d| d.bytes().next()).unwrap_or(b',');
let vars = s.active().ok_or(EngineError::NoDocument)?.doc.variables.clone();
- let mut records = csv_records(&text).filter(|r| !r.trim().is_empty());
+ let mut records = csv_records(text).filter(|r| !r.trim().is_empty());
let header: Vec<String> = records.next().map(|h| split_csv(h, delim)).unwrap_or_default();
if header.is_empty() {
return Err(bad("file.import.variableDataSets", "empty CSV"));
@@ -366,9 +372,30 @@ fn split_csv(line: &str, delim: u8) -> Vec<String> {
}
/// Apply each data set in turn and export the flattened document, restoring the original after.
-/// `{dir, format?("png"), dataSets?[names]}` → `{files:[…]}`.
+/// `{dir, format?("png"), dataSets?[names]}` → `{files:[…],count}`.
fn export_as_files(s: &mut Session, p: &Value) -> Result<Value> {
- let dir = p.get("dir").and_then(Value::as_str).ok_or_else(|| bad("file.export.dataSetsAsFiles", "need `dir`"))?;
+ let dir = p.get("dir").and_then(Value::as_str).ok_or_else(|| bad("file.export.dataSetsAsFiles", "need `dir`"))?.to_string();
+ // The directory appears only once the batch has been planned, as it always did, so a batch
+ // rejected for colliding names still leaves no directory behind.
+ let mut made_dir = false;
+ let names = export_data_sets_with(s, p, |name, bytes| {
+ if !made_dir {
+ std::fs::create_dir_all(&dir).map_err(|e| EngineError::Other(format!("mkdir `{dir}`: {e}")))?;
+ made_dir = true;
+ }
+ crate::file_cmds::write_file(&format!("{dir}/{name}"), bytes)
+ })?;
+ let files: Vec<String> = names.iter().map(|name| format!("{dir}/{name}")).collect();
+ let count = files.len();
+ Ok(json!({"files": files, "count": count}))
+}
+
+/// The bodies of `file.export.dataSetsAsFiles`, streamed to `write` as a single-component
+/// filename plus its bytes: one flattened file per data set. The whole batch is planned first,
+/// so colliding names are rejected before any file is written, and automation writes exactly
+/// these bytes beneath its write root (#3216) — the two paths cannot drift. Returns the
+/// filenames written, in order.
+pub fn export_data_sets_with(s: &Session, p: &Value, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result<Vec<String>> {
let format = p.get("format").and_then(Value::as_str).unwrap_or("png");
let st = s.active().ok_or(EngineError::NoDocument)?;
let original = st.doc.clone();
@@ -384,28 +411,29 @@ fn export_as_files(s: &mut Session, p: &Value) -> Result<Value> {
// Plan the whole batch before writing: sanitised names or a constant template may collide.
// Match the case-insensitive comparison used by the other batch exporters.
let mut claimed = std::collections::HashMap::new();
- let mut files = Vec::new();
+ let mut names = Vec::new();
for (n, set) in sets.iter().enumerate() {
let safe: String = set.name.chars().map(|c| if c.is_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect();
let stem = template.replace("{name}", &safe).replace("{index}", &format!("{:03}", n + 1)).replace("{document}", &doc_stem);
- let path = format!("{dir}/{stem}.{format}");
- if let Some(first) = claimed.insert(path.to_lowercase(), &set.name) {
+ let name = format!("{stem}.{format}");
+ if let Some(first) = claimed.insert(name.to_lowercase(), &set.name) {
return Err(bad(
"file.export.dataSetsAsFiles",
- format!("data sets `{first}` and `{}` resolve to the same output `{path}`; include {{index}} in `naming` to use distinct filenames", set.name),
+ format!("data sets `{first}` and `{}` resolve to the same output `{name}`; include {{index}} in `naming` to use distinct filenames", set.name),
));
}
- files.push(path);
+ names.push(name);
}
- std::fs::create_dir_all(dir).map_err(|e| EngineError::Other(format!("mkdir `{dir}`: {e}")))?;
- for (set, path) in sets.iter().zip(&files) {
+ let mut written = Vec::new();
+ for (set, name) in sets.iter().zip(&names) {
let mut doc = (*original).clone();
apply_to_doc(&mut doc, &vars, set)?;
let opts = photocraft_io::ExportOptions::default();
let bytes = photocraft_io::export(&doc, format, &opts).map(|r| r.bytes).map_err(|e| EngineError::Other(format!("export `{}`: {e}", set.name)))?;
- crate::file_cmds::write_file(path, &bytes)?;
+ write(name, &bytes)?;
+ written.push(name.clone());
}
- Ok(json!({"files": files, "count": files.len()}))
+ Ok(written)
}
fn list(s: &mut Session) -> Result<Value> {
diff --git a/docs/architecture.md b/docs/architecture.md
index e7e99ea33..893617a92 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -467,6 +467,7 @@ psd/src/
- **`automation`:** an MCP server built on `rmcp`. Its tool names use underscores (the dotted
names such as `doc.open` belong to the JSON control protocol, `docs/control-protocol.md`). It exposes:
- `session_list`, `doc_open`, `doc_new`, `doc_place` (place from the read root as a Smart Object),
+ `doc_export_layers`, `doc_export_data_sets` (write beneath the write root), `doc_import_data_sets` (a CSV from the read root),
`doc_save`, `doc_export`, `doc_inspect` (layer tree as JSON), `doc_render_preview` (PNG), `doc_select`, `doc_close`.
- `command_list`, `command_run` and `command_batch`, generated from the registry; `jobs_list` and `jobs_cancel` for background jobs.
- Bridge only (a running app): `ui_inspect`, `ui_screenshot`, `ui_pointer`, `ui_menu_invoke`, `ui_set`, `control_call`. The full list is in `docs/development.md` › MCP.
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index df4df7089..e50e34fd0 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -263,6 +263,9 @@ How each MCP tool maps onto control methods in bridge mode:
| `doc_inspect` | `engine.execute {command: "document.inspect"}` |
| `doc_open {path}` | `app.open {path}` |
| `doc_place {path, …}` | `engine.execute {command: "file.placeEmbedded", params}` |
+| `doc_export_layers {dir, …}` | `engine.execute {command: "file.export.layersToFiles", params}` |
+| `doc_export_data_sets {dir, …}` | `engine.execute {command: "file.export.dataSetsAsFiles", params}` |
+| `doc_import_data_sets {path, …}` | `engine.execute {command: "file.import.variableDataSets", params}` |
| `doc_save {path?, tgaBits?}` / `doc_export {path, tgaBits?}` | `app.save {path?, tgaBits?}` |
| `doc_render_preview {max_side?}` | `ui.screenshot`, returned directly as PNG image content |
| `session_list`, `ui_inspect` | `ui.inspect` |
@@ -317,6 +320,9 @@ no MCP framing, no app start-up per command. Configure its file access with the
| `session.list` | open documents and the active index |
| `doc.open` / `doc.new` | `{path}` / `file.new` params |
| `doc.place` | `{path, scale? (percent), fit? (true), center? ([x, y]), index?}`: places a file as a Smart Object layer above the active one and returns `{layer, scale, bounds}`. `path` resolves beneath the read root, so this is the capability-scoped `file.placeEmbedded` — that command itself still refuses an ambient path |
+| `doc.exportLayers` | `{dir, format? (png), prefix?, visibleOnly? (true), quality?, index?}` → `{files, count}`: one file per exported layer, named like `file.export.layersToFiles` names them. `dir` resolves beneath the write root, so the ambient command stays refused. The bytes come from the command's own core, so both paths write the same files; the write capability refuses to overwrite an existing file |
+| `doc.exportDataSets` | `{dir, format? (png), dataSets? (all), naming? ("{name}\|{index}\|{document}"), index?}` → `{files, count}`: the capability-scoped `file.export.dataSetsAsFiles`. The batch is planned first and colliding names are refused before any file is written, as in the command |
+| `doc.importDataSets` | `{path, delimiter? (,), index?}` → `{imported}`: the capability-scoped `file.import.variableDataSets`; the CSV is read beneath the read root |
| `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tgaBits?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tgaBits` 24 or 32 sets a TGA's bits per pixel, as `app.save` does). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty |
| `doc.inspect` | `{index?}`: same JSON as `document.inspect` |
| `doc.render` | `{index?, maxSide? (1024; 0 = full), path?}`: PNG to `path`, else `{mime, base64}` |
diff --git a/docs/development.md b/docs/development.md
index 6eac94c6c..5baf62bc1 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -187,7 +187,7 @@ For headless MCP clients, pass absolute paths to deliberately chosen trusted wor
Tools:
- `session_list`
-- `doc_open`, `doc_new`, `doc_place`, `doc_save`, `doc_export`, `doc_inspect`, `doc_render_preview` (returns a PNG image), `doc_select`, `doc_close`
+- `doc_open`, `doc_new`, `doc_place`, `doc_export_layers`, `doc_export_data_sets`, `doc_import_data_sets`, `doc_save`, `doc_export`, `doc_inspect`, `doc_render_preview` (returns a PNG image), `doc_select`, `doc_close`
- `command_list`, `command_run`, `command_batch` (several commands per call)
- `jobs_list` (running background jobs with progress, then recently finished ones with their result or error), `jobs_cancel` (one job by id, or every running job)
- bridge only: `ui_inspect`, `ui_screenshot`, `ui_pointer`, `ui_menu_invoke`, `ui_set`, `control_call`