From a0418a2e29e12c6f50d64e07083a5a96d5205fbf Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 3 Nov 2026 14:50:52 +0100 Subject: [PATCH] Address CodeRabbit review: Batch failures, late Esc, CLI format, bridge result - A failed input stays in `errors` when `jobs.cancel` or Esc lands while it runs, instead of showing up as skipped without its reason. - Esc after the last input is refused: the worker closes the interrupt window once no checkpoint is left, so `request_batch_interrupt` no longer answers true for a question that never comes. - `photocraft-cli batch` without `--format` saves a file PhotoCraft only opens as PSD, the format `--naming`'s {ext} already plans, instead of asking the encoder for the input's import-only extension. - `--recursive` help says the output is flat. - The app bridge keeps a cancelled Batch's partial result in the error it returns to MCP. Co-Authored-By: Claude Opus 5.5 --- apps/photocraft-cli/src/args.rs | 3 +- apps/photocraft-cli/src/batch.rs | 6 +- apps/photocraft-cli/tests/it/cli.rs | 31 +++++++++ crates/automation/src/bridge.rs | 31 +++++++-- crates/engine/src/cmd/file_cmds.rs | 4 +- crates/engine/src/cmd/file_cmds/batch_run.rs | 32 +++++++-- crates/engine/src/cmd/file_cmds/tests.rs | 72 ++++++++++++++++++++ crates/engine/src/jobs.rs | 9 +++ docs/control-protocol.md | 2 +- 9 files changed, 174 insertions(+), 16 deletions(-) diff --git a/apps/photocraft-cli/src/args.rs b/apps/photocraft-cli/src/args.rs index b582b32c590..c94a4bb8cd2 100644 --- a/apps/photocraft-cli/src/args.rs +++ b/apps/photocraft-cli/src/args.rs @@ -182,7 +182,8 @@ pub(crate) struct BatchArgs { /// originals; --in-place allows it #[arg(long)] pub(crate) in_place: bool, - /// Include images in subfolders and mirror their folders under --out + /// Include images in subfolders; every result goes straight into --out, so a later file of + /// the same name replaces an earlier one #[arg(long)] pub(crate) recursive: bool, /// Name each result with Batch tokens such as {name}, {serial}, {date}, and {ext} diff --git a/apps/photocraft-cli/src/batch.rs b/apps/photocraft-cli/src/batch.rs index c096d8100db..347f829443c 100644 --- a/apps/photocraft-cli/src/batch.rs +++ b/apps/photocraft-cli/src/batch.rs @@ -93,7 +93,7 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) -> .iter() .map(|input| { let path = Path::new(&input.path); - let ext = format.map(str::to_owned).or_else(|| path.extension().map(|e| e.to_string_lossy().into_owned())).unwrap_or_else(|| "png".into()); + let ext = format.map_or_else(|| photocraft_engine::file_cmds::batch_same_format(&input.path), str::to_owned); let stem = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); out_dir.join(format!("{stem}.{ext}")) }) @@ -112,7 +112,9 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) -> for (input, target) in inputs.iter().zip(targets) { let input = Path::new(&input.path); // The selected format encodes the bytes, whatever extension `--naming` gives the file. - let ext = format.map(str::to_owned).or_else(|| input.extension().map(|e| e.to_string_lossy().into_owned())).unwrap_or_else(|| "png".into()); + // Without --format, a file PhotoCraft only opens (.kra, raw, …) is saved as PSD, the + // same format `--naming`'s {ext} plans. + let ext = format.map_or_else(|| photocraft_engine::file_cmds::batch_same_format(&input.to_string_lossy()), str::to_owned); let r = (|| -> Result> { if let Some(parent) = target.parent() { std::fs::create_dir_all(parent)?; diff --git a/apps/photocraft-cli/tests/it/cli.rs b/apps/photocraft-cli/tests/it/cli.rs index 4dac055d2f5..cafe35b8049 100644 --- a/apps/photocraft-cli/tests/it/cli.rs +++ b/apps/photocraft-cli/tests/it/cli.rs @@ -556,6 +556,37 @@ fn batch_naming_keeps_the_tree_order_and_the_selected_encoder() { std::fs::remove_dir_all(root).unwrap(); } +/// Without --format, a file PhotoCraft only opens is saved as PSD, with or without --naming: +/// the encoder gets the format the planned name uses, not the input's import-only extension. +#[test] +fn batch_saves_import_only_inputs_as_psd() { + let root = tmp("batch-import-only"); + let input = root.join("in"); + std::fs::create_dir_all(&input).unwrap(); + std::fs::write( + input.join("logo.xpm"), + "/* XPM */ +static char *logo[] = { +\"2 2 1 1\", +\"a c #FF0000\", +\"aa\", +\"aa\" +}; +", + ) + .unwrap(); + let actions = root.join("actions.json"); + std::fs::write(&actions, "[]").unwrap(); + for (name, extra) in [("plain", &[][..]), ("named", &["--naming", "{name}.{ext}"][..])] { + let out = root.join(name); + let result = bin().args(["batch", "--actions"]).arg(&actions).arg("--in").arg(&input).arg("--out").arg(&out).args(extra).output().unwrap(); + assert!(result.status.success(), "{name}: {}{}", String::from_utf8_lossy(&result.stdout), String::from_utf8_lossy(&result.stderr)); + assert!(std::fs::read(out.join("logo.psd")).unwrap().starts_with(b"8BPS"), "{name}: PSD bytes"); + assert!(!out.join("logo.xpm").exists(), "{name}"); + } + std::fs::remove_dir_all(root).unwrap(); +} + #[test] fn batch_skips_recorded_view_and_save_steps() { let d = tmp("batch-shell-steps"); diff --git a/crates/automation/src/bridge.rs b/crates/automation/src/bridge.rs index 5c238a3b510..adb6d8eea62 100644 --- a/crates/automation/src/bridge.rs +++ b/crates/automation/src/bridge.rs @@ -227,18 +227,39 @@ async fn exchange(conn: &mut Conn, id: u64, method: &str, params: &Value) -> Res if v.get("id").and_then(Value::as_u64) != Some(id) { continue; // stale reply from an earlier, timed-out request } - return Ok(if v.get("ok").and_then(Value::as_bool) == Some(true) { - Ok(v.get("result").cloned().unwrap_or(Value::Null)) - } else { - Err(AutomationError::App(v.get("error").and_then(Value::as_str).unwrap_or("unknown error").to_owned())) - }); + return Ok(reply_result(&v)); } } +/// An app reply as the caller's result. A failed reply can still carry a `result`: a cancelled +/// Batch lists the outputs it already wrote, so the error keeps it rather than dropping it. +fn reply_result(v: &Value) -> Result { + if v.get("ok").and_then(Value::as_bool) == Some(true) { + return Ok(v.get("result").cloned().unwrap_or(Value::Null)); + } + let error = v.get("error").and_then(Value::as_str).unwrap_or("unknown error"); + Err(AutomationError::App(match v.get("result") { + Some(result) if !result.is_null() => format!("{error}; partial result: {result}"), + _ => error.to_owned(), + })) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn a_failed_reply_keeps_its_partial_result() { + assert_eq!(reply_result(&json!({"ok": true, "result": {"files": ["a.png"]}})).unwrap(), json!({"files": ["a.png"]})); + let Err(AutomationError::App(message)) = reply_result(&json!({"ok": false, "error": "cancelled", "result": {"files": ["a.png"], "cancelled": true}})) + else { + panic!("a failed reply is an app error") + }; + assert!(message.starts_with("cancelled; partial result: ") && message.contains("a.png"), "{message}"); + let Err(AutomationError::App(message)) = reply_result(&json!({"ok": false, "error": "cancelled"})) else { panic!("a failed reply is an app error") }; + assert_eq!(message, "cancelled"); + } + #[test] fn the_call_timeout_stays_below_the_app_reply_deadline() { // At or above the app's 60s deadline, callers would see their own cutoff first. diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index 96fc4719cc1..611fdb0d609 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -31,10 +31,12 @@ mod save; pub use batch_naming::plan as plan_batch_names; #[cfg(test)] pub(crate) use batch_run::MAX_SUBFOLDER_DEPTH; +use batch_run::batch; +pub use batch_run::same_format as batch_same_format; +use batch_run::same_format; #[cfg(not(target_arch = "wasm32"))] pub use batch_run::validate_flat_outputs; pub use batch_run::{BatchInput, OutputClaims, encode_batch_error_log, list_images_tree}; -use batch_run::{batch, same_format}; pub(crate) use batch_run::{batch_inputs, batch_keeps_step, batch_save_point, process_files}; pub use export::{LayerExportReport, SkippedExportLayer, bake_cube, export_layers_report_with, export_layers_with}; use export::{color_lookup_tables, layers_to_files, push_unique}; diff --git a/crates/engine/src/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs index 7d62d16f457..5a93e670a87 100644 --- a/crates/engine/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine/src/cmd/file_cmds/batch_run.rs @@ -143,7 +143,9 @@ pub(crate) fn process_tree( /// codec formats without a writer in this build. Those are saved as PSD, the format Photoshop's /// Save As offers for a raw. An input whose file name has no extension (a dot in a folder name /// doesn't count) is saved as PNG. -pub(super) fn same_format(path: &str) -> String { +/// The format Batch's "Save in the same format" writes for `path`: its own, or PSD for a file +/// PhotoCraft only opens. +pub fn same_format(path: &str) -> String { const IMPORT_ONLY: &[&str] = &["pdn", "kra", "krz", "af", "afdesign", "afphoto", "afpub", "heic", "heif", "hif", "svg", "svgz", "cin", "pcx", "xpm", "xcf", "xcfgz", "gz", "psdt"]; let ext = extension(path).unwrap_or_else(|| "png".into()); @@ -364,25 +366,41 @@ pub(super) fn process_batch_outputs( } ctx.progress(index as f32 / total.max(1) as f32, &format!("{} of {total}: {}", index + 1, file_name(path))); let result = process_one(raw_ppi, path, out, save, ProcessOptions { format: Some(format), written: None, ctx: Some(ctx) }, f); + // An input that failed on its own (not because it was stopped) stays a failure with its + // reason, even when a cancel or Esc lands while it runs. + let failure = + result.as_ref().err().filter(|error| !matches!(error, EngineError::Cancelled)).map(|error| json!({"file": path, "error": error.to_string()})); if ctx.cancelled() { ctx.publish_batch_preview(path, None); // A cancel that lands while the result is written still leaves that file written. if result.is_ok() { files.push(out.clone()); done = index + 1; + } else if let Some(failure) = failure { + errors.push(failure); + done = index + 1; } else { done = index; } break; } if ctx.batch_take_interrupt() { - if ctx.batch_wait_for_decision() { - ctx.publish_batch_preview(path, None); - interrupted.push(path.clone()); - done = index + 1; + let continue_next = ctx.batch_wait_for_decision(); + ctx.publish_batch_preview(path, None); + match failure { + Some(failure) => { + errors.push(failure); + done = index + 1; + } + None if continue_next => { + interrupted.push(path.clone()); + done = index + 1; + } + None => {} + } + if continue_next { continue; } - ctx.publish_batch_preview(path, None); ctx.cancel(); break; } @@ -402,6 +420,8 @@ pub(super) fn process_batch_outputs( } } } + // No checkpoint follows the last input: a later Esc has nothing to interrupt. + ctx.batch_close_interrupts(); let log_failure = error_log_failure(policy.error_log.as_deref(), &errors); let cancelled = ctx.cancelled(); if !cancelled { diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 53efd65782f..7c49ed2151e 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -89,6 +89,78 @@ fn batch_cancelled_during_an_action_does_not_save_that_input() { assert!(!std::path::Path::new(&out).exists()); } +/// A cancel that lands while an input fails on its own keeps that failure and its reason; only +/// the inputs after it are skipped. +#[test] +fn batch_cancel_during_a_failing_input_keeps_its_error() { + let dir = tmp("batch-cancel-failing"); + let first = png(&dir, "first.png", 8, 6, "#ff0000"); + let second = png(&dir, "second.png", 8, 6, "#00ff00"); + let ctx = crate::jobs::JobCtx::new(); + let policy = super::batch_run::BatchPolicy { stop_on_error: false, error_log: None }; + let outputs = vec![(first.clone(), join(&dir, "out/first.png")), (second.clone(), join(&dir, "out/second.png"))]; + let result = super::batch_run::process_batch_outputs(72.0, outputs, "png", SaveOpts::default(), &policy, &ctx, &|_, _| { + ctx.cancel(); + Err(EngineError::Other("boom".into())) + }) + .unwrap(); + assert_eq!(result["errors"], json!([{"file": first, "error": "boom"}]), "{result}"); + assert_eq!(result["skipped"], json!([second]), "{result}"); + assert_eq!(result["cancelled"], json!(true), "{result}"); +} + +/// Esc during an input that fails on its own: Continue records the failure (not an interrupted +/// input) and goes on with the next one. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn batch_interruption_during_a_failing_input_keeps_its_error() { + use std::time::Duration; + + let dir = tmp("batch-interrupt-failing"); + let first = png(&dir, "first.png", 8, 6, "#ff0000"); + let second = png(&dir, "second.png", 8, 6, "#00ff00"); + let second_out = join(&dir, "out/second.png"); + let ctx = crate::jobs::JobCtx::new(); + let worker_ctx = ctx.clone(); + let outputs = vec![(first.clone(), join(&dir, "out/first.png")), (second, second_out.clone())]; + let worker = std::thread::spawn(move || { + let policy = super::batch_run::BatchPolicy { stop_on_error: false, error_log: None }; + super::batch_run::process_batch_outputs(72.0, outputs, "png", SaveOpts::default(), &policy, &worker_ctx, &|_, path| { + if path.ends_with("first.png") { + assert!(worker_ctx.request_batch_interrupt()); + return Err(EngineError::Other("boom".into())); + } + Ok(false) + }) + }); + let deadline = std::time::Instant::now() + Duration::from_secs(10); + while !ctx.batch_waiting_for_decision() && std::time::Instant::now() < deadline { + std::thread::yield_now(); + } + assert!(ctx.decide_batch_interrupt(true)); + let result = worker.join().unwrap().unwrap(); + assert_eq!(result["errors"], json!([{"file": first, "error": "boom"}]), "{result}"); + assert_eq!(result["files"], json!([second_out]), "{result}"); + assert!(result.get("skipped").is_none(), "{result}"); +} + +/// Once the last input is handled, Esc has nothing to interrupt and is refused, so the desktop +/// never waits for a question that will not come. +#[test] +fn batch_refuses_esc_after_its_last_input() { + let dir = tmp("batch-late-esc"); + let input = png(&dir, "source.png", 8, 6, "#ff0000"); + let ctx = crate::jobs::JobCtx::new(); + let policy = super::batch_run::BatchPolicy { stop_on_error: false, error_log: None }; + let result = + super::batch_run::process_batch_outputs(72.0, vec![(input, join(&dir, "out/source.png"))], "png", SaveOpts::default(), &policy, &ctx, &|_, _| { + Ok(false) + }) + .unwrap(); + assert_eq!(result["errors"], json!([]), "{result}"); + assert!(!ctx.request_batch_interrupt()); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn batch_interruption_continues_with_the_original_next_output() { diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index 6a792b7b0e4..34ac2c12a96 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -116,6 +116,8 @@ enum BatchInterrupt { Continue, Stop, Saving, + /// Every input has been handled; Esc is no longer accepted. + Closed, } const CANCEL_REQUESTED: u8 = 1; @@ -247,6 +249,13 @@ impl JobCtx { Ok(()) } + /// The worker has passed its last checkpoint. A pending request is dropped (nothing is left to + /// interrupt) and later requests return false. + pub(crate) fn batch_close_interrupts(&self) { + *self.shared.batch.lock().unwrap_or_else(PoisonError::into_inner) = BatchInterrupt::Closed; + self.shared.batch_decision.notify_all(); + } + /// A completed write allows Esc on the next input. pub(crate) fn batch_after_write(&self) { let mut phase = self.shared.batch.lock().unwrap_or_else(PoisonError::into_inner); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index e9f073db1e2..1c945f696c4 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -250,7 +250,7 @@ The shape is pinned by a test in `crates/automation/src/rpc.rs` (#3684). ### Background jobs (#210) -Long commands (every `filter.*`, `edit.contentAwareFill`, `edit.contentAwareScale`, `file.automate.photomerge`, `brush.presets.importAbr`), file opens and interactive saves (File › Save, Save As and the TIFF Options continuation, #2017) run as background jobs in the desktop app: the window keeps drawing, the status bar shows progress with a Cancel button, and jobs that lock the active document show a modal progress dialog (Esc cancels). `engine.execute`, `ui.menu.invoke`, `ui.dialog.confirm` and `app.save` still wait for the result by default; pass `"wait": false` to get `{job, pending: true}` at once, then poll `jobs.list` (`state`: running, done, failed, cancelled; `progress` 0–1; the result or error) and stop it with `jobs.cancel {job}`. A cancelled or failed job leaves the document unchanged; a folder Batch can already have written earlier output files. A cancelled Batch has `state: "cancelled"` with its partial `result` in `jobs.list`; a waiting control request receives `{"ok":false,"error":"cancelled","result":…}`. While a job runs, commands that would edit its document fail with "… is still running on this document". `ui.inspect` reports `jobs` (running jobs, opening files, saving files). Set `PHOTOCRAFT_INLINE_JOBS=1` to run everything inline. +Long commands (every `filter.*`, `edit.contentAwareFill`, `edit.contentAwareScale`, `file.automate.photomerge`, `brush.presets.importAbr`), file opens and interactive saves (File › Save, Save As and the TIFF Options continuation, #2017) run as background jobs in the desktop app: the window keeps drawing, the status bar shows progress with a Cancel button, and jobs that lock the active document show a modal progress dialog (Esc cancels). `engine.execute`, `ui.menu.invoke`, `ui.dialog.confirm` and `app.save` still wait for the result by default; pass `"wait": false` to get `{job, pending: true}` at once, then poll `jobs.list` (`state`: running, done, failed, cancelled; `progress` 0–1; the result or error) and stop it with `jobs.cancel {job}`. A cancelled or failed job leaves the document unchanged; a folder Batch can already have written earlier output files. A cancelled Batch has `state: "cancelled"` with its partial `result` in `jobs.list`; a waiting control request receives `{"ok":false,"error":"cancelled","result":…}`, and an MCP call through the app bridge gets the error `cancelled; partial result: {…}`. While a job runs, commands that would edit its document fail with "… is still running on this document". `ui.inspect` reports `jobs` (running jobs, opening files, saving files). Set `PHOTOCRAFT_INLINE_JOBS=1` to run everything inline. ## Preferences