diff --git a/crates/mcp/src/agents.rs b/crates/mcp/src/agents.rs index d167ed9135..5a63b194a3 100644 --- a/crates/mcp/src/agents.rs +++ b/crates/mcp/src/agents.rs @@ -321,7 +321,8 @@ impl LiveBackend { Self { live: shared::Live::new(shared_cfg), config_dir, read_settings, default_folder } } - /// The folders the open window lets agents use, as the window opens them. + /// The folders the open window lets agents use, read from the saved settings: the answer for a + /// window that doesn't report the folders it enforces itself. fn window_folders(&self) -> Value { folders_answer(&(self.read_settings)(&self.config_dir).folders_with(self.default_folder.as_deref())) } @@ -330,7 +331,12 @@ impl LiveBackend { impl Backend for LiveBackend { fn call(&mut self, method: &str, params: Value) -> Result { match self.live.resolve()? { - Route::Window(_) if method == FOLDERS_METHOD => Ok(self.window_folders()), + // The window answers with the folders it enforces, which are none when a saved folder + // can't be used; a window without the method gets the saved settings. + Route::Window(w) if method == FOLDERS_METHOD => match w.lock().unwrap_or_else(PoisonError::into_inner).call(method, params) { + Err(e) if e.contains(&format!("unknown method `{FOLDERS_METHOD}`")) => Ok(self.window_folders()), + answer => answer, + }, Route::Window(w) => w.lock().unwrap_or_else(PoisonError::into_inner).call(method, params), Route::Headless(h) => h.borrow_mut().call(method, params), } diff --git a/crates/mcp/src/tests/agents.rs b/crates/mcp/src/tests/agents.rs index 3beb1838b3..20ce9b77ce 100644 --- a/crates/mcp/src/tests/agents.rs +++ b/crates/mcp/src/tests/agents.rs @@ -19,8 +19,13 @@ const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789a /// A stand-in for the window's control server holding `token`: it authenticates as the shared /// server does and answers every request with `{"window": true, "method"}`. The count is of the -/// requests it got after authentication. +/// requests it got after authentication. It doesn't know `agent.folders`, as a window from before it. fn fake_window(token: &'static str) -> (u16, Arc) { + fake_window_with_folders(token, None) +} + +/// [`fake_window`], answering `agent.folders` with `folders` when given. +fn fake_window_with_folders(token: &'static str, folders: Option) -> (u16, Arc) { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let port = listener.local_addr().unwrap().port(); let served = Arc::new(AtomicUsize::new(0)); @@ -29,6 +34,7 @@ fn fake_window(token: &'static str) -> (u16, Arc) { for stream in listener.incoming() { let Ok(stream) = stream else { return }; let count = count.clone(); + let folders = folders.clone(); std::thread::spawn(move || { let mut writer = stream.try_clone().unwrap(); let mut handshake = ServerHandshake::new(); @@ -38,7 +44,11 @@ fn fake_window(token: &'static str) -> (u16, Arc) { let reply = if signed_in { count.fetch_add(1, Ordering::SeqCst); let req: Value = serde_json::from_str(&line).unwrap(); - json!({"id": req["id"], "ok": true, "result": {"window": true, "method": req["method"]}}) + match (&folders, req["method"] == FOLDERS_METHOD) { + (Some(f), true) => json!({"id": req["id"], "ok": true, "result": f}), + (None, true) => json!({"id": req["id"], "ok": false, "error": format!("unknown method `{FOLDERS_METHOD}`")}), + _ => json!({"id": req["id"], "ok": true, "result": {"window": true, "method": req["method"]}}), + } } else { let (reply, step) = handshake.reply(&line, token); signed_in = matches!(step, AuthStep::Authenticated); @@ -102,12 +112,25 @@ fn plain_mcp_reaches_the_window_while_agents_are_allowed() { let r = b.call("document.inspect", json!({})).unwrap(); assert_eq!(r["window"], true, "{r}"); assert!(served.load(Ordering::SeqCst) >= 1); - // The window's folders are the agent folders as the window opens them: the default one here. + // A window without `agent.folders`: the saved agent folders, the default one here. let folders = b.call(FOLDERS_METHOD, json!({})).unwrap(); assert_eq!(folders["read_folder"], json!(dir.file("Agents").to_string_lossy())); assert_eq!(folders["write_folder"], folders["read_folder"]); } +// `agent_folders` shows the folders the window enforces, not the saved ones: none here, as when a +// saved folder can't be used and the window refuses every file. +#[test] +fn the_window_reports_the_folders_it_enforces() { + let dir = TempFolder::new("agents-window-enforced"); + let (port, served) = fake_window_with_folders(TOKEN, Some(json!({"read_folder": null, "write_folder": null}))); + publish(&dir, port); + let mut b = live(&dir, || true, settings_headless, dir.file("Agents")); + let folders = b.call(FOLDERS_METHOD, json!({})).unwrap(); + assert_eq!(folders, json!({"read_folder": null, "write_folder": null})); + assert!(served.load(Ordering::SeqCst) >= 1); +} + // With agents off the app doesn't listen (its link is the gate), and plain `mcp` runs headless with // only the command's folders: the closed-app choice (an error here) is for agents the person let in. #[test] diff --git a/crates/ui-egui/src/agents.rs b/crates/ui-egui/src/agents.rs index 3f6fae9bae..c713bd677b 100644 --- a/crates/ui-egui/src/agents.rs +++ b/crates/ui-egui/src/agents.rs @@ -13,9 +13,10 @@ use std::sync::Arc; use craft::automation::ControlChannel; use craft::automation::agents::{AgentLink, AgentLinkStatus, AgentSettings, AgentSwitch, LinkProblem}; +use craft::control::agents::{AgentFolders, folders_answer}; use craft::ui::runtime::windows::WindowHost; use serde_json::{Value, json}; -use vectorcraft_engine::file_access::{self, AutomationRoots}; +use vectorcraft_engine::file_access::{self, Access, AutomationRoots}; use crate::VectorcraftApp; @@ -112,6 +113,30 @@ fn roots_for(settings: &AgentSettings, default: Option<&std::path::Path>) -> Res Ok(AutomationRoots::new(&read, &write)?.unwrap_or_else(AutomationRoots::none)) } +/// `agent.folders`: the folders the request's own automation roots let it open and save in, as the +/// `agent_folders` tool shows them, with `read_folders` / `write_folders` listing every folder of a +/// kind that has several (`--automation-read-root` given twice). Roots that grant nothing (a saved +/// folder the window can't use) list no folder; a request that isn't confined says so. +pub(crate) fn folders(roots: Option<&AutomationRoots>) -> Value { + let Some(roots) = roots else { + return json!({"read_folder": null, "write_folder": null, "unrestricted": true}); + }; + let (read, write): (Vec<&std::path::Path>, Vec<&std::path::Path>) = + (roots.folders(Access::Read).collect(), roots.folders(Access::Write).collect()); + let mut folders = AgentFolders::default(); + folders.read = read.first().map(|p| p.to_path_buf()); + folders.write = write.first().map(|p| p.to_path_buf()); + let mut answer = folders_answer(&folders); + for (key, all) in [("read_folders", &read), ("write_folders", &write)] { + if all.len() > 1 + && let Some(o) = answer.as_object_mut() + { + o.insert(key.into(), json!(all.iter().map(|p| p.to_string_lossy()).collect::>())); + } + } + answer +} + /// Once per pass: brings the link in line with the launcher's switch and the saved settings. The /// control server starts, moves or stops; while it runs, its requests are the app's control channel /// and run inside the agent folders ([`VectorcraftApp::run_control`]). diff --git a/crates/ui-egui/src/agents/tests.rs b/crates/ui-egui/src/agents/tests.rs index 4e66e6ae8a..3a2a42c51f 100644 --- a/crates/ui-egui/src/agents/tests.rs +++ b/crates/ui-egui/src/agents/tests.rs @@ -54,8 +54,10 @@ fn app_with_agents(base: &Path, switch: AgentSwitch) -> (VectorcraftApp, Arc, method: &str, params: Value) -> Result { + use std::sync::mpsc::TryRecvError; let ctx = app.ui_ctx.clone().unwrap_or_default(); let mut c = client.take().expect("a connected client"); let sent = method.to_owned(); @@ -64,15 +66,18 @@ fn agent_request(app: &mut VectorcraftApp, client: &mut Option, m let r = c.call(&sent, params); let _ = done.send((c, r)); }); - for _ in 0..2000 { + loop { app.run_control(&ctx); app.poll_input(&ctx); - if let Ok((c, r)) = reply.recv_timeout(std::time::Duration::from_millis(5)) { - *client = Some(c); - return r; + match reply.try_recv() { + Ok((c, r)) => { + *client = Some(c); + return r; + } + Err(TryRecvError::Empty) => std::thread::yield_now(), + Err(TryRecvError::Disconnected) => panic!("the client thread for {method:?} stopped without a reply"), } } - panic!("the app did not answer {method:?}") } // With the launcher's switch naming VectorCraft, the window serves agents on loopback and publishes @@ -114,6 +119,28 @@ fn with_the_switch_off_nothing_listens() { let _ = std::fs::remove_dir_all(&base); } +#[test] +fn agent_folders_reaches_the_window_with_unusable_saved_roots() { + let base = folders("agent-folders-window"); + let (mut app, _) = app_with_agents(&base, AgentSwitch::fixed(true, true)); + app.run("prefs.agents", json!({"readRoot": s(base.join("in/a.svg"))})).unwrap(); + let ctx = app.ui_ctx.clone().unwrap_or_default(); + super::sync(&mut app, &ctx); + let connection = read_connection(&base.join("settings")).unwrap().expect("the connection file is published"); + let token = std::fs::read_to_string(&connection.token_file).unwrap(); + let mut client = Some(ControlClient::connect(([127, 0, 0, 1], connection.port).into(), token.trim()).unwrap()); + + for params in [json!({}), Value::Null] { + let answer = agent_request(&mut app, &mut client, "agent.folders", params).unwrap(); + assert_eq!(answer.get("read_folder"), Some(&Value::Null), "{answer}"); + assert_eq!(answer.get("write_folder"), Some(&Value::Null), "{answer}"); + assert_ne!(answer.get("unrestricted"), Some(&Value::Bool(true)), "{answer}"); + } + let unexpected = agent_request(&mut app, &mut client, "agent.folders", json!({"unexpected": true})); + assert!(unexpected.as_ref().is_err_and(|e| e.contains("takes no parameters")), "{unexpected:?}"); + let _ = std::fs::remove_dir_all(&base); +} + // `prefs.agents` saves the person's settings, refuses unknown keys, and refuses every change from a // confined request: agents can't widen their own folders. #[test] @@ -134,6 +161,26 @@ fn prefs_agents_saves_and_agents_cannot_change_it() { let _ = std::fs::remove_dir_all(&base); } +// `agent.folders` answers with the roots the request runs inside: roots that grant nothing (a saved +// folder the window can't use) list no folder. +#[test] +fn agent_folders_reports_the_roots_a_request_runs_inside() { + let base = folders("agent-folders"); + let roots = AutomationRoots::new(&[&base.join("in")], &[&base.join("out")]).unwrap().unwrap(); + let answer = super::folders(Some(&roots)); + assert!(answer["read_folder"].as_str().is_some_and(|f| f.ends_with("in")), "{answer}"); + assert!(answer["write_folder"].as_str().is_some_and(|f| f.ends_with("out")), "{answer}"); + assert!(answer.get("read_folders").is_none(), "{answer}"); + let two = AutomationRoots::new(&[&base.join("in"), &base.join("outside")], &[&base.join("out")]).unwrap().unwrap(); + let answer = super::folders(Some(&two)); + assert_eq!(answer["read_folders"].as_array().map(Vec::len), Some(2), "{answer}"); + assert!(answer.get("write_folders").is_none(), "{answer}"); + let none = super::folders(Some(&AutomationRoots::none())); + assert_eq!((&none["read_folder"], &none["write_folder"]), (&Value::Null, &Value::Null), "{none}"); + assert_eq!(super::folders(None)["unrestricted"], true); + let _ = std::fs::remove_dir_all(&base); +} + // A control client started without automation roots runs unconfined, and it still can't change the // agent settings: only the person sets them. #[test] diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 5e084671fc..18689f9985 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -1230,7 +1230,10 @@ pub fn handle(app: &mut VectorcraftApp, ctx: &egui::Context, req: &ControlReques } other => return other, }; - hide_in_reply(app, &mut reply, &req.params, before); + // `agent.folders` names the request's own roots, which it may use whole. + if method != "agent.folders" { + hide_in_reply(app, &mut reply, &req.params, before); + } Reply::Done(reply) } @@ -1479,6 +1482,14 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val } "engine.commands" => ok(all_commands(app)), "document.inspect" => wrap(app.run("document.inspect", p.clone())), + // Each request runs confined to the window's automation roots ([`VectorcraftApp::run_control`]). + #[cfg(not(target_arch = "wasm32"))] + "agent.folders" => { + if !p.is_null() && !p.as_object().is_some_and(|fields| fields.is_empty()) { + return err("`agent.folders` takes no parameters"); + } + ok(crate::agents::folders(vectorcraft_engine::file_access::current().as_deref())) + } "ui.inspect" => ok(inspect(app, ctx)), "ui.docking" => ok(crate::panel_docking::inspect(app, ctx)), // A request that stops with a panic quoting the status text, after clearing the Color Guide's diff --git a/docs/mcp.md b/docs/mcp.md index 5fc5a75897..289695fc2e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -890,7 +890,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `create_graph` | `{type?, x, y, width, height, csv? \| series?, categories?, rows?}` | The nine Illustrator graph types: column, stacked column, bar, stacked bar, line, area, scatter, pie and radar. An empty CSV cell or a `null` in `rows` is a blank value; a number in straight quotes is a label. Edit later with `graph.setData` / `graph.setType` via `run_command`. `graph.column {design, columnType: vertical\|uniform\|repeating\|sliding, each, fractions: chop\|scale}` draws the columns or bars of the series picked with Group Selection (or `seriesIndexes`, or all of them) with a graph design saved by `graph.design`; with no `design` it returns the series' current design and options. Type in the design that holds a `%` followed by two digits shows each column's value, with at least the first digit's places before the decimal point and the second digit's places after it. | | `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. A type object in `ids` with another of them above it in its layer is the text to wrap, not a wrap object, so the objects and the type can be selected together. The reply has a `warning` when no area type lies below any of the wrap objects. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. | | `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy`, `path.moveAnchors` by 0, `layer.setProps` with every row already as given and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. Any other command that changes the document during a tool's drag, from `run_command`, a panel or a menu, records its own undo step before the drag's. The command acts on the document without the drag's preview, and the drag then continues from the command's result: with Real-time Drawing on, the drag's preview is applied again at once, and with it off, the release applies it as before. The release records the drag's step after the command's, `undo` takes back the drag first and the command next, and Escape cancels only the drag. The drag acts on the objects it started with, so a selection the command makes (`select.all`, `edit.duplicate`) does not change what the drag moves, and the drag's release and Escape set the selection as they do without the command (with Real-time Drawing on, so does each move of the drag); a command that records no undo step, such as `select.none`, adds no step. When the command deletes or changes the art being dragged, the drag continues with the art the command left, and a drag left with nothing to change records no step. A warning or an error from the drag's preview applied again after the command is in the command's result as `previewWarning`. Typing in progress is kept as a step of its own before the command. Two cases run the command inside the drag, which then keeps the command's edit as part of its own step: a press of the Quick Pen (an edit to its path ends the path), and `object.transform` with `copy` during an Alt-drag, which copies the art as the drag's move left it. A command run while a dialog's or a panel's preview is open runs inside that preview, except during an add-on dialog's preview (Object › Plug-ins, other than Edit Points Only): there a command that changes the document records its own undo step, acts on the document without the preview using the shown selection restricted to objects present in that document, and stays after the dialog's Cancel or OK. A shown selection containing only preview objects becomes empty for the command. A path whose selected anchors or segments the preview renumbered (Set Corners recut it) is left out of that selection, so Clear does not delete its points. A command that is refused leaves the dialog's selection as it was. The dialog previews again from the command's result and selection, including after a failed preview when only the selection changed. An outside selection command's selection and paint defaults stay together after Cancel or OK. `edit.copy` and the `file.*` commands other than `file.documentColorMode` still run on the document as the preview shows it. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | -| `agent_folders` | `{}` | Where VectorCraft opens and saves files for this session: `{read_folder, write_folder}`, each a path or `null`. In the open window, the agent folders of Preferences › AI Integrations (`Documents/ArtCraft/Agents/VectorCraft` for an empty one); in a headless session started for agents, the folders it was confined to (`read_folders` / `write_folders` list them all when a kind has several); a session started without automation roots answers `unrestricted: true`. An app reached with the deprecated `--connect` answers an error: its own `--automation-*-root` flags, if any, confine it. | +| `agent_folders` | `{}` | Where VectorCraft opens and saves files for this session: `{read_folder, write_folder}`, each a path or `null`. In the open window, the agent folders the window enforces: those of Preferences › AI Integrations (`Documents/ArtCraft/Agents/VectorCraft` for an empty one), or `null` for both when a saved folder can't be used (a deleted folder, a file) and the window refuses every file (a window from before `agent.folders` was added answers with the saved folders, even one it can't use); in a headless session started for agents, the folders it was confined to (`read_folders` / `write_folders` list them all when a kind has several); a session started without automation roots answers `unrestricted: true`. An app reached with the deprecated `--connect` answers an error: its own `--automation-*-root` flags, if any, confine it. | For example, create editable Japanese area type with the engine's vertical writing mode: