From 85cb54025cdb421e8a811aa756d317ef80b6967c Mon Sep 17 00:00:00 2001 From: Fabio Lissi Date: Sun, 1 Nov 2026 23:56:10 -0600 Subject: [PATCH] Guard Batch outputs and preserve partial results --- apps/photocraft-cli/src/batch.rs | 6 +- apps/photocraft-cli/tests/it/cli.rs | 27 ++++++ .../engine/src/cmd/file_cmds/batch_naming.rs | 4 +- crates/engine/src/cmd/file_cmds/batch_run.rs | 64 ++++++------- crates/engine/src/cmd/file_cmds/paths.rs | 71 ++++++++------ crates/engine/src/cmd/file_cmds/tests.rs | 95 +++++++++++++++++++ crates/engine/src/jobs.rs | 13 ++- crates/engine/src/jobs/tests.rs | 26 +++++ docs/batch-naming.md | 4 +- docs/control-protocol.md | 2 +- 10 files changed, 243 insertions(+), 69 deletions(-) diff --git a/apps/photocraft-cli/src/batch.rs b/apps/photocraft-cli/src/batch.rs index d2f35c57e4..15abd8848c 100644 --- a/apps/photocraft-cli/src/batch.rs +++ b/apps/photocraft-cli/src/batch.rs @@ -66,8 +66,10 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) -> } else { std::fs::read_dir(in_dir) .map_err(|source| CliError::ReadDir { path: in_dir.to_path_buf(), source })? - .flatten() - .map(|entry| entry.path()) + .map(|entry| entry.map(|entry| entry.path())) + .collect::>>() + .map_err(|source| CliError::ReadDir { path: in_dir.to_path_buf(), source })? + .into_iter() .filter(|path| is_input(path)) .map(|path| photocraft_engine::file_cmds::BatchInput { path: path.to_string_lossy().into_owned(), rel_dir: String::new() }) .collect() diff --git a/apps/photocraft-cli/tests/it/cli.rs b/apps/photocraft-cli/tests/it/cli.rs index 2981db84c6..5d7b597134 100644 --- a/apps/photocraft-cli/tests/it/cli.rs +++ b/apps/photocraft-cli/tests/it/cli.rs @@ -847,6 +847,33 @@ fn batch_refuses_to_write_over_its_inputs() { assert!(after.iter().zip(&before).all(|(a, b)| a.0 == b.0 && a.1 != b.1), "both inputs replaced"); } +#[test] +fn batch_naming_rejects_unread_input_alias_through_a_missing_directory() { + let d = tmp("batch-missing-directory-alias"); + let input = d.join("in"); + std::fs::create_dir_all(&input).unwrap(); + write_png(&input.join("a.png"), 8, 4, 3); + write_png(&input.join("b.png"), 8, 4, 7); + let original = std::fs::read(input.join("b.png")).unwrap(); + let actions = d.join("actions.json"); + std::fs::write(&actions, r#"[{"command":"image.adjustments.invert"}]"#).unwrap(); + let output = bin() + .arg("batch") + .arg("--actions") + .arg(&actions) + .arg("--in") + .arg(&input) + .arg("--out") + .arg(input.join("missing/..")) + .args(["--in-place", "--naming", "b.{ext}"]) + .output() + .unwrap(); + assert!(!output.status.success(), "{}", String::from_utf8_lossy(&output.stdout)); + assert!(String::from_utf8_lossy(&output.stderr).contains("replace an input")); + assert_eq!(std::fs::read(input.join("b.png")).unwrap(), original); + assert!(!input.join("missing").exists()); +} + /// #7437: `convert` to its own input file, however the output is spelt, is refused before /// anything is read or written, unless `--in-place` asks for it (as `batch` does, #492). #[test] diff --git a/crates/engine/src/cmd/file_cmds/batch_naming.rs b/crates/engine/src/cmd/file_cmds/batch_naming.rs index 706930b9c5..8d6bfba083 100644 --- a/crates/engine/src/cmd/file_cmds/batch_naming.rs +++ b/crates/engine/src/cmd/file_cmds/batch_naming.rs @@ -183,7 +183,9 @@ pub fn plan(inputs: &[BatchInput], output: &str, format: &str, params: &Value) - { let sources: std::collections::HashSet<_> = inputs.iter().filter_map(|i| std::fs::canonicalize(&i.path).ok()).collect(); for output in &outputs { - if std::fs::canonicalize(output).ok().is_some_and(|p| sources.contains(&p)) { + let identity = super::paths::destination_identity(std::path::Path::new(output)) + .ok_or_else(|| bad(format!("naming output path cannot be resolved safely: {output}")))?; + if sources.contains(&identity) { return Err(bad(format!("naming would replace an input file: {output}; choose a different destination or template"))); } } diff --git a/crates/engine/src/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs index 52db5a0e5c..93e8da6d66 100644 --- a/crates/engine/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine/src/cmd/file_cmds/batch_run.rs @@ -49,7 +49,7 @@ pub(crate) fn batch_inputs_tree(p: &Value, cmd: &str, output: &str) -> Result Result> { use std::path::{Path, PathBuf}; @@ -64,12 +64,8 @@ pub fn list_images_tree(dir: &str, skip: &str, cmd: &str) -> Result = vec![(root.to_path_buf(), String::new(), 0)]; while let Some((folder, rel, depth)) = stack.pop() { let shown = folder.to_string_lossy().into_owned(); - // The top folder must be readable; a subfolder that isn't is skipped. - let files = match list_images(&shown) { - Ok(f) => f, - Err(e) if depth == 0 => return Err(e), - Err(_) => continue, - }; + // Fail before writing any output if a reached input folder cannot be read. + let files = list_images(&shown)?; if out.len().saturating_add(files.len()) > MAX_SUBFOLDER_FILES { return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("{dir} holds more than {MAX_SUBFOLDER_FILES} images with its subfolders") }); } @@ -77,17 +73,14 @@ pub fn list_images_tree(dir: &str, skip: &str, cmd: &str) -> Result= MAX_SUBFOLDER_DEPTH { continue; } - let Ok(rd) = std::fs::read_dir(&folder) else { continue }; - let mut subs: Vec<(String, PathBuf)> = rd - .filter_map(|e| e.ok()) - .map(|e| e.path()) - .filter(|p| p.is_dir()) - .filter_map(|p| Some((p.file_name()?.to_string_lossy().into_owned(), p))) - .collect(); + let rd = std::fs::read_dir(&folder).map_err(|e| EngineError::Other(format!("{shown}: {e}")))?; + let entries = rd.collect::>>().map_err(|e| EngineError::Other(format!("{shown}: {e}")))?; + let mut subs: Vec<(String, PathBuf)> = + entries.into_iter().map(|e| e.path()).filter(|p| p.is_dir()).filter_map(|p| Some((p.file_name()?.to_string_lossy().into_owned(), p))).collect(); subs.sort(); // Pushed in reverse so the stack pops them in name order. for (name, sub) in subs.into_iter().rev() { - let Some(c) = canon(&sub) else { continue }; + let c = canon(&sub).ok_or_else(|| EngineError::Other(format!("{}: cannot resolve the subfolder", sub.display())))?; if skip.as_ref() == Some(&c) || !seen.insert(c) { continue; } @@ -249,6 +242,10 @@ fn write_error_log(path: &str, errors: &[Value]) -> Result<()> { super::paths::write_file(path, body.as_bytes()).map_err(|error| EngineError::Other(format!("error log: {error}"))) } +fn error_log_failure(path: Option<&str>, errors: &[Value]) -> Option { + path.filter(|_| !errors.is_empty()).and_then(|path| write_error_log(path, errors).err().map(|error| error.to_string())) +} + fn batch_outcome(files: Vec, errors: Vec, stopped: Option<(String, Vec)>, error_log: Option<&str>) -> Value { let logged = !errors.is_empty(); let mut result = json!({"files": files, "errors": errors}); @@ -306,17 +303,21 @@ fn process_batch_outputs( } } } - if let Some(path) = &policy.error_log - && !errors.is_empty() - { - write_error_log(path, &errors)?; + let log_failure = error_log_failure(policy.error_log.as_deref(), &errors); + let cancelled = ctx.cancelled(); + if !cancelled { + ctx.progress(1.0, ""); } - if ctx.cancelled() { - return Err(EngineError::Cancelled); - } - ctx.progress(1.0, ""); let skipped = outputs.iter().skip(done).map(|(path, _)| path.clone()).collect(); - Ok(batch_outcome(files, errors, stopped.map(|at| (at, skipped)), policy.error_log.as_deref())) + let mut result = batch_outcome(files, errors, stopped.map(|at| (at, skipped)), policy.error_log.as_deref().filter(|_| log_failure.is_none())); + if cancelled { + result["cancelled"] = json!(true); + result["skipped"] = json!(outputs.iter().skip(done).map(|(path, _)| path).collect::>()); + } + if let Some(error) = log_failure { + result["errorLogError"] = json!(error); + } + Ok(result) } /// The output paths a batch run has written, so a later input whose output name matches an @@ -554,8 +555,8 @@ fn batch_open_documents( let out = paths.get(index).ok_or_else(|| EngineError::Other("batch output plan is incomplete".into()))?; claims.check(out).map_err(EngineError::Other)?; let doc = match saved { - Some(saved) if s.active().is_none_or(|active| active.doc.id != saved.id) => saved, - _ => s.documents().iter().find(|state| state.doc.id.0 == *id).ok_or(EngineError::NoDocument)?.doc.clone(), + Some(saved) => saved, + None => s.documents().iter().find(|state| state.doc.id.0 == *id).ok_or(EngineError::NoDocument)?.doc.clone(), }; save_doc(&doc, out, save)?; claims.record(out, name); @@ -576,13 +577,12 @@ fn batch_open_documents( { s.set_active(position); } - if let Some(path) = &policy.error_log - && !errors.is_empty() - { - write_error_log(path, &errors)?; - } + let log_failure = error_log_failure(policy.error_log.as_deref(), &errors); let skipped = originals.iter().skip(done).map(|(_, name, _)| name.clone()).collect(); - let mut result = batch_outcome(files, errors, stopped.map(|at| (at, skipped)), policy.error_log.as_deref()); + let mut result = batch_outcome(files, errors, stopped.map(|at| (at, skipped)), policy.error_log.as_deref().filter(|_| log_failure.is_none())); + if let Some(error) = log_failure { + result["errorLogError"] = json!(error); + } result["documents"] = json!(originals.len()); Ok(result) } diff --git a/crates/engine/src/cmd/file_cmds/paths.rs b/crates/engine/src/cmd/file_cmds/paths.rs index 41d6121b94..63455286ec 100644 --- a/crates/engine/src/cmd/file_cmds/paths.rs +++ b/crates/engine/src/cmd/file_cmds/paths.rs @@ -40,8 +40,9 @@ pub(crate) fn write_file(path: &str, _bytes: &[u8]) -> Result<()> { #[cfg(not(target_arch = "wasm32"))] pub fn list_images(dir: &str) -> Result> { let rd = std::fs::read_dir(dir).map_err(|e| EngineError::Other(format!("{dir}: {e}")))?; - let mut out: Vec = rd - .filter_map(|e| e.ok()) + let entries = rd.collect::>>().map_err(|e| EngineError::Other(format!("{dir}: {e}")))?; + let mut out: Vec = entries + .into_iter() .map(|e| e.path()) .filter(|p| p.is_file() && openable_name(&p.to_string_lossy())) .map(|p| p.to_string_lossy().into_owned()) @@ -181,6 +182,34 @@ pub fn same_file(a: impl AsRef, b: impl AsRef) false } +/// Resolve a future output path component by component. Existing symlinks are followed before +/// applying a later `..`, while components not created yet are kept so a new `x/../file` still +/// resolves to the file it would reach after `x` is created. +#[cfg(not(target_arch = "wasm32"))] +pub fn destination_identity(path: &std::path::Path) -> Option { + use std::path::{Component, PathBuf}; + let absolute = if path.is_absolute() { path.to_path_buf() } else { std::env::current_dir().ok()?.join(path) }; + let mut resolved = PathBuf::new(); + for component in absolute.components() { + match component { + Component::CurDir => {} + Component::ParentDir => { + resolved.pop(); + } + Component::Normal(_) => { + resolved.push(component.as_os_str()); + match std::fs::symlink_metadata(&resolved) { + Ok(_) => resolved = std::fs::canonicalize(&resolved).ok()?, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => return None, + } + } + Component::Prefix(_) | Component::RootDir => resolved.push(component.as_os_str()), + } + } + Some(resolved) +} + /// Whether two paths would name the same destination even before the file exists. This is used /// when a batch error log must not be allowed to replace a result that will be written later. pub fn same_destination(a: impl AsRef, b: impl AsRef) -> bool { @@ -190,36 +219,20 @@ pub fn same_destination(a: impl AsRef, b: impl AsRef Option { - let absolute = if path.is_absolute() { path.to_path_buf() } else { std::env::current_dir().ok()?.join(path) }; - let mut clean = PathBuf::new(); - for component in absolute.components() { - match component { - Component::CurDir => {} - Component::ParentDir => { - clean.pop(); + match (destination_identity(a), destination_identity(b)) { + (Some(a), Some(b)) => { + #[cfg(any(target_os = "windows", target_os = "macos"))] + { + match (a.to_str(), b.to_str()) { + (Some(a), Some(b)) => a.eq_ignore_ascii_case(b), + _ => a == b, } - other => clean.push(other.as_os_str()), + } + #[cfg(not(any(target_os = "windows", target_os = "macos")))] + { + a == b } } - let mut existing = clean.as_path(); - let mut suffix = Vec::new(); - while !existing.exists() { - suffix.push(existing.file_name()?.to_os_string()); - existing = existing.parent()?; - } - let mut resolved = std::fs::canonicalize(existing).ok()?; - for component in suffix.into_iter().rev() { - resolved.push(component); - } - Some(resolved) - }; - match (normalize(a), normalize(b)) { - (Some(a), Some(b)) => match (a.to_str(), b.to_str()) { - (Some(a), Some(b)) => a.eq_ignore_ascii_case(b), - _ => a == b, - }, _ => false, } } diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index e87eac1c69..ef9758fa53 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -64,6 +64,45 @@ fn batch_error_log_cannot_replace_an_input_or_result() { } } +#[test] +fn batch_naming_rejects_an_input_alias_through_a_missing_parent() { + let dir = tmp("batch-missing-parent-alias"); + let first = png(&dir, "a.png", 8, 6, "#ff0000"); + let second = png(&dir, "b.png", 8, 6, "#00ff00"); + let original = std::fs::read(&second).unwrap(); + let output = join(&dir, "missing/.."); + let error = + Session::new().execute("file.automate.batch", json!({"steps": [], "input": [first, second], "output": output, "naming": "b.{ext}"})).unwrap_err(); + assert!(error.to_string().contains("replace an input"), "{error}"); + assert_eq!(std::fs::read(&second).unwrap(), original); + assert!(!std::path::Path::new(&join(&dir, "missing")).exists()); +} + +#[cfg(unix)] +#[test] +fn batch_error_log_rejects_a_symlink_parent_alias() { + use std::os::unix::fs::symlink; + let dir = tmp("batch-symlink-parent-alias"); + let source_dir = join(&dir, "in"); + std::fs::create_dir_all(&source_dir).unwrap(); + let input = png(&source_dir, "result.png", 8, 6, "#ff0000"); + let other = join(&dir, "other"); + std::fs::create_dir_all(join(&other, "child")).unwrap(); + symlink(join(&other, "child"), join(&dir, "link")).unwrap(); + let output = other; + let log = join(&dir, "link/../result.png"); + let error = Session::new().execute("file.automate.batch", json!({"steps": [], "input": [input], "output": output, "errorLog": log})).unwrap_err(); + assert!(error.to_string().contains("errorLog"), "{error}"); + assert!(!std::path::Path::new(&join(&output, "result.png")).exists()); +} + +#[cfg(target_os = "linux")] +#[test] +fn linux_distinct_case_destinations_are_not_the_same_file() { + let dir = tmp("batch-case-sensitive-destinations"); + assert!(!same_destination(join(&dir, "Image.png"), join(&dir, "image.png"))); +} + #[test] fn batch_open_source_edits_each_live_document_and_restores_the_active_one() { let dir = tmp("batch-open-documents"); @@ -87,6 +126,62 @@ fn batch_open_source_edits_each_live_document_and_restores_the_active_one() { assert!(std::path::Path::new(&join(&dir, "02_SECOND.PNG")).is_file()); } +#[test] +fn batch_open_source_exports_the_document_at_the_save_point() { + let dir = tmp("batch-open-save-point"); + let mut session = Session::new(); + session.execute("file.new", json!({"name": "First", "width": 8, "height": 6})).unwrap(); + session.execute("file.new", json!({"name": "Second", "width": 12, "height": 5})).unwrap(); + let result = session + .execute( + "file.automate.batch", + json!({ + "source": "open", "steps": [["document.activate", {"document": 1}], ["file.save", {}]], + "output": dir, "format": "png", "naming": "{name}.{ext}" + }), + ) + .unwrap(); + assert!(result["errors"].as_array().unwrap().is_empty(), "{result}"); + let mut opened = Session::new(); + opened.execute("file.openAs", json!({"path": join(&dir, "First.png"), "as": "png"})).unwrap(); + assert_eq!(doc(&opened).size.width, 12, "the save point selected the second document"); +} + +#[test] +fn batch_reports_file_failures_even_if_error_log_cannot_be_written() { + let dir = tmp("batch-error-log-write-fails"); + let mut session = session(8, 6, 8); + let result = session + .execute( + "file.automate.batch", + json!({ + "source": "open", "steps": [["layer.select", {"layer": "does not exist"}]], + "output": dir, "format": "png", "errorLog": dir + }), + ) + .unwrap(); + assert_eq!(result["files"], json!([])); + assert_eq!(result["errors"].as_array().map(Vec::len), Some(1), "{result}"); + assert!(result["errorLogError"].as_str().is_some(), "{result}"); +} + +#[cfg(unix)] +#[test] +fn recursive_batch_reports_an_unreadable_subfolder() { + use std::os::unix::fs::PermissionsExt; + let dir = tmp("batch-unreadable-subfolder"); + let sub = join(&dir, "locked"); + std::fs::create_dir_all(&sub).unwrap(); + png(&sub, "image.png", 8, 6, "#ff0000"); + std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o000)).unwrap(); + let inaccessible = std::fs::read_dir(&sub).is_err(); + let result = list_images_tree(&dir, "", "file.automate.batch"); + std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o700)).unwrap(); + if inaccessible { + assert!(result.is_err(), "an inaccessible input folder must not be omitted"); + } +} + #[test] fn close_all_and_close_others() { let mut s = session(8, 8, 8); diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rs index ac9e38a723..3c2cb9e3b9 100644 --- a/crates/engine/src/jobs.rs +++ b/crates/engine/src/jobs.rs @@ -693,10 +693,17 @@ impl Session { } } - /// Cancel job `id`: it stops at its next check, its result is discarded and the document - /// stays unchanged. The document is unlocked at once. False if no such job is running. + /// Cancel job `id`: ordinary jobs stop at their next check and discard their result. + /// A batch finishes the current input and reports outputs already written. False if no + /// such job is running. pub fn cancel_job(&mut self, id: JobId) -> bool { let Some(i) = self.jobs.running.iter().position(|r| r.id == id) else { return false }; + // Earlier batch outputs are already on disk. Let the worker stop after its current + // input and return the completed and skipped lists. + if self.jobs.running[i].command == "file.automate.batch" { + self.jobs.running[i].ctx.cancel(); + return true; + } // A print worker can already have handed the job to the OS. Discarding its result // would falsely report cancellation; removal belongs to the system print queue. if matches!(self.jobs.running[i].command.as_str(), "file.print" | "file.printOneCopy") { @@ -977,7 +984,7 @@ impl Session { let outcome = match r { Err(EngineError::Cancelled) => JobOutcome::Cancelled, Err(e) => JobOutcome::Failed(e.to_string()), - Ok(_) if job.ctx.cancelled() => JobOutcome::Cancelled, + Ok(_) if job.ctx.cancelled() && job.command != "file.automate.batch" => JobOutcome::Cancelled, Ok(payload) => match self.apply_job(&job, apply, payload) { Ok(v) => JobOutcome::Done(v), Err(EngineError::Cancelled) => JobOutcome::Cancelled, diff --git a/crates/engine/src/jobs/tests.rs b/crates/engine/src/jobs/tests.rs index 0974a5c17a..19502cae35 100644 --- a/crates/engine/src/jobs/tests.rs +++ b/crates/engine/src/jobs/tests.rs @@ -543,6 +543,32 @@ fn open_runs_as_a_job_and_cancel_adds_nothing() { assert!(matches!(wait_event(&mut s, id).outcome, JobOutcome::Failed(_))); } +#[test] +fn cancelled_batch_job_returns_its_partial_result() { + let mut s = Session::new(); + let id = job(s + .start_job( + "file.automate.batch", + json!({}), + "Batch", + false, + |ctx| { + while !ctx.cancelled() { + std::thread::sleep(Duration::from_millis(2)); + } + Ok(json!({"files": ["done.png"], "skipped": ["later.png"], "cancelled": true})) + }, + |_, result| Ok(result), + ) + .unwrap()); + assert!(s.cancel_job(id)); + let event = wait_event(&mut s, id); + let JobOutcome::Done(result) = &event.outcome else { panic!("batch result was discarded: {:?}", event.outcome) }; + assert_eq!(result["files"], json!(["done.png"])); + assert_eq!(result["skipped"], json!(["later.png"])); + assert_eq!(result["cancelled"], true); +} + /// Ask When Opening: a file whose profile doesn't match is decoded but not added; the shell takes /// it once the prompt is answered. Without Ask it opens as usual. #[test] diff --git a/docs/batch-naming.md b/docs/batch-naming.md index d6f64e33cd..caa17e78e2 100644 --- a/docs/batch-naming.md +++ b/docs/batch-naming.md @@ -21,7 +21,9 @@ keeps its order. Failed inputs consume their position, so later filenames do not Braces in an input filename are literal text, not additional tokens. Subfolder inputs keep their relative folders under the output folder. **Stop On Error** leaves later inputs unprocessed; **Error Log** records failures and their reasons. Folder batches report progress per file and -can be cancelled after the current file. +can be cancelled after the current file. A cancelled batch returns `cancelled: true`, its +completed `files`, and `skipped` inputs. If writing the error log fails, the batch still +returns its per-file results with `errorLogError` instead of `errorLog`. Unknown tokens, unmatched braces, invalid parameter types, path separators, reserved filename characters, excessive filename length (255 UTF-8 bytes), and serial overflow are rejected before diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 7c5f4f2c24..b5f0dca68e 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. 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 and reports those paths when cancelled. 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