fix(automation): review findings on agents in the open window

- The command's --automation-read-root/--automation-write-root also bind
  calls that reach the window (checked in the CLI, on top of the window's
  agent folders).
- An agent request keeps the agents channel's reply deadline: one still
  waiting in the backlog after it is not run.
- The person's --control requests run without a pending agent's gate.
- An agent's `null` params read as `{}`, other non-objects are refused, so
  a screenshot or frame can't skip the inline branch.
- The handshake reply is read up to 64 KiB.
- --when-closed launch/error without a settings folder is an error, not a
  silent headless session.
- Docs: the closed-app choice, not "headless", when EffectCraft is closed;
  the window's footage exception (#4387); the command's folders.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
David MannandClaude Opus 5.5 committed 2026-12-03 01:46:57 +01:00
1 parent b27167e441
commit bb9cc35e18
13 files changed
+157 -32

No files matched your search

+1 -1
View File
@@ -177,7 +177,7 @@ but not UI-only commands or bridge-only `ui_*` tools.
- **MCP server:** `effectcraft-cli mcp` speaks the Model Context Protocol over stdio. It drives
the open window while the ArtCraft Launcher's Settings › AI agents switch lets agents use
EffectCraft, and runs headless otherwise ([docs/agents.md](docs/agents.md#agents-in-the-open-window)). Tools cover commands, the project and property
EffectCraft, runs headless while it doesn't, and follows the closed-app choice while EffectCraft is closed ([docs/agents.md](docs/agents.md#agents-in-the-open-window)). Tools cover commands, the project and property
tree, keyframes and rendered frames. This repository ships a ready [`.mcp.json`](.mcp.json).
- **Command line:** one-shot calls with JSON output, for example
`effectcraft-cli set Main '#1' transform/position '[100,360]' --time 0 main.ecproj --save`
+6 -1
View File
@@ -904,6 +904,11 @@ fn mcp_backend(args: &Args) -> Result<Backend, Failure> {
return usage_err("--when-closed is for a session that may use the open window: --headless, --autosave and the project options always run without it");
}
let config_dir = effectcraft_host::config_dir();
if config_dir.is_none() && when_closed.is_some_and(|w| w != craft_control::agents::WhenAppClosed::Headless) {
return Err(Failure::Error(
"--when-closed launch and error need EffectCraft's settings folder to find the open window, and there is none: set EFFECTCRAFT_CONFIG_DIR, or use --when-closed headless".into(),
));
}
let (true, Some(config_dir)) = (args.opt("--bridge").is_none() && !headless, config_dir) else {
let mut b = backend(args, false)?;
if !read.is_empty() || !write.is_empty() {
@@ -922,7 +927,7 @@ fn mcp_backend(args: &Args) -> Result<Backend, Failure> {
cfg.read_roots = read;
cfg.write_root = write.into_iter().next();
cfg.launch = std::env::current_exe().ok().and_then(|cli| craft_control::agents::launcher(&cli, agents::APP_EXE));
Ok(agents::live(cfg))
Ok(agents::live(cfg)?)
}
fn positional<const N: usize>(args: &Args, usage: &str) -> Result<[String; N], Failure> {
+12 -4
View File
@@ -154,14 +154,22 @@ pub(crate) type Live = shared::Live<Arc<Mutex<Backend>>, Arc<Mutex<Backend>>>;
/// Plain `effectcraft-cli mcp`: every call goes to the open window while the person lets agents
/// use it, otherwise to a headless session; a closed app follows the closed-app choice. The lookup
/// is the shared `craft_control::agents::Live`; a session that went headless stays headless.
pub fn live(cfg: LiveConfig) -> Backend {
pub fn live(cfg: LiveConfig) -> Result<Backend> {
let LiveConfig { config_dir, when_closed, read_roots, write_root, launch, launch_timeout, allowed, default_folder, headless } = cfg;
let consent = move |dir: &Path| Consent::new(allowed(), read_settings(dir));
let connect = |w: &shared::Window| -> std::result::Result<Arc<Mutex<Backend>>, String> {
// The command's folders bind the window too: its calls must pass them here and the window's
// agent folders there, so an agent reaches only what both allow.
let own_roots =
(!read_roots.is_empty() || write_root.is_some()).then(|| Confinement::new(&read_roots, &write_root.iter().cloned().collect::<Vec<_>>())).transpose()?;
let connect = move |w: &shared::Window| -> std::result::Result<Arc<Mutex<Backend>>, String> {
let mut client = BridgeClient::agents(w.port, w.token.clone());
// Signs in now, so a listener that can't prove it holds the token is never used.
client.sign_in_now().map_err(|e| e.to_string())?;
Ok(Arc::new(Mutex::new(Backend::window(client))))
let mut window = Backend::window(client);
if let Some(roots) = &own_roots {
window.confine(roots.clone());
}
Ok(Arc::new(Mutex::new(window)))
};
let settings_dir = config_dir.clone();
let make_headless = move |folders: &HeadlessFolders| -> std::result::Result<Arc<Mutex<Backend>>, String> {
@@ -186,7 +194,7 @@ pub fn live(cfg: LiveConfig) -> Backend {
shared_cfg.launch = launch;
shared_cfg.launch_timeout = launch_timeout;
shared_cfg.default_folder = default_folder;
Backend::live(shared::Live::new(shared_cfg))
Ok(Backend::live(shared::Live::new(shared_cfg)))
}
/// The error a live call reports when no window and no session can serve it.
+50 -7
View File
@@ -83,7 +83,7 @@ fn not_allowed() -> bool {
#[test]
fn without_the_switch_the_session_runs_headless_with_the_commands_folders() {
let dir = temp("off");
let mut b = live(config(&dir, not_allowed));
let mut b = live(config(&dir, not_allowed)).unwrap();
b.exec("comp.new", json!({"name": "Here"})).unwrap();
assert_eq!(b.exec("comp.info", json!({})).unwrap()["name"], "Here", "the comp is in this process's session");
// Not confined without roots, and it says so instead of naming no folder.
@@ -93,7 +93,7 @@ fn without_the_switch_the_session_runs_headless_with_the_commands_folders() {
let mut cfg = config(&dir, not_allowed);
cfg.read_roots = vec![roots.clone()];
cfg.write_root = Some(roots.clone());
let mut b = live(cfg);
let mut b = live(cfg).unwrap();
let folders = b.agent_folders().unwrap();
assert_eq!(folders["write_folder"].as_str().map(PathBuf::from), Some(roots.canonicalize().unwrap()), "{folders}");
assert!(!dir.join("Agents").exists(), "the default agent folder was made for a session that doesn't use it");
@@ -105,13 +105,13 @@ fn with_the_switch_on_calls_reach_the_open_window() {
let token = generate_token().unwrap();
let (port, seen) = fake_window(token.clone());
publish(&dir, port, &token);
let mut b = live(config(&dir, allowed));
let mut b = live(config(&dir, allowed)).unwrap();
let r = b.exec("project.summary", json!({})).unwrap();
assert_eq!(r["from"], "window", "{r}");
assert_eq!(b.agent_folders().unwrap()["method"], crate::agents::FOLDERS_METHOD, "the window answers agent_folders");
assert_eq!(*seen.lock().unwrap(), ["engine.execute", crate::agents::FOLDERS_METHOD]);
// Every tool is listed, the window's included.
let mut server = McpServer::new(live(config(&dir, allowed)));
let mut server = McpServer::new(live(config(&dir, allowed)).unwrap());
let line = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"}).to_string();
let tools: Value = serde_json::from_str(&server.handle_line(&line).unwrap()).unwrap();
let names: Vec<&str> = tools["result"]["tools"].as_array().unwrap().iter().filter_map(|t| t["name"].as_str()).collect();
@@ -124,7 +124,7 @@ fn a_listener_that_cannot_prove_it_holds_the_token_gets_nothing() {
let (port, seen) = fake_window(generate_token().unwrap());
// The token file names another token than the listener holds (a program on a stale port).
publish(&dir, port, &generate_token().unwrap());
let mut b = live(config(&dir, allowed));
let mut b = live(config(&dir, allowed)).unwrap();
let e = b.exec("project.summary", json!({})).unwrap_err().to_string();
assert!(e.contains("could not prove"), "{e}");
assert!(seen.lock().unwrap().is_empty(), "a request reached a listener without the token: {:?}", seen.lock().unwrap());
@@ -138,12 +138,12 @@ fn a_closed_app_follows_the_closed_app_choice() {
publish(&dir, port, &generate_token().unwrap());
let mut cfg = config(&dir, allowed);
cfg.when_closed = Some(WhenAppClosed::Error);
let e = live(cfg).exec("project.summary", json!({})).unwrap_err().to_string();
let e = live(cfg).unwrap().exec("project.summary", json!({})).unwrap_err().to_string();
assert!(e.contains("isn't running"), "{e}");
// Headless: the agent folder, created when used; nothing outside it is written.
let mut cfg = config(&dir, allowed);
cfg.when_closed = Some(WhenAppClosed::Headless);
let mut b = live(cfg);
let mut b = live(cfg).unwrap();
let folders = b.agent_folders().unwrap();
let agent = dir.join("Agents").join("EffectCraft").canonicalize().unwrap();
assert_eq!(folders["write_folder"].as_str().map(PathBuf::from), Some(agent.clone()), "{folders}");
@@ -157,3 +157,46 @@ fn a_closed_app_follows_the_closed_app_choice() {
let e = b.control("ui.inspect", json!({})).unwrap_err().to_string();
assert!(e.contains("needs the open EffectCraft window"), "{e}");
}
#[test]
fn the_commands_folders_bind_calls_to_the_window_too() {
let dir = temp("roots");
let token = generate_token().unwrap();
let (port, seen) = fake_window(token.clone());
publish(&dir, port, &token);
let roots = temp("roots-own");
let mut cfg = config(&dir, allowed);
cfg.read_roots = vec![roots.clone()];
cfg.write_root = Some(roots.clone());
let mut b = live(cfg).unwrap();
let outside = temp("roots-outside").join("out.ecproj");
let e = b.exec("file.saveAs", json!({"path": outside.to_string_lossy()})).unwrap_err().to_string();
assert!(e.contains("outside the automation roots"), "{e}");
assert!(seen.lock().unwrap().is_empty(), "the save outside the command's folders reached the window");
let inside = roots.canonicalize().unwrap().join("in.ecproj");
assert_eq!(b.exec("file.saveAs", json!({"path": inside.to_string_lossy()})).unwrap()["from"], "window");
}
#[test]
fn a_handshake_reply_without_an_end_is_not_read_forever() {
let dir = temp("endless");
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
// Every connection (the lookup probes the port first) gets far more than any handshake reply,
// and never a line end.
std::thread::spawn(move || {
for mut stream in listener.incoming().flatten() {
std::thread::spawn(move || {
let chunk = vec![b'x'; 16 * 1024];
for _ in 0..64 {
if stream.write_all(&chunk).is_err() {
return;
}
}
});
}
});
publish(&dir, port, &generate_token().unwrap());
let e = live(config(&dir, allowed)).unwrap().exec("project.summary", json!({})).unwrap_err().to_string();
assert!(e.contains("longer than"), "{e}");
}
+8 -2
View File
@@ -6,7 +6,7 @@
//! its own proof, so the token never crosses the wire and a program that took a stale port learns
//! nothing derived from it.
use std::io::{BufRead, BufReader, Write};
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::time::Duration;
@@ -14,6 +14,9 @@ use serde_json::{Value, json};
use crate::{Error, Result};
/// The longest handshake reply read: the challenge's two hex nonces and proofs are a few hundred
/// bytes, and a listener that can't prove it holds the token gets no more than this read.
const HANDSHAKE_REPLY_LIMIT: u64 = 64 * 1024;
/// Slightly longer than the app's own 60 s per-request timeout, so its error reply wins.
const READ_TIMEOUT: Duration = Duration::from_secs(65);
/// The desktop control protocol's request-line limit, excluding the newline.
@@ -180,11 +183,14 @@ fn round_trip(conn: &mut (BufReader<TcpStream>, TcpStream), method: &str, params
);
w.write_all(line.as_bytes()).and_then(|()| w.flush()).map_err(|e| Error::Bridge(e.to_string()))?;
let mut buf = String::new();
match r.read_line(&mut buf) {
match r.by_ref().take(HANDSHAKE_REPLY_LIMIT).read_line(&mut buf) {
Ok(0) => return Err(Error::Bridge("connection closed by the app".into())),
Ok(_) => {}
Err(e) => return Err(Error::Bridge(e.to_string())),
}
if !buf.ends_with('\n') {
return Err(Error::Bridge(format!("the handshake reply is longer than {HANDSHAKE_REPLY_LIMIT} bytes; the agent token was not used")));
}
let v: Value = serde_json::from_str(&buf).map_err(|e| Error::Bridge(format!("bad reply: {e}")))?;
Ok(if v.get("ok").and_then(Value::as_bool) == Some(true) {
Ok(v.get("result").cloned().unwrap_or(Value::Null))
+8 -1
View File
@@ -251,7 +251,14 @@ fn play(session: effectcraft_engine::Session, cid: ItemId, secs: f64, gpu: bool)
}
h.state().frames.clear();
let (reply, _r) = std::sync::mpsc::channel();
let _ = tx.send(ControlRequest { method: "ui.playback".into(), params: json!({"action": "play"}), reply, abandoned: Default::default(), agent: None });
let _ = tx.send(ControlRequest {
method: "ui.playback".into(),
params: json!({"action": "play"}),
reply,
abandoned: Default::default(),
agent: None,
deadline: None,
});
let t0 = Instant::now();
let (mut started, mut stalled, mut last, mut scales) = (None, 0.0, t0, std::collections::BTreeMap::<u32, u64>::new());
// When each new frame went on screen (seconds since play was pressed): the cadence. The
+1 -1
View File
@@ -135,7 +135,7 @@ fn main() {
continue;
}
let (reply_tx, reply_rx) = mpsc::channel();
let _ = tx.send(ControlRequest { method: method.clone(), params, reply: reply_tx, abandoned: Default::default(), agent: None });
let _ = tx.send(ControlRequest { method: method.clone(), params, reply: reply_tx, abandoned: Default::default(), agent: None, deadline: None });
// Requests are answered on a later frame (some wait for input to be processed).
let deadline = Instant::now() + Duration::from_secs(10);
let reply = loop {
+1 -1
View File
@@ -142,7 +142,7 @@ impl Agents {
pub fn next_request(&mut self) -> Option<ControlRequest> {
let scope = self.scope.clone()?;
let request = self.channel.as_mut()?.next_request()?;
Some(ControlRequest::for_agent(request.method, request.params, request.reply, scope))
Some(ControlRequest::for_agent(request.method, request.params, request.reply, scope, request.deadline))
}
/// `agents.settings`: without params, the settings and where the link stands; with params,
+2 -4
View File
@@ -65,10 +65,8 @@ impl EffectcraftApp {
// pass has applied it (`agent_input`).
let queued = self.synthetic.len();
let gate = req.agent.as_ref().map(|scope| scope.gate.clone());
let outer = match &gate {
Some(gate) => self.session.command_gate.replace(gate.clone()),
None => self.session.command_gate.clone(),
};
// The person's own channel (`--control`) isn't confined, even while an agent's input waits.
let outer = std::mem::replace(&mut self.session.command_gate, gate.clone());
let outcome = control::handle(self, ctx, &req, now);
self.session.command_gate = outer;
if gate.is_some() && self.synthetic.len() > queued {
+15 -5
View File
@@ -45,6 +45,9 @@ pub struct ControlRequest {
/// An agent's request through the ArtCraft Launcher's switch (`crate::agents`): what it may
/// do. `None` for the person's own channel (`--control`).
pub agent: Option<Arc<AgentScope>>,
/// When the sender stops waiting (the agents channel's reply deadline): a request not begun by
/// then is not run, as with [`ControlRequest::abandoned`].
pub deadline: Option<web_time::Instant>,
}
/// The control method `effectcraft-cli mcp`'s `agent_folders` tool calls.
@@ -75,17 +78,18 @@ impl ControlRequest {
/// receive the UI thread's reply.
pub fn new(method: impl Into<String>, params: Value) -> (Self, std::sync::mpsc::Receiver<Value>) {
let (tx, rx) = std::sync::mpsc::channel();
(Self { method: method.into(), params, reply: tx, abandoned: Default::default(), agent: None }, rx)
(Self { method: method.into(), params, reply: tx, abandoned: Default::default(), agent: None, deadline: None }, rx)
}
/// An agent's request answered on `reply`, which may do what `scope` allows.
pub fn for_agent(method: String, params: Value, reply: Sender<Value>, scope: Arc<AgentScope>) -> Self {
Self { method, params, reply, abandoned: Default::default(), agent: Some(scope) }
/// An agent's request answered on `reply`, which may do what `scope` allows; its sender stops
/// waiting at `deadline`.
pub fn for_agent(method: String, params: Value, reply: Sender<Value>, scope: Arc<AgentScope>, deadline: Option<web_time::Instant>) -> Self {
Self { method, params, reply, abandoned: Default::default(), agent: Some(scope), deadline }
}
/// Whether the sender stopped waiting for the reply ([`ControlRequest::abandoned`]).
pub fn is_abandoned(&self) -> bool {
self.abandoned.load(std::sync::atomic::Ordering::SeqCst)
self.abandoned.load(std::sync::atomic::Ordering::SeqCst) || self.deadline.is_some_and(|d| craft_ui::runtime::motion::now() >= d)
}
}
@@ -276,6 +280,12 @@ pub fn handle(app: &mut EffectcraftApp, ctx: &egui::Context, req: &ControlReques
return ok(req.agent.as_ref().map_or_else(unrestricted_folders, |scope| scope.folders.clone()));
}
if let Some(scope) = &req.agent {
let empty = json!({});
let p = match p {
Value::Null => &empty,
Value::Object(_) => p,
_ => return err("params must be an object"),
};
match agent_paths(&req.method, p, scope) {
Ok(Some(p)) => return handle_method(app, ctx, &req.method, &p, now),
Ok(None) => {}
+45 -1
View File
@@ -730,7 +730,7 @@ fn send_agent(
) -> std::sync::mpsc::Receiver<serde_json::Value> {
let (reply_tx, reply) = std::sync::mpsc::channel();
let (tx, rx) = std::sync::mpsc::channel();
tx.send(ControlRequest::for_agent(method.into(), params, reply_tx, scope.clone())).unwrap();
tx.send(ControlRequest::for_agent(method.into(), params, reply_tx, scope.clone(), None)).unwrap();
app.control_rx = Some(rx);
reply
}
@@ -819,3 +819,47 @@ fn agents_cannot_change_the_agent_settings() {
let e = crate::menus::invoke(&mut app, &ctx, crate::agents::SETTINGS_COMMAND, json!({"writeRoot": "/"})).unwrap_err();
assert!(e.contains("Agents can't change the agent settings"), "{e}");
}
#[test]
fn an_agents_request_past_its_deadline_or_with_odd_params_does_not_run() {
let ctx = headless();
let frame = eframe::Frame::_new_kittest();
let mut app = app_with_comp();
let agent_dir = tempfile::tempdir().unwrap();
let scope = agent_scope(agent_dir.path());
// The agents channel stopped waiting: the request is skipped, not run late.
let (reply_tx, reply) = std::sync::mpsc::channel();
let past = craft_ui::runtime::motion::now().checked_sub(std::time::Duration::from_secs(1));
let request = ControlRequest::for_agent("engine.execute".into(), json!({"command": "comp.new", "params": {"name": "Late"}}), reply_tx, scope.clone(), past);
let (tx, rx) = std::sync::mpsc::channel();
tx.send(request).unwrap();
app.control_rx = Some(rx);
hidden_tick(&mut app, &ctx, &frame);
assert!(reply.try_recv().is_err() && !has_comp(&app, "Late"), "a request nobody waits for ran");
// `null` params are `{}`: a frame comes back inline; other non-objects are refused.
let reply = send_agent(&mut app, &scope, "render.frame", serde_json::Value::Null);
hidden_tick(&mut app, &ctx, &frame);
let value = reply.try_recv().unwrap();
assert!(value["result"]["png"].is_string() && value["result"].get("path").is_none(), "{value}");
let reply = send_agent(&mut app, &scope, "render.frame", json!([]));
hidden_tick(&mut app, &ctx, &frame);
assert_eq!(reply.try_recv().unwrap()["ok"], false);
}
#[test]
fn the_persons_channel_is_not_confined_while_an_agents_input_waits() {
let ctx = headless();
let frame = eframe::Frame::_new_kittest();
let mut app = app_with_comp();
ready(&mut app, &ctx, &frame);
let (agent_dir, other) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
let _ = send_agent(&mut app, &agent_scope(agent_dir.path()), "ui.key", json!({"key": "Escape"}));
hidden_tick(&mut app, &ctx, &frame);
assert!(app.session.command_gate.is_some(), "the agent's input is pending");
let outside = other.path().join("person.ecproj");
let reply = send(&mut app, "engine.execute", json!({"command": "file.saveAs", "params": {"path": outside.to_string_lossy()}}));
hidden_tick(&mut app, &ctx, &frame);
assert_eq!(reply.try_recv().unwrap()["ok"], true);
assert!(outside.exists());
assert!(app.session.command_gate.is_some(), "the agent's pending input keeps its gate");
}
+6 -3
View File
@@ -35,8 +35,8 @@ switch names EffectCraft (behind the suite's `AI-MCP` flag):
- **Plain `effectcraft-cli mcp` finds it** on every tool call, so the client's configuration holds no
port and no token, and EffectCraft may start, quit or change port while the client stays
connected. The CLI checks that the window holds the token before it sends anything (challenge
handshake). Without a window the session runs headless; a session that went headless stays
headless.
handshake). While agents aren't let in, the session runs headless. While they are and EffectCraft
is closed, the closed-app choice below decides. A session that went headless stays headless.
- **When EffectCraft is closed**, Settings › AI Agents decides:
- start EffectCraft and wait (the default);
- use a session without a window, with the agent folders;
@@ -46,7 +46,8 @@ switch names EffectCraft (behind the suite's `AI-MCP` flag):
never uses the window. So do `--autosave` and the project options (`--project`, `--demo`,
`--empty`).
- **Agent folders.** Agent requests open files only from the agent folders and save only into
them, in the window too: the Automation Read and Write Folders on the Agents page, or
them, in the window too (one exception: in the window, footage that a project opened from the agent
folder already names is read wherever it is; #4387): the Automation Read and Write Folders on the Agents page, or
`Documents/ArtCraft/Agents/EffectCraft` (created when first used) when they are empty. The checks
are the same as for `--automation-read-root` / `--automation-write-root` (see
[MCP conventions](mcp.md#confining-file-access)). They cover each command an agent runs, and the
@@ -54,6 +55,8 @@ switch names EffectCraft (behind the suite's `AI-MCP` flag):
without a file comes back inline. A folder that can't be used means no file access, never
unrestricted access, and the Agents page says why. The `agent_folders` tool names the folders the
session really uses. Agents can't change the agent settings; only the person can.
`--automation-read-root` / `--automation-write-root` on plain `mcp` bind calls to the window too:
they must pass both those and the window's agent folders.
- **Settings › AI Agents** (shown with the `AI-MCP` flag) has the launcher's state, the port agents
connect on, Control Port, the two folders and the closed-app choice. These settings are saved as
you change them, in `agents.json` in the settings folder, where `effectcraft-cli mcp` reads them.
+2 -1
View File
@@ -1,7 +1,8 @@
# MCP conventions
Run `effectcraft-cli mcp`: it reaches the open EffectCraft window while the ArtCraft Launcher's
Settings › AI agents switch lets agents use EffectCraft, and runs headless otherwise
Settings › AI agents switch lets agents use EffectCraft, runs headless while it doesn't, and
follows the closed-app choice while it does and EffectCraft is closed
([agents.md](agents.md#agents-in-the-open-window)). `--headless` always runs headless, and
`--when-closed launch|headless|error` chooses what happens while EffectCraft is closed.
`effectcraft-cli mcp --bridge 9877` (deprecated) still drives a desktop app started with