fix(automation): review findings on the agents channel (from #4428's review)

- Plain `mcp` routed to a headless session runs a blocking render as a long job again
  (progress, other requests, cancellation): the long-job path uses the routed session.
- A tool's calls all go to one route, so a window closing mid-tool can't split them.
- The window's `agent_folders` answer is narrowed to the command's folders.
- A write-only session names its write folder as its read folder too.
- `file.revert` checks the open project's file against the read folders; `file.save` with
  a non-string `path` checks the open project's file against the write folders.
- Reverting (and the reload after the file changed) keeps an agent's footage limits.
- An agent request queued before the switch turned off, or the folders changed, doesn't run;
  a request with other limits waits until queued input from another scope was applied.
- Docs: several write roots need --headless. Tests: fixture cleanup, broken-pipe write.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
David Mann
2026-12-04 19:38:55 +01:00
parent e3cf095cd3
commit dc3211b354
14 changed files with 210 additions and 26 deletions
+3 -1
View File
@@ -1337,6 +1337,7 @@ fn live_mcp_call(args: &[&str], tool: &str) -> (Value, String) {
writeln!(stdin, "{}", json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": tool, "arguments": {}}})).unwrap();
}
let out = child.wait_with_output().unwrap();
let _ = std::fs::remove_dir_all(&root);
let reply: Value = serde_json::from_str(String::from_utf8(out.stdout).unwrap().lines().next().unwrap_or("null")).unwrap();
(reply["result"].clone(), String::from_utf8_lossy(&out.stderr).into_owned())
}
@@ -1393,7 +1394,8 @@ fn mcp_opens_the_start_project_only_inside_its_roots() {
.stderr(Stdio::piped())
.spawn()
.unwrap();
writeln!(child.stdin.take().unwrap(), "{}", json!({"jsonrpc": "2.0", "id": 1, "method": "ping"})).unwrap();
// A refused start may have exited already: its stdin is then closed.
let _ = writeln!(child.stdin.take().unwrap(), "{}", json!({"jsonrpc": "2.0", "id": 1, "method": "ping"}));
child.wait_with_output().unwrap()
};
let refused = start(&inside);
+2 -1
View File
@@ -95,7 +95,8 @@ pub fn folders_answer(confinement: Option<&Confinement>) -> Value {
match confinement {
Some(c) => {
let mut folders = AgentFolders::default();
folders.read = c.read_roots().first().cloned();
// A write root may be read too: with no read root of its own, it is the read folder.
folders.read = c.read_roots().first().or(c.write_roots().first()).cloned();
folders.write = c.write_roots().first().cloned();
shared::folders_answer(&folders)
}
+48
View File
@@ -239,3 +239,51 @@ fn a_handshake_reply_without_an_end_is_not_read_forever() {
let e = live(config(&dir, allowed)).unwrap().exec("project.summary", json!({})).unwrap_err().to_string();
assert!(e.contains("longer than"), "{e}");
}
/// Plain `mcp` routed to a headless session runs a blocking render as a long job (progress,
/// other requests answered meanwhile, cancellation), as `mcp` without a window always did.
#[test]
fn a_render_in_the_live_headless_session_is_a_long_job() {
let dir = temp("long");
let mut server = McpServer::new(live(config(&dir, not_allowed)).unwrap());
let msg = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "command_run", "arguments": {"id": "renderQueue.render"}}});
assert!(crate::long_job::long_call(&mut server, &msg).is_some());
}
/// The window's folders, narrowed to the command's: only what both allow is named.
#[test]
fn the_window_names_only_folders_the_commands_folders_allow() {
let (own, other) = (temp("narrow-own"), temp("narrow-other"));
let inside = own.join("sub");
std::fs::create_dir_all(&inside).unwrap();
let own = own.canonicalize().unwrap();
let confinement = crate::confine::Confinement::new(std::slice::from_ref(&own), std::slice::from_ref(&own)).unwrap();
let window = json!({"read_folder": other.to_string_lossy(), "write_folder": own.join("sub").to_string_lossy()});
let narrowed = crate::backend::narrow_folders(window, &confinement);
assert!(narrowed["read_folder"].is_null(), "{narrowed}");
assert_eq!(narrowed["write_folder"].as_str().map(PathBuf::from), Some(own.join("sub")), "{narrowed}");
// A command folder inside the window's takes its place.
let window = json!({"read_folder": own.parent().unwrap().to_string_lossy(), "write_folder": null});
let narrowed = crate::backend::narrow_folders(window, &confinement);
assert_eq!(narrowed["read_folder"].as_str().map(PathBuf::from), Some(own.clone()), "{narrowed}");
// A session with only a write folder reads there too, and says so.
let write_only = crate::confine::Confinement::new(&[], std::slice::from_ref(&own)).unwrap();
let answer = crate::agents::folders_answer(Some(&write_only));
assert_eq!(answer["read_folder"].as_str().map(PathBuf::from), Some(own), "{answer}");
}
/// `file.revert` reads the open project's file again, and `file.save` with an array path writes
/// the open project's file: both are checked against the folders like a path the agent gives.
#[test]
fn revert_and_save_without_a_path_string_check_the_open_projects_file() {
use crate::confine::{Confinement, Lookup};
let (root, outside) = (temp("revert-root"), temp("revert-outside"));
let c = Confinement::new(std::slice::from_ref(&root), std::slice::from_ref(&root)).unwrap();
let away = json!({"path": outside.join("p.ecproj").to_string_lossy()});
let lookups = c.check_command("file.revert", &json!({})).unwrap();
assert!(matches!(lookups[..], [Lookup::ProjectRead]), "revert looked up nothing");
assert!(c.check_lookup(&Lookup::ProjectRead, &away).is_err(), "revert of a project outside the folders was allowed");
assert!(c.check_lookup(&Lookup::ProjectRead, &json!({"path": root.join("p.ecproj").to_string_lossy()})).is_ok());
let lookups = c.check_command("file.save", &json!({"path": []})).unwrap();
assert!(matches!(lookups[..], [Lookup::ProjectFile]), "save with an array path skipped the open project's file");
}
+37 -4
View File
@@ -87,12 +87,30 @@ impl Backend {
if let Some(inner) = self.routed()? {
return lock(&inner).agent_folders();
}
match &mut self.target {
Target::Bridge(b) => b.call(crate::agents::FOLDERS_METHOD, json!({})),
match (&mut self.target, &self.confinement) {
// The command's folders bind the window too: name only what both allow.
(Target::Bridge(b), Some(c)) => Ok(narrow_folders(b.call(crate::agents::FOLDERS_METHOD, json!({}))?, c)),
(Target::Bridge(b), None) => b.call(crate::agents::FOLDERS_METHOD, json!({})),
_ => Ok(crate::agents::folders_answer(self.confinement.as_ref())),
}
}
/// Where a tool's calls all go: plain `mcp`'s live backend picks the window or the headless
/// session once per tool, so a tool's later calls can't land in another session than its
/// first (a window that closed in between). `None`: this backend runs them itself.
pub(crate) fn route(&self) -> Result<Option<std::sync::Arc<std::sync::Mutex<Backend>>>> {
self.routed()
}
/// Runs `f` on the in-process session calls run in: this backend's own, or the headless
/// session plain `mcp` routes to. `None` when calls go to a window.
pub fn with_session<R>(&mut self, f: impl FnOnce(&mut Session) -> R) -> Option<R> {
if let Ok(Some(inner)) = self.routed() {
return lock(&inner).with_session(f);
}
self.session().map(f)
}
/// Confine the files the commands run here may read and write ([`Confinement`]). In-process,
/// the session's own footage and file reads are confined too, so a project from a read root
/// can't show footage from outside it.
@@ -130,7 +148,7 @@ impl Backend {
if let Some(c) = self.confinement.clone() {
for lookup in c.check_command(id, &params)? {
let found = match lookup {
Lookup::ProjectFile | Lookup::QueueDefault => self.run("project.summary", json!({}))?,
Lookup::ProjectFile | Lookup::ProjectRead | Lookup::QueueDefault => self.run("project.summary", json!({}))?,
Lookup::RenderOutputs => self.run("renderQueue.list", json!({}))?,
};
c.check_lookup(&lookup, &found)?;
@@ -329,7 +347,22 @@ fn no_comp(comp: Option<&Value>) -> Error {
}
/// A live session's backend, whichever thread used it last.
fn lock(inner: &std::sync::Mutex<Backend>) -> std::sync::MutexGuard<'_, Backend> {
/// The window's `agent_folders` answer, narrowed to `confinement` (the command's folders): a
/// window folder inside one of them stays, a command folder inside the window's takes its place,
/// and folders that don't nest leave that direction with none.
pub(crate) fn narrow_folders(mut answer: Value, confinement: &Confinement) -> Value {
let reads: Vec<&std::path::PathBuf> = confinement.read_roots().iter().chain(confinement.write_roots()).collect();
let writes: Vec<&std::path::PathBuf> = confinement.write_roots().iter().collect();
for (key, roots) in [("read_folder", reads), ("write_folder", writes)] {
let window = answer.get(key).and_then(Value::as_str).map(std::path::PathBuf::from);
let both =
window.and_then(|w| if roots.iter().any(|r| w.starts_with(r)) { Some(w) } else { roots.iter().find(|r| r.starts_with(&w)).map(|r| (*r).clone()) });
answer[key] = both.map_or(Value::Null, |p| json!(p.to_string_lossy()));
}
answer
}
pub(crate) fn lock(inner: &std::sync::Mutex<Backend>) -> std::sync::MutexGuard<'_, Backend> {
inner.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
+13 -3
View File
@@ -167,8 +167,10 @@ const QUEUES_AN_OUTPUT: &[&str] = &["renderQueue.add", "render.preRender", "file
/// What must be looked up before an implicitly writing command may run.
#[derive(Debug, PartialEq, Eq)]
pub enum Lookup {
/// The open project's file (`project.summary` → `path`).
/// The open project's file (`project.summary` → `path`), which the command writes.
ProjectFile,
/// The open project's file, which the command reads again (`file.revert`).
ProjectRead,
/// Every output of the queued Render Queue items (`renderQueue.list`).
RenderOutputs,
/// Whether the open project has a file (`project.summary` → `path`): a render queued without
@@ -206,7 +208,7 @@ impl Confinement {
let params = if params.is_null() { &empty } else { params };
for lookup in self.check_command(id, params).map_err(|e| e.to_string())? {
let query = match lookup {
Lookup::ProjectFile | Lookup::QueueDefault => "project.summary",
Lookup::ProjectFile | Lookup::ProjectRead | Lookup::QueueDefault => "project.summary",
Lookup::RenderOutputs => "renderQueue.list",
};
let found = session.execute(query, empty.clone()).map_err(|e| e.to_string())?;
@@ -417,9 +419,15 @@ impl Confinement {
if QUEUES_AN_OUTPUT.contains(&id) && !gave_a_file {
lookups.push(Lookup::QueueDefault);
}
if IMPLICIT_WRITES.contains(&id) && !(given && id == "file.save") {
// Save with a `path` writes there, checked above; with anything else (an array, which it
// ignores) it writes the open project's file.
if IMPLICIT_WRITES.contains(&id) && !(gave_a_file && id == "file.save") {
lookups.push(if id == "file.save" || id == "file.incrementAndSave" { Lookup::ProjectFile } else { Lookup::RenderOutputs });
}
// Revert reads the open project's file again, wherever it is.
if id == "file.revert" {
lookups.push(Lookup::ProjectRead);
}
Ok(lookups)
}
@@ -431,6 +439,8 @@ impl Confinement {
Some(p) => self.check(p, Access::Write).map(drop),
None => Err(Error::BadArgs("the project has no file yet: give `path` (Save As) inside an automation write root".into())),
},
// Without a file there is nothing to read; the command says so itself.
Lookup::ProjectRead => found.get("path").and_then(Value::as_str).map_or(Ok(()), |p| self.check(p, Access::Read).map(drop)),
// A saved project's default output sits beside it, and rendering checks it then.
Lookup::QueueDefault => match found.get("path").and_then(Value::as_str) {
Some(_) => Ok(()),
+15 -5
View File
@@ -38,7 +38,7 @@ pub struct LongCall {
/// Whether `msg` is a blocking `renderQueue.render` call (valid arguments, headless backend).
pub fn long_call(server: &mut McpServer, msg: &Value) -> Option<LongCall> {
let id = msg.get("id").filter(|i| i.is_string() || i.is_number())?;
if msg.get("method").and_then(Value::as_str) != Some("tools/call") || server.backend().is_bridge() {
if msg.get("method").and_then(Value::as_str) != Some("tools/call") {
return None;
}
let p = msg.get("params")?;
@@ -49,6 +49,9 @@ pub fn long_call(server: &mut McpServer, msg: &Value) -> Option<LongCall> {
{
return None;
}
// A window renders on its own thread; only an in-process session (its own, or the headless one
// plain `mcp` routes to) runs the render as a long job here.
server.backend().with_session(|_| ())?;
if tools::find(name).and_then(|t| t.unknown_arg(&args)).is_some() {
return None; // the normal path reports it
}
@@ -91,7 +94,7 @@ impl McpServer {
}
};
let ids: Vec<u64> = items.iter().filter_map(|i| i["id"].as_u64()).collect();
let shared = self.backend().session().and_then(|s| s.render_job.as_ref().map(|job| job.shared.clone()));
let shared = self.backend().with_session(|s| s.render_job.as_ref().map(|job| job.shared.clone())).flatten();
let mut last = -1.0f64;
let mut last_report: Option<std::time::Instant> = None;
let mut open = true;
@@ -155,9 +158,16 @@ impl McpServer {
Err(RecvTimeoutError::Timeout) => {}
}
}
let Some(s) = self.backend().session() else { return Ok(open) };
s.poll_render();
s.drain_events();
if self
.backend()
.with_session(|s| {
s.poll_render();
s.drain_events();
})
.is_none()
{
return Ok(open);
}
let list = self.guarded("command_run", &json!({"id": "renderQueue.list"}));
let items: Vec<Value> = match &list {
Ok(Reply::Json(v)) => {
+6 -1
View File
@@ -118,7 +118,12 @@ pub fn run(b: &mut Backend, name: &str, args: &Value) -> Result<Reply> {
return Err(Error::BadArgs(format!("`{name}` is not available while file access is confined (--automation-read-root/--automation-write-root)")));
}
let empty = json!({});
(t.run)(b, if args.is_null() { &empty } else { args })
let args = if args.is_null() { &empty } else { args };
// Plain `mcp`: every call of this tool goes where its first one goes.
if let Some(inner) = b.route()? {
return (t.run)(&mut crate::backend::lock(&inner), args);
}
(t.run)(b, args)
}
// ------------------------------------------------------------------ schema fragments
+4 -1
View File
@@ -150,7 +150,10 @@ fn increment_save(s: &mut Session, _: &Value) -> Result<Value> {
fn revert(s: &mut Session, _: &Value) -> Result<Value> {
let path = s.path.clone().ok_or_else(|| bad("file.revert", "not saved"))?;
open(s, &json!({"path": path}))
s.reverting = true;
let r = open(s, &json!({"path": path}));
s.reverting = false;
r
}
/// File ▸ Import; with `addToComp` (files dropped on the Timeline or the Composition viewer) they
+4
View File
@@ -308,6 +308,9 @@ pub struct Session {
pub agent_footage: Option<FootageWrap>,
/// The footage source from before an agent's project wrapped it ([`Session::agent_footage`]).
pub unconfined_footage: Option<Arc<dyn FootageSource>>,
/// Set while `file.revert` reopens the open project from its own file (also the reload after
/// it changed on disk): an agent's project keeps the agent's footage limits then.
pub reverting: bool,
}
/// Wraps the session's footage source for a project an agent opened ([`Session::agent_footage`]).
@@ -452,6 +455,7 @@ impl Default for Session {
command_gate: None,
agent_footage: None,
unconfined_footage: None,
reverting: false,
}
}
}
+13 -7
View File
@@ -233,13 +233,19 @@ impl Session {
self.drop_crypto_probe();
self.layer_cache.clear();
// A project an agent opens reads its footage only inside the agent folders; the next one
// the person opens reads it as before.
if let Some(own) = self.unconfined_footage.take() {
self.footage = own;
}
if let Some(wrap) = self.agent_footage.clone() {
self.unconfined_footage = Some(self.footage.clone());
self.footage = wrap(self.footage.clone());
// the person opens reads it as before. Reverting the agent's project to its own file (also
// the reload after it changed on disk) keeps the agent's limits.
let agents_project_again = self.unconfined_footage.is_some() && self.reverting;
let own = self.unconfined_footage.take();
match (self.agent_footage.clone(), own) {
(Some(wrap), own) => {
let own = own.unwrap_or_else(|| self.footage.clone());
self.footage = wrap(own.clone());
self.unconfined_footage = Some(own);
}
(None, Some(own)) if agents_project_again => self.unconfined_footage = Some(own),
(None, Some(own)) => self.footage = own,
(None, None) => {}
}
self.project = Arc::new(p);
// The set of footage effects read the channels of is sent again, even when it is empty.
+17
View File
@@ -137,6 +137,13 @@ impl Agents {
}
}
/// Whether a request with `scope` may still run: agents may use EffectCraft, and the folders
/// it was given are still the agent folders. A request queued before the switch turned off,
/// or before the folders changed, doesn't run.
pub fn still_allows(&self, scope: &Arc<AgentScope>) -> bool {
self.allowed() && self.scope.as_ref().is_some_and(|current| Arc::ptr_eq(current, scope))
}
/// The next agent request to run, with what it may do. Requests whose client stopped waiting
/// are answered and skipped.
pub fn next_request(&mut self) -> Option<ControlRequest> {
@@ -169,6 +176,10 @@ mod tests {
use super::*;
use craft_control::agents::{AgentSwitch, CONNECTION_FILE};
fn scope_for_test(folders: &AgentFolders) -> Result<AgentScope, String> {
scope(folders)
}
fn scope(_: &AgentFolders) -> Result<AgentScope, String> {
let gate: effectcraft_engine::CommandGate = Arc::new(|_: &mut effectcraft_engine::Session, _: &str, _: &Value| Ok(()));
Ok(AgentScope { gate, check_write: Box::new(|_| Ok(())), folders: json!({}), footage: Arc::new(|f| f) })
@@ -195,6 +206,12 @@ mod tests {
on.sync(&host);
assert!(on.status().port.is_some(), "{:?}", on.status());
assert!(dir.path().join(CONNECTION_FILE).exists(), "the CLI finds the window through the connection file");
// A request queued with the current folders may run; one from other folders, or any
// once the switch is off, may not.
let scope = on.scope.clone().expect("the link opened the agent folders");
assert!(on.still_allows(&scope));
assert!(!on.still_allows(&Arc::new(scope_for_test(&AgentFolders::default()).unwrap())));
assert!(!off.still_allows(&scope), "a request ran with the switch off");
drop(on);
assert!(!dir.path().join(CONNECTION_FILE).exists(), "a closed window leaves no connection file");
}
+16 -1
View File
@@ -53,8 +53,23 @@ impl EffectcraftApp {
if req.is_abandoned() {
continue;
}
if ran > 0 && started.elapsed() >= self.control_budget {
// An agent's request queued before the switch turned off (or the agent folders changed)
// doesn't run.
#[cfg(not(target_arch = "wasm32"))]
if let Some(scope) = &req.agent
&& self.agents.as_ref().is_some_and(|a| !a.still_allows(scope))
{
let _ = req.reply.send(json!({"ok": false, "error": "agents may no longer use EffectCraft: the request was not run"}));
continue;
}
// Input another agent scope queued runs first, under its own gate: a request with other
// limits waits until a UI pass has applied it.
let other_scope_waits = matches!((&req.agent, &self.agent_input), (Some(scope), Some((gate, _))) if !std::sync::Arc::ptr_eq(&scope.gate, gate));
if other_scope_waits || (ran > 0 && started.elapsed() >= self.control_budget) {
self.control_backlog.push((req, deadline));
if other_scope_waits {
ctx.request_repaint();
}
continue;
}
ran += 1;
+30
View File
@@ -756,6 +756,9 @@ fn a_project_an_agent_opens_reads_footage_through_its_folders_and_the_persons_ne
assert_eq!(reply.try_recv().unwrap()["ok"], true);
assert!(Arc::ptr_eq(&app.session.footage, &confined), "the agent's project reads footage outside its folders");
assert!(app.session.agent_footage.is_none(), "the agent's footage wrapper outlived its request");
// Reverting it, as the reload after the file changed on disk does, keeps the agent's limits.
app.session.execute("file.revert", json!({})).unwrap();
assert!(Arc::ptr_eq(&app.session.footage, &confined), "reloading the agent's project dropped its footage limits");
// The person opens a project: its footage is read as before.
let reply = send(&mut app, "engine.execute", open);
hidden_tick(&mut app, &ctx, &frame);
@@ -817,6 +820,33 @@ fn agent_folders_names_the_agents_folders_and_the_persons_channel_is_unrestricte
assert_eq!(reply.try_recv().unwrap()["result"]["unrestricted"], true);
}
/// While one agent scope's input waits for a UI pass, a request with other limits waits too, so
/// the input never runs under the other scope's gate.
#[test]
fn a_request_with_other_limits_waits_for_the_input_queued_before_it() {
let ctx = headless();
let frame = eframe::Frame::_new_kittest();
let mut app = app_with_comp();
ready(&mut app, &ctx, &frame);
let (dir_a, dir_b) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
let (a, b) = (agent_scope(dir_a.path()), agent_scope(dir_b.path()));
let key = send_agent(&mut app, &a, "ui.key", json!({"key": "Escape"}));
hidden_tick(&mut app, &ctx, &frame);
let folders = send_agent(&mut app, &b, control::AGENT_FOLDERS_METHOD, json!({}));
hidden_tick(&mut app, &ctx, &frame);
assert!(folders.try_recv().is_err(), "the other scope's request ran before the input was applied");
assert!(app.session.command_gate.as_ref().is_some_and(|g| Arc::ptr_eq(g, &a.gate)), "the waiting input lost its own gate");
let mut passes = 0;
while key.try_recv().is_err() {
passes += 1;
assert!(passes < 40, "the key must be applied within a few passes");
let mut raw = raw(egui::vec2(800.0, 480.0));
pass(&mut app, &ctx, &frame, &mut raw);
}
hidden_tick(&mut app, &ctx, &frame);
assert_eq!(folders.try_recv().expect("the waiting request runs once the input was applied")["ok"], true);
}
#[test]
fn input_an_agent_queues_runs_behind_its_gate_until_a_pass_applied_it() {
let ctx = headless();
+2 -2
View File
@@ -14,8 +14,8 @@ without automation roots.
## Confining file access
`--automation-read-root DIR` and `--automation-write-root DIR` (each repeatable, as in
PhotoCraft) confine what the agent can reach: files are read only under a read or write root and
`--automation-read-root DIR` and `--automation-write-root DIR` (as in PhotoCraft; read roots are
repeatable, and several write roots need `--headless`, since plain `mcp` takes one) confine what the agent can reach: files are read only under a read or write root and
written only under a write root; with no write root nothing is written. A session without a window
is always confined, as in every Craft app: a direction without a root (or, on plain `mcp`, without
an agent folder) grants nothing, so `mcp --headless` without roots opens and saves no file. Every engine command