diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs index 677cb90482..fa780f71f5 100644 --- a/crates/automation/src/rpc.rs +++ b/crates/automation/src/rpc.rs @@ -11,7 +11,7 @@ //! `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?} | {method, params?}], stopOnError?}` +//! - `batch {steps: [{command, params?, wait?} | {method, params?}], stopOnError?}` //! - `methods`: this list. use std::io::{BufRead, Write}; @@ -133,7 +133,7 @@ impl Headless { } } - /// Run `steps` in order. Each step is `{command, params?}` (an engine command) or + /// Run `steps` in order. Each step is `{command, params?, wait?}` (an engine command) or /// `{method, params?}` (any [`METHODS`] entry). Stops at the first error unless /// `stopOnError` is false; the reply lists every step's result. pub fn batch(&mut self, p: &Value) -> Result { @@ -148,7 +148,9 @@ impl Headless { for (i, s) in steps.iter().enumerate() { let params = s.get("params").cloned().unwrap_or(Value::Null); let r = if let Some(c) = str_of(s, "command") { - self.command_run(c, params) + // Like `engine.execute`: `wait: false` starts a long command as a background job. + let wait = s.get("wait").and_then(Value::as_bool).unwrap_or(true); + self.command_start(c, params, wait) } else if let Some(m) = str_of(s, "method") { if m == "batch" { Err(bad("nested batch")) } else { self.handle(m, params) } } else { @@ -421,6 +423,29 @@ mod tests { assert!(std::sync::Arc::ptr_eq(&h.session.active().unwrap().doc, &before)); } + #[test] + fn batch_steps_can_start_background_jobs() { + let mut h = Headless::new(); + h.handle("doc.new", json!({"width": 600, "height": 400})).unwrap(); + let steps = json!([ + {"command": "layer.new.layer"}, + {"command": "edit.fill", "params": {"color": "#808080"}}, + {"command": "filter.blur.gaussianBlur", "params": {"radius": 40}, "wait": false} + ]); + let r = h.handle("batch", json!({"steps": steps})).unwrap(); + assert_eq!(r["completed"], 3, "{r}"); + let job = r["results"][2]["result"]["job"].as_u64().unwrap_or_else(|| panic!("no job id: {r}")); + assert_eq!(r["results"][2]["result"]["pending"], true); + let listed = h.handle("jobs.list", json!({})).unwrap(); + assert!(listed["jobs"].as_array().unwrap().iter().any(|j| j["id"] == job), "{listed}"); + let t = std::time::Instant::now(); + while h.session.jobs().iter().any(|j| j.id.0 == job) { + assert!(t.elapsed().as_secs() < 60); + std::thread::sleep(std::time::Duration::from_millis(5)); + h.handle("jobs.list", json!({})).unwrap(); + } + } + #[test] fn automation_preview_rejects_oversized_full_size_and_numeric_wraparound() { let mut h = Headless::new(); diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index df507d55e5..bae49ea2e1 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -133,7 +133,10 @@ pub struct JobCancelParams { #[derive(Debug, Deserialize, JsonSchema)] pub struct BatchParams { - /// Commands to run in order: `[{"id": "layer.new.layer", "params": {"name": "Ink"}}, …]`. + /// Commands to run in order: `[{"id": "layer.new.layer", "params": {"name": "Ink"}}, …]`. A + /// step with `"wait": false` starts a long command as a background job (its result is + /// `{"job": id}`, as in `command_run`); later steps that edit the same document fail until + /// the job ends. pub steps: Vec, /// Stop at the first failing step (default true). #[serde(default)] @@ -505,7 +508,8 @@ impl PhotocraftMcp { return Ok(fail(format!("batch contains {} steps; maximum is {MAX_BATCH_STEPS}", p.steps.len()))); } let stop = p.stop_on_error.unwrap_or(true); - let steps: Vec = p.steps.into_iter().map(|s| json!({"command": s.id, "params": s.params.unwrap_or_else(|| json!({}))})).collect(); + let steps: Vec = + p.steps.into_iter().map(|s| json!({"command": s.id, "params": s.params.unwrap_or_else(|| json!({})), "wait": s.wait.unwrap_or(true)})).collect(); let args = json!({"steps": steps, "stopOnError": stop}); if let Some(r) = self.headless_op(move |h| h.batch(&args)).await { return to_result(r); diff --git a/crates/automation/tests/mcp.rs b/crates/automation/tests/mcp.rs index 438c546557..162458b759 100644 --- a/crates/automation/tests/mcp.rs +++ b/crates/automation/tests/mcp.rs @@ -317,7 +317,7 @@ async fn fake_app() -> (String, tokio::task::JoinHandle>) { json!({"id": id, "ok": true, "result": {"tool": "brush", "panels": ["layers"]}}) } "engine.execute" => { - json!({"id": id, "ok": true, "result": {"ran": req["params"]["command"], "params": req["params"]["params"]}}) + json!({"id": id, "ok": true, "result": {"ran": req["params"]["command"], "params": req["params"]["params"], "wait": req["params"]["wait"]}}) } "engine.commands" => { json!({"id": id, "ok": true, "result": [{"id": "file.new", "label": "New…", "enabled": true}]}) @@ -421,6 +421,48 @@ async fn command_batch_runs_steps_in_order() { client.cancel().await.unwrap(); } +#[tokio::test(flavor = "multi_thread")] +async fn command_batch_step_without_waiting_starts_a_background_job() { + let client = connect(PhotocraftMcp::headless()).await; + json_of(&call(&client, "doc_new", json!({"width": 600, "height": 400})).await); + let blur = json!({"id": "filter.blur.gaussianBlur", "params": {"radius": 40}, "wait": false}); + let r = json_of( + &call(&client, "command_batch", json!({"steps": [{"id": "layer.new.layer"}, {"id": "edit.fill", "params": {"color": "#808080"}}, blur]})).await, + ); + assert_eq!(r["completed"], 3, "{r}"); + let started = &r["results"][2]["result"]; + assert_eq!(started["pending"], true, "the step returned without waiting: {r}"); + let job = started["job"].as_u64().expect("a job id"); + // The job is listed and finishes like one started by command_run. + let t = std::time::Instant::now(); + loop { + let l = json_of(&call(&client, "jobs_list", json!({})).await); + let state = l["jobs"].as_array().unwrap().iter().find(|j| j["id"] == job).map(|j| j["state"].clone()); + assert!(state.is_some(), "job {job} not listed: {l}"); + if state == Some(json!("done")) { + break; + } + assert!(t.elapsed().as_secs() < 60, "{l}"); + tokio::time::sleep(std::time::Duration::from_millis(5)).await; + } + // Without `wait` a step still returns the command's own result. + let r = json_of(&call(&client, "command_batch", json!({"steps": [{"id": "filter.blur.gaussianBlur", "params": {"radius": 2}}]})).await); + assert!(r["results"][0]["result"]["filter"].is_object(), "{r}"); + client.cancel().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread")] +async fn bridge_command_batch_forwards_each_steps_wait() { + let (addr, app) = fake_app().await; + let client = connect(PhotocraftMcp::bridge(&addr, CONTROL_TOKEN).unwrap()).await; + let r = json_of(&call(&client, "command_batch", json!({"steps": [{"id": "filter.blur.gaussianBlur", "wait": false}, {"id": "layer.new.layer"}]})).await); + assert_eq!(r["completed"], 2, "{r}"); + assert_eq!(r["results"][0]["result"]["wait"], false, "{r}"); + assert_eq!(r["results"][1]["result"]["wait"], true, "{r}"); + client.cancel().await.unwrap(); + app.abort(); +} + #[tokio::test(flavor = "multi_thread")] async fn command_batch_rejects_too_many_steps() { let client = connect(PhotocraftMcp::headless()).await; diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 6d554e0227..c4be38630c 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -203,7 +203,7 @@ no MCP framing, no app start-up per command. Configure its file access with the | `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?}` | -| `batch` | `{steps: [{command, params?} \| {method, params?}], stopOnError? (true)}` → `{completed, failed, results}` | +| `batch` | `{steps: [{command, params?, wait?} \| {method, params?}], stopOnError? (true)}` → `{completed, failed, results}` (a step with `wait: false` starts a long command as a background job, like `engine.execute`) | | `methods` | the list above | ```sh @@ -214,8 +214,9 @@ printf '%s\n' \ photocraft-cli serve --automation-read-root /work/project --automation-write-root /work/project ``` -The MCP server has the same batching as the `command_batch` tool (`{steps:[{id, params}], stop_on_error}`), -in headless and bridge mode. +The MCP server has the same batching as the `command_batch` tool (`{steps:[{id, params, wait?}], stop_on_error}`), +in headless and bridge mode. A step with `wait: false` returns `{job, pending}` at once, as `command_run` +does; later steps that edit the same document fail with a message naming the job until it ends. ## Transport limits