mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
MCP `doc_save {}` and `serve` `doc.save {}` fell back to the document's
own path for any format, so an agent that saved its work replaced the
input PNG or JPEG with a flattened, re-encoded copy, and a `format`
override wrote PNG bytes under a `.psd` name. The desktop's File › Save
already writes back only to layered files.
The rule now lives in one place, `engine::file_cmds::saves_in_place`
(plus `extension`), shared by File › Save, the control channel's
`app.save` and the headless save. Without `path`, a save writes back
only to a PSD, PSB or .pcraft file in its own format; anything else is
an error naming `path` and the file is left unchanged. An explicit
`path`, even the opened file's own, still writes as before. The MCP
`doc_save` description and `path` doc, and docs/control-protocol.md,
state the rule.
Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
55054b5fcc
commit
3443833532
9 files changed
+109
-15
No files matched your search
@@ -4,7 +4,7 @@
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use photocraft_engine::{Session, command_specs};
|
||||
use photocraft_engine::{Session, command_specs, file_cmds};
|
||||
use photocraft_format::PcraftWriter;
|
||||
use photocraft_io::ExportOptions;
|
||||
use serde_json::{Value, json};
|
||||
@@ -91,7 +91,18 @@ impl Headless {
|
||||
};
|
||||
let target: PathBuf = match (path, stored_path.as_deref()) {
|
||||
(Some(p), _) => p.to_path_buf(),
|
||||
(None, Some(p)) => PathBuf::from(p),
|
||||
// Like the desktop's File › Save: without a new path, only a layered file is written
|
||||
// back, in its own format; a flattened or converted copy never replaces it (#416).
|
||||
(None, Some(p)) => {
|
||||
let own = file_cmds::extension(p);
|
||||
let written = format.map(|f| f.trim_start_matches('.').to_ascii_lowercase()).or_else(|| own.clone());
|
||||
if !file_cmds::saves_in_place(p) || written != own {
|
||||
return Err(AutomationError::BadRequest(format!(
|
||||
"pass `path`: without one, only a PSD, PSB or .pcraft file is written back, in its own format, so `{p}` was left unchanged"
|
||||
)));
|
||||
}
|
||||
PathBuf::from(p)
|
||||
}
|
||||
(None, None) => {
|
||||
return Err(AutomationError::BadRequest("document has no path; pass `path`".into()));
|
||||
}
|
||||
|
||||
@@ -72,7 +72,9 @@ pub struct NewParams {
|
||||
#[derive(Debug, Default, Deserialize, JsonSchema)]
|
||||
pub struct SaveParams {
|
||||
/// Forward-slash relative target beneath the configured automation write root.
|
||||
/// The extension selects the format. Omit to save to the document's own relative path.
|
||||
/// The extension selects the format. Omit to write back to the document's own file, which
|
||||
/// works only for a PSD, PSB or .pcraft file kept in its own format; any other save needs
|
||||
/// `path`, so a flattened or converted copy never replaces the opened file.
|
||||
#[serde(default)]
|
||||
pub path: Option<String>,
|
||||
/// Format override as an extension (pcraft, psd, png, jpg, tif, webp, exr, …).
|
||||
@@ -396,7 +398,7 @@ impl PhotocraftMcp {
|
||||
}
|
||||
|
||||
#[tool(description = "Save the document. `.pcraft` is the lossless native format (incremental); other extensions \
|
||||
(psd, png, jpg, tif, webp, exr, …) export. Returns warnings about anything the format cannot hold.")]
|
||||
(psd, png, jpg, tif, webp, exr, …) export. Without `path` only a PSD, PSB or .pcraft document is written back to its own file. Returns warnings about anything the format cannot hold.")]
|
||||
async fn doc_save(&self, Parameters(p): Parameters<SaveParams>) -> Result<CallToolResult, McpError> {
|
||||
self.save_impl(p).await
|
||||
}
|
||||
|
||||
@@ -254,6 +254,57 @@ async fn open_png_and_inspect() {
|
||||
cleanup(&dir);
|
||||
}
|
||||
|
||||
fn write_image(dir: &std::path::Path, name: &str, format: photocraft_codecs::Format) -> Vec<u8> {
|
||||
let img = photocraft_codecs::Image::from_u8(16, 8, photocraft_codecs::ChannelLayout::Rgb, (0..384).map(|i| (i * 7 % 251) as u8).collect()).unwrap();
|
||||
let bytes = photocraft_codecs::encode(&img, format, &Default::default()).unwrap();
|
||||
std::fs::write(dir.join(name), &bytes).unwrap();
|
||||
bytes
|
||||
}
|
||||
|
||||
/// A save without `path` writes back only to a layered file in its own format (#416).
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn save_without_path_never_flattens_over_the_opened_file() {
|
||||
let dir = tmp("save-in-place");
|
||||
let png = write_image(&dir, "seed.png", photocraft_codecs::Format::Png);
|
||||
let jpg = write_image(&dir, "seed.jpg", photocraft_codecs::Format::Jpeg);
|
||||
let client = connect(headless_in(&dir)).await;
|
||||
let refused = |r: &CallToolResult| r.is_error == Some(true) && text(r).contains("pass `path`");
|
||||
|
||||
// A flat file, edited or not, is left unchanged.
|
||||
json_of(&call(&client, "doc_open", json!({"path": "seed.png"})).await);
|
||||
json_of(&call(&client, "command_run", json!({"id": "layer.newAdjustmentLayer.curves", "params": {"points": [[0, 0], [128, 170], [255, 255]]}})).await);
|
||||
let r = call(&client, "doc_save", json!({})).await;
|
||||
assert!(refused(&r), "{}", text(&r));
|
||||
assert_eq!(std::fs::read(dir.join("seed.png")).unwrap(), png);
|
||||
json_of(&call(&client, "doc_open", json!({"path": "seed.jpg"})).await);
|
||||
let r = call(&client, "doc_save", json!({})).await;
|
||||
assert!(refused(&r), "{}", text(&r));
|
||||
assert_eq!(std::fs::read(dir.join("seed.jpg")).unwrap(), jpg);
|
||||
|
||||
// An explicit path, even the opened file's own, still writes and reports what was lost.
|
||||
let r = json_of(&call(&client, "doc_save", json!({"path": "seed.jpg"})).await);
|
||||
assert!(r["warnings"].to_string().contains("lossy"), "{r}");
|
||||
|
||||
// A layered file saves in place in its own format, but not converted over itself.
|
||||
json_of(&call(&client, "doc_select", json!({"index": 0})).await);
|
||||
json_of(&call(&client, "doc_save", json!({"path": "layered.psd"})).await);
|
||||
json_of(&call(&client, "doc_open", json!({"path": "layered.psd"})).await);
|
||||
let psd = std::fs::read(dir.join("layered.psd")).unwrap();
|
||||
let r = call(&client, "doc_save", json!({"format": "png"})).await;
|
||||
assert!(refused(&r), "{}", text(&r));
|
||||
assert_eq!(std::fs::read(dir.join("layered.psd")).unwrap(), psd);
|
||||
assert_eq!(json_of(&call(&client, "doc_save", json!({})).await)["path"], "layered.psd");
|
||||
assert!(photocraft_io::is_psd(&std::fs::read(dir.join("layered.psd")).unwrap()));
|
||||
|
||||
// Once saved as .pcraft, a flat-born document saves in place there.
|
||||
json_of(&call(&client, "doc_select", json!({"index": 0})).await);
|
||||
json_of(&call(&client, "doc_save", json!({"path": "work.pcraft"})).await);
|
||||
assert_eq!(json_of(&call(&client, "doc_save", json!({})).await)["path"], "work.pcraft");
|
||||
assert_eq!(std::fs::read(dir.join("seed.png")).unwrap(), png);
|
||||
client.cancel().await.unwrap();
|
||||
cleanup(&dir);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn filesystem_policy_rejects_absolute_and_escaping_paths_before_effects() {
|
||||
let base = tmp("filesystem-policy");
|
||||
|
||||
@@ -122,6 +122,17 @@ pub(crate) fn file_name(path: &str) -> String {
|
||||
path.rsplit(['/', '\\']).next().unwrap_or(path).to_string()
|
||||
}
|
||||
|
||||
/// The lower-case extension of the file name in `path` (none for `.hidden` or `name`).
|
||||
pub fn extension(path: &str) -> Option<String> {
|
||||
file_name(path).rsplit_once('.').filter(|(base, ext)| !base.is_empty() && !ext.is_empty()).map(|(_, ext)| ext.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
/// Whether a save without a new path may write back to `path`: only layered files (PSD, PSB,
|
||||
/// .pcraft). A flat file goes through Save As instead, so it is never flattened over the original.
|
||||
pub fn saves_in_place(path: &str) -> bool {
|
||||
extension(path).is_some_and(|ext| matches!(ext.as_str(), "psd" | "psb" | "pcraft"))
|
||||
}
|
||||
|
||||
pub(crate) fn stem(path: &str) -> String {
|
||||
let n = file_name(path);
|
||||
match n.rfind('.') {
|
||||
|
||||
@@ -377,3 +377,16 @@ fn guide_layouts() {
|
||||
assert_eq!(g.vertical, vec![10.0, 30.0, 50.0]);
|
||||
assert_eq!(g.horizontal, vec![10.0, 20.0, 30.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_layered_files_save_in_place() {
|
||||
for path in ["a.psd", "dir/a.PSB", r"C:\w\a.pcraft", "my.dir/a.psd"] {
|
||||
assert!(saves_in_place(path), "{path}");
|
||||
}
|
||||
// Flat formats, no extension, a dotted folder with an extensionless file, a dot file.
|
||||
for path in ["a.png", "a.jpg", "a", "my.psd/a", ".psd", "a.", ""] {
|
||||
assert!(!saves_in_place(path), "{path}");
|
||||
}
|
||||
assert_eq!(extension("dir/Photo.JPEG").as_deref(), Some("jpeg"));
|
||||
assert_eq!(extension("my.dir/name"), None);
|
||||
}
|
||||
@@ -733,5 +733,14 @@ mod tests {
|
||||
let r = call(&mut app, &ctx, "app.save", json!({"path": "out.png"}));
|
||||
assert_eq!(r["result"], json!({"path": "out.png", "warnings": ["Layers were flattened"]}), "{r}");
|
||||
assert_eq!(*written.borrow(), vec!["out.png".to_string()]);
|
||||
// Without `path`, only a layered file is written back, like File › Save (#416).
|
||||
call(&mut app, &ctx, "app.open", json!({"path": "in/flat.jpg"}));
|
||||
let r = call(&mut app, &ctx, "app.save", json!({}));
|
||||
assert!(r["error"].as_str().unwrap().contains("pass `path`"), "{r}");
|
||||
assert_eq!(written.borrow().len(), 1, "nothing written over the JPEG");
|
||||
call(&mut app, &ctx, "app.open", json!({"path": "in/layered.psd"}));
|
||||
let r = call(&mut app, &ctx, "app.save", json!({}));
|
||||
assert_eq!(r["result"]["path"], "in/layered.psd", "{r}");
|
||||
assert_eq!(written.borrow().last().map(String::as_str), Some("in/layered.psd"));
|
||||
}
|
||||
}
|
||||
@@ -711,7 +711,10 @@ impl PhotocraftApp {
|
||||
/// written and the export warnings (also shown to the user).
|
||||
pub fn save_automation(&mut self, path: Option<String>) -> Result<(String, Vec<String>), String> {
|
||||
let state = self.session.active().ok_or("no document")?;
|
||||
let target = path.or_else(|| state.path.clone()).ok_or("document has no relative path; pass `path`")?;
|
||||
// As File › Save: without `path` only a layered file is written back (#416).
|
||||
let target = path
|
||||
.or_else(|| state.path.clone().filter(|p| photocraft_engine::file_cmds::saves_in_place(p)))
|
||||
.ok_or("pass `path`: a save without one writes back only to the document's own PSD, PSB or .pcraft file")?;
|
||||
let export = self.services.export.as_ref().ok_or("no exporter configured")?;
|
||||
let (bytes, warnings) = export(&state.doc, &target, &ExportSettings::default())?;
|
||||
let write = self.services.automation_write.as_mut().ok_or("automation write authority is not configured")?;
|
||||
|
||||
@@ -225,11 +225,12 @@ pub(crate) fn invoke_unguarded(app: &mut PhotocraftApp, ctx: &egui::Context, id:
|
||||
}
|
||||
}
|
||||
"file.save" => {
|
||||
// Writes back only to a layered file; a flat one goes through Save As.
|
||||
let path = params
|
||||
.get("path")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::to_string)
|
||||
.or_else(|| app.session.active().and_then(|d| d.path.clone()).filter(|p| saves_in_place(p)));
|
||||
.or_else(|| app.session.active().and_then(|d| d.path.clone()).filter(|p| photocraft_engine::file_cmds::saves_in_place(p)));
|
||||
app.save_as(path).map(|(p, w)| json!({"path": p, "warnings": w}))
|
||||
}
|
||||
"file.exit" => {
|
||||
@@ -430,13 +431,6 @@ fn open_path(app: &mut PhotocraftApp, path: &str) -> Result<Value, String> {
|
||||
app.open_path(path).map(|w| json!({"warnings": w}))
|
||||
}
|
||||
|
||||
/// File › Save writes back to the document's own file for layered formats (PSD, PSB, .pcraft);
|
||||
/// flat files go through Save As, like Photoshop.
|
||||
fn saves_in_place(path: &str) -> bool {
|
||||
let ext = path.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default();
|
||||
matches!(ext.as_str(), "psd" | "psb" | "pcraft")
|
||||
}
|
||||
|
||||
pub fn is_enabled(app: &PhotocraftApp, id: &str) -> bool {
|
||||
// Photoshop greys these for the Background layer, other layer kinds or single-layer documents.
|
||||
if crate::enable_rules::disabled(app, id) {
|
||||
|
||||
@@ -51,7 +51,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
|
||||
base64 PNG data; a path is relative to the automation write root. Raises the window first
|
||||
(default) because occluded macOS windows stop rendering
|
||||
- `ui.focus`: bring the main window to the front
|
||||
- `app.open {path}` / `app.save {path}`: relative file I/O through the configured automation roots (`app.open` reads under the read root, `app.save` writes under the write root; absolute paths, `..` and paths escaping the root are refused, and both fail closed when no root was granted). Both reply with `warnings` (import/export notes such as "adjustment layer flattened"; `[]` when none), also shown to the user in the status bar and as a notice (`notices` in `ui.inspect`); `app.open` also returns the `path` and document `name`, `app.save` the `path` written. Automation opens and saves never fire script events. `file.open`, `file.save`, `file.saveAs` and `file.saveACopy` reply with `warnings` the same way
|
||||
- `app.open {path}` / `app.save {path}`: relative file I/O through the configured automation roots (`app.open` reads under the read root, `app.save` writes under the write root; absolute paths, `..` and paths escaping the root are refused, and both fail closed when no root was granted). Both reply with `warnings` (import/export notes such as "adjustment layer flattened"; `[]` when none), also shown to the user in the status bar and as a notice (`notices` in `ui.inspect`); `app.open` also returns the `path` and document `name`, `app.save` the `path` written. `app.save` without `path` writes back only to the document's own PSD, PSB or `.pcraft` file, like File › Save. Automation opens and saves never fire script events. `file.open`, `file.save`, `file.saveAs` and `file.saveACopy` reply with `warnings` the same way
|
||||
- `app.quit`
|
||||
|
||||
## Engine commands
|
||||
@@ -199,7 +199,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.save` | `{path?, format?, quality?, index?}` (`.pcraft` native, else export by extension) |
|
||||
| `doc.save` | `{path?, format?, quality?, index?}` (`.pcraft` native, else export by extension). 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 |
|
||||
| `doc.inspect` | `{index?}`: same JSON as `document.inspect` |
|
||||
| `doc.render` | `{index?, maxSide? (1024; 0 = full), path?}`: PNG to `path`, else `{mime, base64}` |
|
||||
| `doc.select` / `doc.close` | `{index}` / `{index?}` |
|
||||
|
||||
Reference in new issue
Block a user