Skip to content

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

automation: doc.place reads a file through the read root (#2810) (#3215)

Gert Pellin - GPE886372812d71
diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rs
index 4af8839e6..9993652e4 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/save/inspect/render/select/close, session.list, batch, methods
+ doc.open/new/place/save/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 afdceaead..481fbc238 100644
--- a/crates/automation/src/headless.rs
+++ b/crates/automation/src/headless.rs
@@ -106,6 +106,34 @@ impl Headless {
}))
}
+ /// Place a file into a document as a Smart Object layer: the capability-scoped counterpart
+ /// of `file.placeEmbedded`, which reads an ambient path and is therefore refused in
+ /// automation (#2810). `path` resolves beneath the read root the way `open` resolves one,
+ /// and `params` carries the command's own options (`scale`, `fit`, `center`).
+ pub fn place(&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}")));
+ }
+ let mut opts = params.as_object().cloned().unwrap_or_default();
+ opts.insert("path".into(), json!(path));
+ // Where ambient paths are allowed the command reads the file itself, as everywhere else.
+ if matches!(&self.filesystem, Filesystem::TrustedLocal) {
+ return self.command_run("file.placeEmbedded", Value::Object(opts));
+ }
+ let bytes = match &self.filesystem {
+ Filesystem::Workspace(workspace) => workspace.read(path)?,
+ _ => {
+ return Err(AutomationError::BadRequest("automation filesystem access is not granted: read authority is absent".into()));
+ }
+ };
+ let name = Path::new(path).file_name().and_then(|name| name.to_str()).unwrap_or(path);
+ self.sync_jobs();
+ // The bytes are already in memory and the path resolved beneath the root capability, so
+ // placing them needs no filesystem check of its own (`place_bytes` is the command body).
+ Ok(file_cmds::place_bytes(&mut self.session, name, bytes, None, &Value::Object(opts))?)
+ }
+
/// 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> {
diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs
index 8847aec70..4ba197a53 100644
--- a/crates/automation/src/rpc.rs
+++ b/crates/automation/src/rpc.rs
@@ -8,6 +8,8 @@
//! - `engine.execute {command, params?, wait?}` / `engine.commands {filter?}`
//! - `jobs.list` / `jobs.cancel {job?}`: background jobs (#210)
//! - `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.render {index?, maxSide?, path?}` (writes a PNG to `path`, else
//! returns it base64-encoded), `doc.select {index}`, `doc.close {index?}`
@@ -37,6 +39,7 @@ pub const METHODS: &[&str] = &[
"engine.commands",
"session.list",
"doc.open",
+ "doc.place",
"doc.new",
"doc.save",
"doc.inspect",
@@ -95,6 +98,14 @@ impl Headless {
let path = str_of(&p, "path").ok_or_else(|| bad("doc.open needs `path`"))?;
self.open(&PathBuf::from(path))
}
+ "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))
+ }
"doc.new" => self.command_run("file.new", p),
"doc.save" => {
let tga_bits = photocraft_engine::file_cmds::tga_bits_param(&p, "doc.save").map_err(|e| bad(e.to_string()))?;
@@ -572,6 +583,45 @@ mod tests {
std::fs::remove_dir(root).unwrap();
}
+ #[test]
+ fn doc_place_reads_through_the_read_root_and_never_outside_it() {
+ let base = std::env::temp_dir().join(format!("pc-doc-place-{}", std::process::id()));
+ let root = base.join("workspace");
+ let outside = base.join("outside");
+ for dir in [&root, &outside] {
+ std::fs::create_dir_all(dir).unwrap();
+ }
+ let img = photocraft_codecs::Image::from_u8(8, 6, photocraft_codecs::ChannelLayout::Rgb, vec![42; 8 * 6 * 3]).unwrap();
+ let png = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap();
+ std::fs::write(root.join("logo.png"), &png).unwrap();
+ std::fs::write(outside.join("logo.png"), &png).unwrap();
+ let absolute = outside.join("logo.png").to_string_lossy().into_owned();
+
+ let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap());
+ h.handle("doc.new", json!({"width": 40, "height": 30})).unwrap();
+ let placed = h.handle("doc.place", json!({"path": "logo.png", "scale": 50})).unwrap();
+ assert!(placed["layer"].as_u64().is_some(), "{placed}");
+ assert_eq!(placed["scale"].as_f64(), Some(50.0), "the options reach the command: {placed}");
+ let inspected = h.handle("doc.inspect", json!({})).unwrap();
+ assert_eq!(inspected["layers"].as_array().map(Vec::len), Some(2), "the placed layer is in the document: {inspected}");
+ // A path outside the read root is refused the way the ambient command is (#2810).
+ for (path, reason) in [("../outside/logo.png", "parent traversal"), (absolute.as_str(), "must be inside the automation root")] {
+ let refused = h.handle("doc.place", json!({"path": path})).unwrap_err().to_string();
+ assert!(refused.contains(reason), "{refused}");
+ let inspected = h.handle("doc.inspect", json!({})).unwrap();
+ assert_eq!(inspected["layers"].as_array().map(Vec::len), Some(2), "nothing was placed: {refused}");
+ }
+ // Trusted local keeps the ambient command: that caller may read the path itself.
+ let mut t = Headless::trusted_local();
+ t.handle("doc.new", json!({"width": 40, "height": 30})).unwrap();
+ let trusted = t.handle("doc.place", json!({"path": root.join("logo.png").to_string_lossy()})).unwrap();
+ assert!(trusted["layer"].as_u64().is_some(), "{trusted}");
+ // Release directory capabilities before cleanup on Windows.
+ drop(t);
+ 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 24da196bf..43d106e2a 100644
--- a/crates/automation/src/server.rs
+++ b/crates/automation/src/server.rs
@@ -52,6 +52,25 @@ pub struct OpenParams {
pub path: String,
}
+#[derive(Debug, Default, Deserialize, JsonSchema)]
+#[serde(deny_unknown_fields)]
+pub struct PlaceParams {
+ /// 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>,
+ /// Scale as a percentage; defaults to fitting a file larger than the canvas.
+ #[serde(default)]
+ pub scale: Option<f64>,
+ /// Place at a centred size instead of a scaled one.
+ #[serde(default)]
+ pub fit: Option<bool>,
+ /// Centre of the placed layer, in document pixels.
+ #[serde(default)]
+ pub center: Option<[f64; 2]>,
+}
+
#[derive(Debug, Default, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct NewParams {
@@ -520,6 +539,33 @@ impl PhotocraftMcp {
to_result(b.call("app.open", json!({"path": p.path})).await)
}
+ #[tool(
+ description = "Place a file into the document as a Smart Object layer (Place Embedded), reading `path` beneath the read root. `scale` (percent), `fit` and `center` are the command's own."
+ )]
+ async fn doc_place(&self, Parameters(p): Parameters<PlaceParams>) -> Result<CallToolResult, McpError> {
+ let mut opts = serde_json::Map::new();
+ if let Some(v) = p.scale {
+ opts.insert("scale".into(), json!(v));
+ }
+ if let Some(v) = p.fit {
+ opts.insert("fit".into(), json!(v));
+ }
+ if let Some(v) = p.center {
+ opts.insert("center".into(), json!(v));
+ }
+ let opts = Value::Object(opts);
+ // Bridge mode runs the app on this machine, which reads the path itself like any command.
+ 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.place(index, &path, &opts)).await {
+ return to_result(r);
+ }
+ self.run_command("file.placeEmbedded".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/src/server/conventions.rs b/crates/automation/src/server/conventions.rs
index 93a78ac7b..6e2740041 100644
--- a/crates/automation/src/server/conventions.rs
+++ b/crates/automation/src/server/conventions.rs
@@ -16,7 +16,7 @@ fn annotated(mut tool: Tool) -> Tool {
tool.name.as_ref(),
"command_list" | "doc_inspect" | "session_list" | "render_preview" | "doc_render_preview" | "ui_inspect" | "ui_screenshot"
);
- let additive = matches!(tool.name.as_ref(), "doc_new" | "doc_open");
+ let additive = matches!(tool.name.as_ref(), "doc_new" | "doc_open" | "doc_place");
tool.title = Some(title.clone());
tool.annotations = Some(ToolAnnotations::from_raw(Some(title), Some(read), Some(!read && !additive), Some(read), Some(false)));
Arc::make_mut(&mut tool.input_schema).insert("additionalProperties".into(), json!(false));
diff --git a/crates/automation/tests/mcp.rs b/crates/automation/tests/mcp.rs
index 0c40ec93f..abcc3b0c9 100644
--- a/crates/automation/tests/mcp.rs
+++ b/crates/automation/tests/mcp.rs
@@ -79,6 +79,7 @@ async fn lists_expected_tools() {
"session_list",
"doc_open",
"doc_new",
+ "doc_place",
"doc_save",
"doc_export",
"doc_inspect",
@@ -611,6 +612,45 @@ async fn filesystem_policy_rejects_absolute_and_escaping_paths_before_effects()
cleanup(&base);
}
+/// #2810: a file from the read root places as a Smart Object layer; `file.placeEmbedded` itself
+/// stays refused, so `doc_place` is the only way in and the root is still the scope.
+#[tokio::test(flavor = "multi_thread")]
+async fn doc_place_is_capability_scoped() {
+ let base = tmp("place");
+ let root = base.join("workspace");
+ let outside = base.join("outside");
+ std::fs::create_dir_all(&root).unwrap();
+ std::fs::create_dir_all(&outside).unwrap();
+ let img = photocraft_codecs::Image::from_u8(8, 6, photocraft_codecs::ChannelLayout::Rgb, vec![42; 144]).unwrap();
+ let bytes = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap();
+ std::fs::write(root.join("inside.png"), &bytes).unwrap();
+ std::fs::write(outside.join("outside.png"), bytes).unwrap();
+ let client = connect(headless_in(&root)).await;
+
+ json_of(&call(&client, "doc_new", json!({"width": 40, "height": 30})).await);
+ let placed = call(&client, "doc_place", json!({"path": "inside.png", "center": [10, 10]})).await;
+ assert_ne!(placed.is_error, Some(true), "{}", text(&placed));
+ let layers = json_of(&call(&client, "doc_inspect", json!({})).await)["layers"].as_array().unwrap().len();
+ assert_eq!(layers, 2, "the placed layer is in the document");
+ // An absolute path beneath the root is the same file (#2176), so it places too; outside it,
+ // nothing.
+ let inside = call(&client, "doc_place", json!({"path": root.join("inside.png").to_string_lossy()})).await;
+ assert_ne!(inside.is_error, Some(true), "{}", text(&inside));
+ let placed = json_of(&call(&client, "doc_inspect", json!({})).await)["layers"].as_array().unwrap().len();
+ assert_eq!(placed, 3, "the absolute path beneath the root places as well");
+ let refused = call(&client, "doc_place", json!({"path": outside.join("outside.png").to_string_lossy()})).await;
+ assert_eq!(refused.is_error, Some(true));
+ assert!(text(&refused).contains("must be inside the automation root"), "{}", text(&refused));
+ let after = json_of(&call(&client, "doc_inspect", json!({})).await)["layers"].as_array().unwrap().len();
+ assert_eq!(after, placed, "nothing outside the root was placed");
+ // The ambient command keeps its refusal: the capability-scoped method is the only way in.
+ let ambient = call(&client, "command_run", json!({"id": "file.placeEmbedded", "params": {"path": "inside.png"}})).await;
+ assert_eq!(ambient.is_error, Some(true));
+ assert!(text(&ambient).contains("ambient filesystem paths"), "{}", text(&ambient));
+ 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/docs/architecture.md b/docs/architecture.md
index 7db7ba0e2..e7e99ea33 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -466,7 +466,8 @@ 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_save`, `doc_export`, `doc_inspect` (layer tree as JSON), `doc_render_preview` (PNG), `doc_select`, `doc_close`.
+ - `session_list`, `doc_open`, `doc_new`, `doc_place` (place from the read root as a Smart Object),
+ `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.
- Stdio for agent CLIs, and optionally loopback TCP with a token so it can attach to a running GUI.
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index dc614bad6..df4df7089 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -262,6 +262,7 @@ How each MCP tool maps onto control methods in bridge mode:
| `doc_new {…}` | `engine.execute {command: "file.new", params}` |
| `doc_inspect` | `engine.execute {command: "document.inspect"}` |
| `doc_open {path}` | `app.open {path}` |
+| `doc_place {path, …}` | `engine.execute {command: "file.placeEmbedded", 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` |
@@ -315,6 +316,7 @@ no MCP framing, no app start-up per command. Configure its file access with the
| `engine.commands` | `{filter?}`: registry with params docs and enablement |
| `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.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 7d9dac3c7..6eac94c6c 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_save`, `doc_export`, `doc_inspect`, `doc_render_preview` (returns a PNG image), `doc_select`, `doc_close`
+- `doc_open`, `doc_new`, `doc_place`, `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`