MCP command_batch and serve batch honour each step's wait (#415) (#439)

`command_batch` steps reuse `command_run`'s params, so its schema
advertised `wait`, but the tool mapped each step to `{command, params}`
and ran it to completion: `"wait": false` blocked on the filter and
started no job. Steps now carry `wait` (default true): headless batches
start the command through `command_start`, and bridge mode forwards it
to `engine.execute`, which already honours it. `serve`'s `batch` reads a
step's `wait` the same way. The schema doc and docs/control-protocol.md
describe the per-step `wait`.

Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
BFlatandClaude Opus 5.5 authored and GitHub committed 2026-10-07 07:59:57 +07:00
1 parent 7930dd0adf
commit 55054b5fcc
4 files changed
+81 -9

No files matched your search

+28 -3
View File
@@ -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<Value, AutomationError> {
@@ -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();
+6 -2
View File
@@ -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<RunParams>,
/// 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<Value> = p.steps.into_iter().map(|s| json!({"command": s.id, "params": s.params.unwrap_or_else(|| json!({}))})).collect();
let steps: Vec<Value> =
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);
+43 -1
View File
@@ -317,7 +317,7 @@ async fn fake_app() -> (String, tokio::task::JoinHandle<Vec<Value>>) {
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;
+4 -3
View File
@@ -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