diff --git a/Cargo.lock b/Cargo.lock index 4b55c4b92..a7a186c91 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -960,6 +960,16 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-ai-agents" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-ai-integrations?rev=d94a3593adcff504eaaad9e5aee4c84fd2f07a72#d94a3593adcff504eaaad9e5aee4c84fd2f07a72" +dependencies = [ + "dirs", + "serde", + "serde_json", +] + [[package]] name = "craft-appkit" version = "0.1.0" @@ -978,6 +988,31 @@ dependencies = [ "rustix 1.1.6", ] +[[package]] +name = "craft-automation" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=d7010805175ba1190d521b2565852bdda39e632c#d7010805175ba1190d521b2565852bdda39e632c" +dependencies = [ + "base64 0.23.1", + "craft-behavior", + "craft-control", + "craft-host", + "craft-keymap", + "craft-platform", + "craft-theme", + "craft-ui", + "egui", + "getrandom 0.3.4", + "hmac", + "log", + "png 0.17.16", + "serde", + "serde_json", + "sha2", + "thiserror 2.0.21", + "web-time", +] + [[package]] name = "craft-behavior" version = "0.1.0" @@ -1009,6 +1044,21 @@ name = "craft-codepage" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=d7010805175ba1190d521b2565852bdda39e632c#d7010805175ba1190d521b2565852bdda39e632c" +[[package]] +name = "craft-control" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=d7010805175ba1190d521b2565852bdda39e632c#d7010805175ba1190d521b2565852bdda39e632c" +dependencies = [ + "craft-ai-agents", + "craft-atomic", + "craft-flags", + "dirs", + "getrandom 0.3.4", + "log", + "serde", + "serde_json", +] + [[package]] name = "craft-dds" version = "0.1.0" @@ -1045,6 +1095,16 @@ dependencies = [ "serde", ] +[[package]] +name = "craft-flags" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=d7010805175ba1190d521b2565852bdda39e632c#d7010805175ba1190d521b2565852bdda39e632c" +dependencies = [ + "craft-atomic", + "dirs", + "toml_edit", +] + [[package]] name = "craft-font-catalog" version = "0.1.0" @@ -1122,7 +1182,7 @@ dependencies = [ "image", "image-webp", "jpeg-encoder", - "png", + "png 0.18.1", "rayon", "serde_json", "thiserror 2.0.21", @@ -1276,7 +1336,7 @@ name = "craft-png" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=d7010805175ba1190d521b2565852bdda39e632c#d7010805175ba1190d521b2565852bdda39e632c" dependencies = [ - "png", + "png 0.18.1", "thiserror 2.0.21", ] @@ -1768,6 +1828,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", "crypto-common", + "subtle", ] [[package]] @@ -2862,6 +2923,15 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + [[package]] name = "http" version = "1.5.0" @@ -3196,7 +3266,7 @@ dependencies = [ "image-webp", "moxcms", "num-traits", - "png", + "png 0.18.1", "qoi", "tiff", "zune-core", @@ -3612,6 +3682,7 @@ name = "materialcraft" version = "0.4.1" dependencies = [ "craft-atomic", + "craft-control", "craft-menu", "craft-nightly", "craft-update", @@ -3636,6 +3707,9 @@ version = "0.4.1" dependencies = [ "base64 0.22.1", "cap-std", + "craft-automation", + "craft-control", + "dirs", "getrandom 0.3.4", "image", "materialcraft-engine", @@ -3777,7 +3851,9 @@ version = "0.4.1" dependencies = [ "base64 0.22.1", "craft-atomic", + "craft-automation", "craft-behavior", + "craft-control", "craft-dialogs", "craft-host", "craft-i18n", @@ -3795,6 +3871,7 @@ dependencies = [ "egui_kittest", "image", "log", + "materialcraft-automation", "materialcraft-engine", "materialcraft-render", "rfd", @@ -3922,7 +3999,7 @@ dependencies = [ "objc2-app-kit 0.3.2", "objc2-core-foundation", "objc2-foundation 0.3.2", - "png", + "png 0.18.1", "thiserror 2.0.21", "windows-sys 0.60.2", ] @@ -4836,6 +4913,19 @@ dependencies = [ "time", ] +[[package]] +name = "png" +version = "0.17.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" +dependencies = [ + "bitflags 1.3.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + [[package]] name = "png" version = "0.18.1" @@ -6091,7 +6181,7 @@ dependencies = [ "bytemuck", "cfg-if", "log", - "png", + "png 0.18.1", "tiny-skia-path", ] diff --git a/Cargo.toml b/Cargo.toml index 18760ac41..d59310aa7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -101,6 +101,11 @@ craft-behavior = { git = "https://github.com/storytold/craft-libs", rev = "d7010 craft-host = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" } craft-theme = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" } craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" } +# Agents in the open window through the ArtCraft Launcher's switch: the link host (control server, token, +# connection file) and the Agents page of Preferences (`craft-automation`), the switch, the agent settings and +# the CLI's live client (`craft-control`). +craft-automation = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" } +craft-control = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c" } craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "d7010805175ba1190d521b2565852bdda39e632c", default-features = false } harfrust = "0.13" read-fonts = { version = "0.43", default-features = false } diff --git a/README.md b/README.md index fd9a76299..da428ff8d 100644 --- a/README.md +++ b/README.md @@ -160,16 +160,16 @@ starts from a PBR template or one of the sample materials. ### Use it from Claude Code and other agents -Register the MCP server with Claude Code, giving it the folders it may read and write: +Turn on **ArtCraft Launcher ▸ Settings ▸ AI agents**: the launcher adds one entry to Claude +Desktop, Claude Code, Cursor and LM Studio, and agents then work in the open MaterialCraft window, +with files in `Documents/ArtCraft/Agents/MaterialCraft` (**Edit ▸ Preferences ▸ AI Agents** sets +other folders and what happens while MaterialCraft is closed). -```sh -claude mcp add materialcraft -- /path/to/materialcraft-cli mcp --read-root /work/materials --write-root /work/materials -``` - -To drive the running app instead, start it with `--control 7878` and bridge to it: +Without the launcher, register a headless MCP server with Claude Code, giving it the folders it may +read and write: ```sh -claude mcp add materialcraft-app -- /path/to/materialcraft-cli mcp --bridge 7878 +claude mcp add materialcraft -- /path/to/materialcraft-cli mcp --headless --read-root /work/materials --write-root /work/materials ``` The details are in [`docs/control-protocol.md`](docs/control-protocol.md). diff --git a/apps/materialcraft-cli/src/main.rs b/apps/materialcraft-cli/src/main.rs index 956f67170..d2298f852 100644 --- a/apps/materialcraft-cli/src/main.rs +++ b/apps/materialcraft-cli/src/main.rs @@ -4,6 +4,7 @@ use std::sync::{Arc, Mutex}; +use materialcraft_automation::agents::{self, WhenAppClosed}; use materialcraft_automation::security::{client_token, server_token}; use materialcraft_automation::{AuthorizedWorkspace, BridgeClient, Filesystem, Headless, MaterialCraftMcp, RenderOptions, rpc}; use serde_json::{Value, json}; @@ -43,10 +44,16 @@ USAGE: Render the material on a 3D scene (rounded_cube, cube, sphere, cylinder, plane, torus, material_ball), or one node's output (--view 2d), to PNG. No GPU needed. The height output raises the surface; --hq is a beauty render with a finer mesh, ambient occlusion and a key light. - materialcraft-cli mcp [--bridge ] [--token ] [--read-root ] [--write-root ] - MCP server on stdio: headless (file access only below the roots), or bridged to - `materialcraft --control `. --automation-read-root / --automation-write-root are - the same as --read-root / --write-root (mcp and serve). + materialcraft-cli mcp [--headless] [--when-closed launch|headless|error] [--read-root ] [--write-root ] + MCP server on stdio. While ArtCraft Launcher > Settings > AI agents lets agents use MaterialCraft + (the suite's AI-MCP flag), each tool call goes to the open window, found by itself: no port or + token to configure. Its files are opened and saved only in the agent folders of Edit > Preferences + > AI Agents (Documents/ArtCraft/Agents/MaterialCraft by default; the roots, when given, replace + them). While MaterialCraft is closed, that page's choice (or --when-closed) decides: open it, work + without a window, or report an error. Otherwise, and with --headless, a session without a window, + with file access only below the roots. --automation-read-root / --automation-write-root are the + same as --read-root / --write-root (mcp and serve). `--bridge [--token ]` (drive + `materialcraft --control `) is deprecated and goes away in the next release. materialcraft-cli serve [--port ] [--read-root ] [--write-root ] JSON lines ({\"id\",\"method\",\"params\"}) on stdio, or on 127.0.0.1: with a token. @@ -88,7 +95,7 @@ const SUBCOMMANDS: &[(&str, &[&str], &[&str])] = &[ &["--size", "--view", "--scene", "--node", "--yaw", "--pitch", "--graph", "--graph-path", "--set", "--tiling", "--displacement"], &["--full", "--hq"], ), - ("mcp", &["--bridge", "--token", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &[]), + ("mcp", &["--bridge", "--token", "--when-closed", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &["--headless"]), ("serve", &["--port", "--read-root", "--write-root", "--automation-read-root", "--automation-write-root"], &[]), ]; @@ -373,12 +380,14 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> { } "mcp" => { let rt = tokio::runtime::Runtime::new().map_err(|e| e.to_string())?; - let server = match a.num::("--bridge")? { - Some(port) => { + let server = match mcp_mode(a, window_reachable())? { + McpMode::Bridge(port) => { + eprintln!("{BRIDGE_DEPRECATED}"); let token = client_token(port, a.get("--token").map(str::to_string)).map_err(|e| e.to_string())?; MaterialCraftMcp::bridge(BridgeClient::new(port, token)) } - None => MaterialCraftMcp::headless(Headless::new(Headless::default_session(), workspace(a)?)), + McpMode::Live(when_closed) => MaterialCraftMcp::live(live_config(a, when_closed)?), + McpMode::Headless => MaterialCraftMcp::headless(Headless::new(Headless::default_session(), workspace(a)?)), }; rt.block_on(server.serve_stdio()).map_err(|e| e.to_string())?; @@ -405,6 +414,66 @@ fn run(cmd: &str, a: &Args) -> Result<(), String> { Ok(()) } +/// What `--bridge` says on stderr while it still works. +const BRIDGE_DEPRECATED: &str = "materialcraft-cli: `mcp --bridge` is deprecated and goes away in the next release: turn on ArtCraft Launcher > Settings > AI agents for MaterialCraft and run plain `materialcraft-cli mcp`, which finds the open window by itself"; + +/// How `mcp` serves. +#[derive(Debug, PartialEq)] +enum McpMode { + /// An app started with `materialcraft --control ` (deprecated) + Bridge(u16), + /// The open window while agents may use it, otherwise headless, with the closed-app override + Live(Option), + /// A session without a window + Headless, +} + +/// `mcp`'s mode: `--bridge` (deprecated) an app started with `--control`; plain `mcp` where agents +/// can reach the open window (`window`) the live client; `--headless`, and plain `mcp` without the +/// window, a session without one. +fn mcp_mode(a: &Args, window: bool) -> Result { + let when_closed = + a.get("--when-closed").map(|v| WhenAppClosed::parse(v).ok_or_else(|| format!("--when-closed: `{v}` is not launch, headless or error"))).transpose()?; + if let Some(port) = a.num::("--bridge")? { + if a.has("--headless") || when_closed.is_some() { + return Err("--bridge drives one app started with --control; it takes neither --headless nor --when-closed".into()); + } + return Ok(McpMode::Bridge(port)); + } + if window && !a.has("--headless") { + return Ok(McpMode::Live(when_closed)); + } + if when_closed.is_some() { + return Err( + "--when-closed decides what happens while MaterialCraft is closed, and this session works without a window (--headless, or no AI-MCP flag in ArtCraft's flags)" + .into(), + ); + } + Ok(McpMode::Headless) +} + +/// Whether plain `mcp` can find the open window: the suite's AI-MCP flag is on, and the app has a +/// settings folder to publish its connection in. +fn window_reachable() -> bool { + agents::mcp_flag() && agents::settings_dir().is_some() +} + +/// Plain `mcp`: the app's settings folder (its connection file, token and agent settings), the +/// closed-app override, the app beside this CLI to start, and the command's roots for a session +/// without the window. +fn live_config(a: &Args, when_closed: Option) -> Result { + let dir = agents::settings_dir().ok_or("can't find MaterialCraft's settings folder (no home folder; set MATERIALCRAFT_DATA_DIR)")?; + // As a headless `mcp` always did: roots that can't be opened stop the start, before the server + // answers anything, rather than at the first call that would fall back to them. + workspace(a)?; + let mut config = materialcraft_automation::live::LiveConfig::new(dir); + config.when_closed = when_closed; + config.read_root = a.get("--read-root").map(std::path::PathBuf::from); + config.write_root = a.get("--write-root").map(std::path::PathBuf::from); + config.launch = std::env::current_exe().ok().and_then(|exe| agents::launcher(&exe)); + Ok(config) +} + /// File access for servers: none without roots, else only below them fn workspace(a: &Args) -> Result { let (r, w) = (a.get("--read-root"), a.get("--write-root")); @@ -451,6 +520,29 @@ mod tests { assert_eq!(a.get("--write-root"), Some("/b")); } + /// `mcp`'s window options: plain `mcp` uses the open window only where agents can reach it, and + /// `--headless` never; `--when-closed` takes one of the three choices and only means something for + /// a session that may use the window; `--bridge` takes neither, and still works for one release. + #[test] + fn mcp_chooses_the_window_only_where_agents_can_reach_it() { + let mode = |args: &[&str], window: bool| mcp_mode(&parse("mcp", &strings(args)).unwrap(), window); + assert_eq!(mode(&[], true), Ok(McpMode::Live(None))); + assert_eq!(mode(&["--when-closed", "error"], true), Ok(McpMode::Live(Some(WhenAppClosed::Error)))); + assert_eq!(mode(&["--read-root", "/r", "--write-root", "/w"], true), Ok(McpMode::Live(None)), "the roots replace the agent folders"); + assert_eq!(mode(&[], false), Ok(McpMode::Headless)); + assert_eq!(mode(&["--headless"], true), Ok(McpMode::Headless)); + assert_eq!(mode(&["--bridge", "7979"], true), Ok(McpMode::Bridge(7979))); + + assert!(mode(&["--when-closed", "later"], true).unwrap_err().contains("launch, headless or error")); + for (args, window) in [(&["--when-closed", "launch"][..], false), (&["--headless", "--when-closed", "error"][..], true)] { + assert!(mode(args, window).unwrap_err().contains("--when-closed"), "{args:?}"); + } + for args in [&["--bridge", "7979", "--headless"][..], &["--bridge", "7979", "--when-closed", "headless"][..]] { + assert!(mode(args, true).unwrap_err().contains("--bridge"), "{args:?}"); + } + assert!(BRIDGE_DEPRECATED.contains("deprecated") && BRIDGE_DEPRECATED.contains("AI agents")); + } + #[test] fn automation_root_flags_need_a_value_and_stay_unknown_elsewhere() { assert!(parse("mcp", &strings(&["--automation-read-root"])).is_err()); diff --git a/apps/materialcraft/Cargo.toml b/apps/materialcraft/Cargo.toml index d3cd947e9..8e117238e 100644 --- a/apps/materialcraft/Cargo.toml +++ b/apps/materialcraft/Cargo.toml @@ -26,6 +26,8 @@ rfd = { workspace = true } craft-atomic = { workspace = true } # Nightly profile isolation, launch protocol, and security fence (src/launch_profile.rs, src/profile_root.rs). craft-nightly = { workspace = true } +# Agents in the open window: the ArtCraft Launcher's switch and the stale connection file at start. +craft-control = { workspace = true, features = ["agents"] } # The window frame's choice applies before the window exists. craft-window = { workspace = true, features = ["ui"] } diff --git a/apps/materialcraft/src/main.rs b/apps/materialcraft/src/main.rs index 8615488bf..4bd09617a 100644 --- a/apps/materialcraft/src/main.rs +++ b/apps/materialcraft/src/main.rs @@ -216,6 +216,32 @@ fn persistence_path() -> Option { .or_else(|| std::env::var_os("MATERIALCRAFT_DATA_DIR").filter(|v| !v.is_empty()).map(|dir| std::path::PathBuf::from(dir).join("app.ron"))) } +/// Agents in the open window: while the ArtCraft Launcher's switch (Settings › AI agents) names +/// MaterialCraft, the agent link serves the control channel for `materialcraft-cli mcp` and publishes +/// `agent-connection.json` in the settings folder `dir` (`materialcraft_ui_egui::agents`), with the +/// agent settings Edit › Preferences › AI Agents saves there. `--control` manages its own server for +/// the whole run instead. +fn agents(ctx: &egui::Context, dir: Option, control: Option) -> materialcraft_ui_egui::agents::Agents { + use materialcraft_automation::agents::{LAUNCHER_APP_ID, read_settings, write_settings}; + // A file a crashed (or, on macOS, quit) launch left behind names a port nothing serves. + if let Some(dir) = &dir { + craft_control::agents::remove_stale_connection(dir); + } + let wake = ctx.clone(); + let switch = craft_control::agents::AgentSwitch::watch(LAUNCHER_APP_ID, move || wake.request_repaint()); + let settings = dir.as_deref().map(read_settings).unwrap_or_default(); + let save_dir = dir.clone(); + let save: materialcraft_ui_egui::agents::SaveFn = Box::new(move |settings| match &save_dir { + Some(dir) => write_settings(dir, settings), + None => Err("MaterialCraft has no settings folder, so the agent settings can't be saved".into()), + }); + let agents = materialcraft_ui_egui::agents::Agents::new(dir, version(), switch, settings, save); + match control { + Some(port) => agents.launched_with_control(port), + None => agents, + } +} + fn main() { let Some(arguments) = prepare_launch() else { return }; let nightly = launch_profile::current().is_nightly(); @@ -261,6 +287,9 @@ fn main() { // run that only redirects MATERIALCRAFT_DATA_DIR keeps its storage and its update prompt. let throwaway_prefs = std::env::var_os("MATERIALCRAFT_NO_PREFS").is_some(); let startup_update_check = !nightly && checks_for_updates_at_start(control, throwaway_prefs); + // A Nightly profile is not the app the launcher's switch names, and a scripted run keeps no + // settings: neither takes agents. + let agents_dir = (!nightly && !throwaway_prefs).then(materialcraft_automation::agents::settings_dir); let options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, persistence_path, ..Default::default() }; // After the primary claim, before entering the window loop. No document names, paths or @@ -303,6 +332,9 @@ fn main() { if let Some(port) = control { app.control = Some(control_server::start(port, cc.egui_ctx.clone())); } + if let Some(dir) = agents_dir { + app.agents = Some(agents(&cc.egui_ctx, dir, control)); + } if previous_nightly_unclean || session_health_warning { let message = if previous_nightly_unclean { "The previous MaterialCraft Nightly session did not finish normally. You can report a problem from About. No diagnostics have been sent." @@ -330,6 +362,13 @@ fn main() { mod tests { use super::*; + /// `materialcraft-cli mcp` finds the window's connection file in the folder the app keeps its + /// settings in; it looks it up without eframe, so the two must name the same folder. + #[test] + fn the_cli_looks_for_agents_in_the_apps_settings_folder() { + assert_eq!(materialcraft_automation::agents::stable_settings_dir(), eframe::storage_dir(os_window::name_for(os_window::LaunchIdentity::Stable))); + } + /// A caller-written `--` separates files; it never becomes one, however many arrive. #[test] fn the_file_delimiter_is_never_opened_as_a_path() { diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index 3b961710b..b7ced0159 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -21,6 +21,13 @@ schemars = { workspace = true } base64 = { workspace = true } cap-std = { workspace = true } getrandom = { workspace = true } +# Agents in the open window: the ArtCraft Launcher's switch, the connection file, the agent +# settings and folders, and the CLI's live client (`agents`). +craft-control = { workspace = true, features = ["agents"] } +# The challenge handshake the window's agent server speaks (no UI parts). +craft-automation = { workspace = true } +# The desktop app's settings folder, as eframe finds it (MIT OR Apache-2.0, already in the tree). +dirs = "7" [target.'cfg(unix)'.dependencies] rustix = { workspace = true } diff --git a/crates/automation/src/agents.rs b/crates/automation/src/agents.rs new file mode 100644 index 000000000..8526c6423 --- /dev/null +++ b/crates/automation/src/agents.rs @@ -0,0 +1,202 @@ +//! Agents in the open window: MaterialCraft's side of the ArtCraft Launcher's switch. +//! +//! While the launcher's *Settings › AI agents* switch names MaterialCraft (behind the suite's +//! `AI-MCP` flag), the desktop app serves agents on loopback and publishes where in its settings +//! folder (`craft_automation::agents::AgentLink`, in `materialcraft-ui-egui`). Plain +//! `materialcraft-cli mcp` reads that file before every tool call ([`crate::live`], over the shared +//! `craft_control::agents::Live`), so an MCP client's configuration holds no port and no token, and +//! the app may start, quit or move to another port while the client stays connected. Adding +//! MaterialCraft to MCP clients is the launcher's job (one entry for every Craft app); MaterialCraft +//! writes no client configuration. +//! +//! What is MaterialCraft's here: its launcher id, its settings folder as the CLI finds it +//! ([`settings_dir`]), its agent settings file ([`SETTINGS_FILE`], which Edit › Preferences › AI +//! Agents writes and the CLI reads), the folders an agent session is held to ([`workspace`]) and the +//! `agent_folders` answer ([`folders_answer`]). + +use std::io::Read; +use std::path::{Path, PathBuf}; + +use craft_control::agents::{self as shared, AgentFolders, AgentSettings}; +pub use craft_control::agents::{WhenAppClosed, mcp_flag}; +use serde_json::{Value, json}; + +use crate::{AuthorizedWorkspace, AutomationError}; + +/// The id the ArtCraft Launcher's app list names MaterialCraft by (its catalog id). +pub const LAUNCHER_APP_ID: &str = "materialcraft"; +/// The app's name in messages and its default agent folder (`Documents/ArtCraft/Agents/MaterialCraft`). +pub const APP_NAME: &str = "MaterialCraft"; +/// The desktop app's file name beside the CLI (without `.exe`). +pub const APP_EXE: &str = "materialcraft"; +/// The agent settings in the settings folder: `{"controlPort", "readRoot", "writeRoot", +/// "whenAppClosed", "allowAgentControl"}` (`craft_control::agents::AgentSettings`). The app writes it +/// when they change, so `materialcraft-cli mcp` reads the current choice before every tool call. +pub const SETTINGS_FILE: &str = "agents.json"; +/// The control method the `agent_folders` tool calls in the window. +pub const FOLDERS_METHOD: &str = "agent.folders"; +/// The settings folder a package wrapper or a test sets (the desktop app reads the same variable). +pub const DATA_DIR_ENV: &str = "MATERIALCRAFT_DATA_DIR"; +/// Scripted runs: the app keeps no settings, so it takes no agents and the CLI finds no window. +pub const NO_PREFS_ENV: &str = "MATERIALCRAFT_NO_PREFS"; + +/// The largest settings file read; the settings are a few short strings. +const MAX_SETTINGS_FILE: u64 = 64 * 1024; + +/// The desktop app's settings folder, where it publishes its agent connection: `None` for a +/// scripted run ([`NO_PREFS_ENV`]), else a non-empty [`DATA_DIR_ENV`], else the folder eframe keeps +/// MaterialCraft's settings in ([`stable_settings_dir`]). A Nightly profile takes no agents, so its +/// folder is never looked for. +pub fn settings_dir() -> Option { + if std::env::var_os(NO_PREFS_ENV).is_some() { + return None; + } + std::env::var_os(DATA_DIR_ENV).filter(|v| !v.is_empty()).map(PathBuf::from).or_else(stable_settings_dir) +} + +/// The folder eframe's `storage_dir("MaterialCraft")` names, found without eframe: the roaming +/// application data folder's `MaterialCraft\data` on Windows, `Library/Application Support/MaterialCraft` +/// on macOS and the XDG data folder's `materialcraft` elsewhere. +pub fn stable_settings_dir() -> Option { + let data = dirs::data_dir()?; + Some(if cfg!(windows) { + data.join(APP_NAME).join("data") + } else if cfg!(target_os = "macos") { + data.join(APP_NAME) + } else { + data.join(APP_NAME.to_lowercase()) + }) +} + +/// The agent settings saved in `dir`; the defaults when nothing is saved or the file can't be +/// read, so neither the app nor the CLI fails over them. One bad value resets only itself. +pub fn read_settings(dir: &Path) -> AgentSettings { + let text = (|| { + let file = std::fs::File::open(dir.join(SETTINGS_FILE)).ok()?; + let mut text = String::new(); + file.take(MAX_SETTINGS_FILE + 1).read_to_string(&mut text).ok()?; + (text.len() as u64 <= MAX_SETTINGS_FILE).then_some(text) + })(); + let Some(Value::Object(saved)) = text.and_then(|text| serde_json::from_str::(&text).ok()) else { return AgentSettings::default() }; + let mut settings = AgentSettings::default(); + for (key, value) in saved { + let mut one = serde_json::to_value(&settings).unwrap_or_default(); + if let Some(o) = one.as_object_mut() + && o.contains_key(&key) + { + o.insert(key, value); + if let Ok(next) = serde_json::from_value(one) { + settings = next; + } + } + } + settings +} + +/// Saves `settings` in `dir` (created when missing), replacing the file in one step so a +/// `materialcraft-cli mcp` reading it at the same time sees the old or the new settings, never half. +pub fn write_settings(dir: &Path, settings: &AgentSettings) -> Result<(), String> { + let text = serde_json::to_vec_pretty(settings).map_err(|e| e.to_string())?; + std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + materialcraft_engine::formats::write_atomic(&dir.join(SETTINGS_FILE), &text).map_err(|e| format!("{}: {e}", dir.join(SETTINGS_FILE).display())) +} + +/// Whether the person lets agents use MaterialCraft now: with the suite's `AI-MCP` flag, the +/// launcher's switch. MaterialCraft had no agent consent of its own before the switch, so without +/// the flag agents get a session without a window, as `mcp` always gave them. +pub fn allowed_now() -> bool { + shared::agents_allowed(shared::mcp_flag(), shared::launcher_allows(LAUNCHER_APP_ID), false) +} + +/// The folders an agent session works in: the read folder (the write folder when there is none, +/// so an agent reopens what it saved) and the write folder. +fn effective(folders: &AgentFolders) -> (Option<&Path>, Option<&Path>) { + (folders.read.as_deref().or(folders.write.as_deref()), folders.write.as_deref()) +} + +/// The file access of an agent session with these folders: paths relative to the read folder and +/// to the write folder ([`effective`]). No folder grants nothing. Nothing may be written in the +/// settings folder `settings` (the agent settings there choose these folders), even when the write +/// folder holds it. +pub fn workspace(folders: &AgentFolders, settings: Option<&Path>) -> Result { + let (read, write) = effective(folders); + let workspace = AuthorizedWorkspace::new(read, write)?; + Ok(match settings { + Some(dir) => workspace.denying_writes_in(dir), + None => workspace, + }) +} + +/// The `agent_folders` answer for a session held to `folders`: `read_folder` and `write_folder` +/// (each a path or `null`), and that MaterialCraft holds agents to them. +pub fn folders_answer(folders: &AgentFolders) -> Value { + let (read, write) = effective(folders); + let mut shown = AgentFolders::default(); + shown.read = read.map(Path::to_path_buf); + shown.write = write.map(Path::to_path_buf); + let mut answer = shared::folders_answer(&shown); + answer["confined"] = json!(true); + answer["paths"] = json!("File tools take forward-slash paths relative to these folders, such as `bricks/wall.sbs`."); + answer +} + +/// Starts the desktop app beside the CLI at `cli` (`materialcraft-cli` and `materialcraft` ship +/// together); `None` when this install has none. +pub fn launcher(cli: &Path) -> Option { + shared::launcher(cli, APP_EXE) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// What the app saves the CLI reads back; a damaged value resets only itself, a damaged file + /// gives the defaults instead of an error. + #[test] + fn settings_round_trip_and_damage_resets_only_itself() { + let dir = tempfile::tempdir().unwrap(); + let dir = dir.path(); + let mut mine = AgentSettings::default(); + mine.read_root = "/in".into(); + mine.when_app_closed = WhenAppClosed::Error; + write_settings(dir, &mine).unwrap(); + assert_eq!(read_settings(dir), mine); + + std::fs::write(dir.join(SETTINGS_FILE), r#"{"readRoot": "/in", "whenAppClosed": "sometimes", "controlPort": 7}"#).unwrap(); + let read = read_settings(dir); + assert_eq!((read.read_root.as_str(), read.control_port), ("/in", 7)); + assert_ne!(read.when_app_closed, WhenAppClosed::Error, "an unknown choice falls back to the default"); + + std::fs::write(dir.join(SETTINGS_FILE), "not json").unwrap(); + assert_eq!(read_settings(dir), AgentSettings::default()); + } + + /// An agent writes only in its write folder, never in the settings folder that names its + /// folders, even when the person chose a write folder that holds the settings folder, and also + /// when the settings folder doesn't exist yet or is named in another letter case. + #[test] + fn the_settings_folder_stays_out_of_reach() { + let base = tempfile::tempdir().unwrap(); + let base = base.path(); + let settings = base.join("settings"); + let mut folders = AgentFolders::default(); + folders.write = Some(base.to_path_buf()); + // Not created yet: an agent must not create it either. + let ws = workspace(&folders, Some(&settings)).unwrap(); + assert!(ws.create_dir_all("settings/sub").is_err()); + std::fs::create_dir_all(&settings).unwrap(); + let ws = workspace(&folders, Some(&settings)).unwrap(); + ws.write("made.txt", b"x").unwrap(); + assert!(ws.write(&format!("settings/{SETTINGS_FILE}"), b"{}").is_err(), "an agent rewrote its own folders"); + assert!(ws.check_write(&format!("settings/{SETTINGS_FILE}")).is_err()); + if cfg!(windows) { + assert!(ws.write(&format!("SETTINGS/{SETTINGS_FILE}"), b"{}").is_err(), "another letter case got past the guard"); + } + assert!(!settings.join(SETTINGS_FILE).exists()); + // With no read folder, the write folder is read: an agent reopens what it saved. + assert_eq!(ws.read("made.txt").unwrap(), b"x"); + let answer = folders_answer(&folders); + assert_eq!(answer["read_folder"], answer["write_folder"]); + assert_eq!(answer["confined"], true); + } +} diff --git a/crates/automation/src/bridge.rs b/crates/automation/src/bridge.rs index 887c306a3..34476cb85 100644 --- a/crates/automation/src/bridge.rs +++ b/crates/automation/src/bridge.rs @@ -1,5 +1,10 @@ -//! Client for the running app's control channel (`materialcraft --control `): one JSON -//! request per line, replies matched by `id`. Keeps one connection, reconnects once on failure. +//! Client for the running app's control channel: one JSON request per line, replies matched by +//! `id`. Keeps one connection, reconnects once on failure. +//! +//! Two ways in: `materialcraft --control ` takes the token in an `auth` request +//! ([`BridgeClient::new`]); the server the app runs for agents (the ArtCraft Launcher's switch, +//! `craft_automation::agents::AgentLink`) takes the challenge handshake ([`BridgeClient::signed_in`]): +//! the app first proves it holds the token, and the token itself never crosses the wire. use std::sync::atomic::{AtomicU64, Ordering}; use std::time::Duration; @@ -15,9 +20,18 @@ use crate::budgets::MAX_BRIDGE_REPLY_BYTES; type Conn = (BufReader, OwnedWriteHalf); +/// How a connection proves it may drive the app. +enum Auth { + /// `{"method":"auth","params":{"token"}}` first (`materialcraft --control`). + Token, + /// The challenge handshake (the agent server of the open window). + Handshake, +} + pub struct BridgeClient { port: u16, token: String, + auth: Auth, conn: Mutex>, next_id: AtomicU64, } @@ -25,7 +39,13 @@ pub struct BridgeClient { impl BridgeClient { /// A client for the app on `127.0.0.1:port` (loopback only, like the server). pub fn new(port: u16, token: String) -> BridgeClient { - BridgeClient { port, token, conn: Mutex::new(None), next_id: AtomicU64::new(1) } + BridgeClient { port, token, auth: Auth::Token, conn: Mutex::new(None), next_id: AtomicU64::new(1) } + } + + /// The open app's agent server on `127.0.0.1:port` (from its connection file), signing in with + /// the challenge handshake and `token` (from the token file the connection names). + pub fn signed_in(port: u16, token: String) -> BridgeClient { + BridgeClient { port, token, auth: Auth::Handshake, conn: Mutex::new(None), next_id: AtomicU64::new(1) } } pub fn port(&self) -> u16 { @@ -37,11 +57,13 @@ impl BridgeClient { let s = tokio::time::timeout(Duration::from_secs(5), TcpStream::connect(addr)) .await .map_err(|_| AutomationError::Bridge(format!("timed out connecting to 127.0.0.1:{}", self.port)))? - .map_err(|e| { - AutomationError::Bridge(format!("cannot connect to 127.0.0.1:{} ({e}); start the app with `materialcraft --control {}`", self.port, self.port)) - })?; + .map_err(|e| AutomationError::Bridge(self.cannot_connect(&e)))?; let (r, w) = s.into_split(); let mut conn = (BufReader::new(r), w); + if let Auth::Handshake = self.auth { + self.handshake(&mut conn).await?; + return Ok(conn); + } let id = self.next_id.fetch_add(1, Ordering::Relaxed); tokio::time::timeout(Duration::from_secs(5), exchange(&mut conn, id, "auth", &json!({"token": self.token}))) .await @@ -50,8 +72,76 @@ impl BridgeClient { Ok(conn) } + /// Why a connection failed and what to do: the agent server comes and goes with the app and the + /// launcher's switch; `--control` is a launch option. + fn cannot_connect(&self, e: &std::io::Error) -> String { + match self.auth { + Auth::Handshake => format!( + "cannot connect to MaterialCraft on 127.0.0.1:{} ({e}): it may have quit or stopped taking agents; open MaterialCraft again and check that ArtCraft Launcher › Settings › AI agents lets agents use it", + self.port + ), + Auth::Token => format!("cannot connect to 127.0.0.1:{} ({e}); start the app with `materialcraft --control {}`", self.port, self.port), + } + } + + /// The challenge handshake (`craft_automation::security::ServerHandshake`): send a nonce, check + /// the app's proof that it holds the token, then send this side's proof. Nothing derived from the + /// token is sent before the app has proved itself, so a program that took the port of an app that + /// quit learns nothing. + async fn handshake(&self, conn: &mut Conn) -> Result<(), AutomationError> { + use craft_automation::security::{AUTH_METHOD, CHALLENGE_METHOD, ProofRole, generate_nonce, handshake_proof, proof_matches}; + let refused = |why: &str| AutomationError::Bridge(format!("MaterialCraft on 127.0.0.1:{} refused the agent connection: {why}", self.port)); + let client_nonce = generate_nonce().map_err(|e| AutomationError::Bridge(e.to_string()))?; + let challenge = self.auth_frame(conn, CHALLENGE_METHOD, json!({"clientNonce": client_nonce})).await?; + if challenge.get("ok") != Some(&Value::Bool(true)) { + return Err(refused(challenge.get("error").and_then(Value::as_str).unwrap_or("no challenge"))); + } + let field = |key: &str| challenge.pointer(&format!("/result/{key}")).and_then(Value::as_str).unwrap_or_default().to_string(); + let (server_nonce, server_proof) = (field("serverNonce"), field("serverProof")); + if !proof_matches(&self.token, ProofRole::Server, &client_nonce, &server_nonce, &server_proof) { + return Err(AutomationError::Bridge(format!( + "the program on 127.0.0.1:{} did not prove it is the MaterialCraft that published the agent connection; start MaterialCraft again", + self.port + ))); + } + let proof = handshake_proof(&self.token, ProofRole::Client, &client_nonce, &server_nonce).map_err(|e| AutomationError::Bridge(e.to_string()))?; + let signed = self.auth_frame(conn, AUTH_METHOD, json!({"proof": proof})).await?; + if signed.get("ok") != Some(&Value::Bool(true)) { + return Err(refused(signed.get("error").and_then(Value::as_str).unwrap_or("authentication failed"))); + } + Ok(()) + } + + /// One handshake frame (id 0; requests count from 1) and its reply. + async fn auth_frame(&self, conn: &mut Conn, method: &str, params: Value) -> Result { + let io = |e: std::io::Error| AutomationError::Bridge(e.to_string()); + let line = format!("{}\n", json!({"id": 0, "method": method, "params": params})); + conn.1.write_all(line.as_bytes()).await.map_err(io)?; + conn.1.flush().await.map_err(io)?; + let mut buf = Vec::new(); + let n = tokio::time::timeout(Duration::from_secs(10), (&mut conn.0).take(64 * 1024).read_until(b'\n', &mut buf)) + .await + .map_err(|_| AutomationError::Bridge(format!("127.0.0.1:{} did not answer the sign-in", self.port)))? + .map_err(io)?; + if n == 0 { + return Err(AutomationError::Bridge(format!("127.0.0.1:{} closed the connection during the sign-in", self.port))); + } + serde_json::from_slice(&buf) + .map_err(|_| AutomationError::Bridge(format!("the program on 127.0.0.1:{} is not a MaterialCraft agent connection", self.port))) + } + /// Call a control method; returns its `result` or the app's error. pub async fn call(&self, method: &str, params: Value) -> Result { + // The agent server reads requests of at most 1 MiB; say so before sending a longer one. + if let Auth::Handshake = self.auth { + let len = serde_json::to_string(¶ms).map_or(0, |p| p.len()); + if len > craft_automation::security::MAX_REQUEST_BYTES - 1024 { + return Err(AutomationError::BadRequest(format!( + "`{method}` is {len} bytes, over the {} bytes MaterialCraft's window takes in one request; send less at once", + craft_automation::security::MAX_REQUEST_BYTES + ))); + } + } let mut guard = self.conn.lock().await; for attempt in 0..2 { let mut conn = match guard.take() { diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index f30e6a147..995741d43 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -12,7 +12,7 @@ use serde_json::{Value, json}; use crate::budgets::{HQ_TRIANGLES, MAX_LOCAL_RENDER_SIDE, MAX_PNG_SIDE, check_png, encode_png}; use crate::workspace::{MAX_READ_BYTES, authorize_command}; -use crate::{AutomationError, bad}; +use crate::{AuthorizedWorkspace, AutomationError, bad}; pub use crate::{Filesystem, RenderOptions, Rendered}; const MAX_EXPORTED_MATERIAL_BYTES: u64 = 256 << 20; @@ -69,6 +69,17 @@ impl Headless { Headless { session, fs, scene: None, light: None } } + /// The open window's `session` for one agent request, with file access only below the agent + /// folders in `workspace`; [`Self::into_session`] hands it back. + pub fn confined(session: Session, workspace: AuthorizedWorkspace) -> Headless { + Headless::new(session, Filesystem::Workspace(workspace)) + } + + /// The session, for the window to keep after [`Self::confined`]. + pub fn into_session(self) -> Session { + self.session + } + /// The session a fresh server starts with: the atomic sample pub fn default_session() -> Session { materialcraft_engine::sample_session() diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index 56aa9f44c..603781d3d 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -1,9 +1,16 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +//! MaterialCraft automation: the headless session ([`Headless`]), the MCP server +//! ([`MaterialCraftMcp`]), the JSON-lines server ([`rpc`]) and the client of the app's control +//! channel ([`BridgeClient`]). [`agents`] and [`live`]: agents in the open window through the +//! ArtCraft Launcher's switch; plain `materialcraft-cli mcp` finds the window by itself. + +pub mod agents; pub mod bridge; pub mod budgets; pub mod headless; +pub mod live; pub mod rpc; pub mod security; pub mod server; diff --git a/crates/automation/src/live.rs b/crates/automation/src/live.rs new file mode 100644 index 000000000..7ce4399f8 --- /dev/null +++ b/crates/automation/src/live.rs @@ -0,0 +1,129 @@ +//! Plain `materialcraft-cli mcp` with the suite's `AI-MCP` flag: tools go to the open MaterialCraft +//! window while the ArtCraft Launcher's switch lets agents use it, found through the connection file +//! the app publishes in its settings folder, and otherwise to a session without a window, as `mcp` +//! always did (`--headless` forces that). The file is read again on every tool call, so the app may +//! start, quit or move to another port while the MCP client stays connected; the client's +//! configuration holds no port and no token. +//! +//! While agents may use the app but it is closed, Edit › Preferences › AI Agents › When MaterialCraft +//! Is Closed (or `--when-closed`) decides: start the app and wait for it, work without a window, or +//! an error that says what to do. A session that went headless stays headless for the rest of the +//! MCP session, so the package doesn't move under the agent. +//! +//! The lookup is the framework's, shared by every Craft app (`craft_control::agents::Live`); this +//! module supplies MaterialCraft's parts: where its settings are, its window client +//! ([`BridgeClient::signed_in`]) and its headless session. + +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use craft_control::agents::{self as shared, AgentFolders, Consent, HeadlessFolders, Route, Window}; +pub use craft_control::agents::{LAUNCH_TIMEOUT, LaunchFn, WhenAppClosed}; +use serde_json::{Value, json}; + +use crate::agents::{self, APP_NAME}; +use crate::{BridgeClient, Filesystem, Headless}; + +/// What plain `mcp` needs to find the window. +pub struct LiveConfig { + /// The app's settings folder: its connection file, token file and agent settings. + pub config_dir: PathBuf, + /// Overrides the app's closed-app choice (`--when-closed`). + pub when_closed: Option, + /// The command's folders (`--automation-read-root`, `--automation-write-root`): a session without a + /// window uses them, and while agents are allowed they replace the app's agent folders. + pub read_root: Option, + pub write_root: Option, + /// Starts the app; `None` when this install can't (no app beside the CLI). + pub launch: Option, + pub launch_timeout: Duration, + /// Whether the person lets agents use the open app ([`agents::allowed_now`]); tests replace it. + pub allowed: fn() -> bool, + /// The default agent folder for an empty folder setting (`Documents/ArtCraft/Agents/MaterialCraft`); + /// tests replace it. + pub default_folder: Option, +} + +impl LiveConfig { + /// The settings in `config_dir`, the launcher's switch, the default agent folder. + pub fn new(config_dir: PathBuf) -> Self { + LiveConfig { + config_dir, + when_closed: None, + read_root: None, + write_root: None, + launch: None, + launch_timeout: LAUNCH_TIMEOUT, + allowed: agents::allowed_now, + default_folder: shared::default_folder(APP_NAME), + } + } +} + +/// A session without a window, and its `agent_folders` answer. +pub struct HeadlessRoute { + pub session: Arc>, + pub folders: Value, +} + +/// Where a tool call goes once [`Live::resolve`] has run. +#[derive(Clone)] +pub enum Target { + Window(Arc), + Headless(Arc), +} + +impl From, Arc>> for Target { + fn from(route: Route, Arc>) -> Self { + match route { + Route::Window(b) => Target::Window(b), + Route::Headless(h) => Target::Headless(h), + } + } +} + +type Shared = shared::Live, Arc>; + +/// Resolves each tool call of one MCP session; see the module docs. +pub struct Live { + shared: Arc, +} + +impl Live { + pub fn new(cfg: LiveConfig) -> Self { + let LiveConfig { config_dir, when_closed, read_root, write_root, launch, launch_timeout, allowed, default_folder } = cfg; + let consent = move |dir: &Path| Consent::new(allowed(), agents::read_settings(dir)); + let connect = |w: &Window| Ok(Arc::new(BridgeClient::signed_in(w.port, w.token.clone()))); + let settings_dir = config_dir.clone(); + let headless = move |folders: &HeadlessFolders| -> Result, String> { + let mut own = AgentFolders::default(); + own.read = folders.read.first().cloned(); + own.write = folders.write.clone(); + let (fs, answer) = if own.read.is_none() && own.write.is_none() { + // No folder: nothing may be opened or saved, as `mcp` without roots never could. + (Filesystem::Denied, json!({"read_folder": null, "write_folder": null, "confined": true})) + } else { + let workspace = agents::workspace(&own, Some(&settings_dir)).map_err(|e| e.to_string())?; + (Filesystem::Workspace(workspace), agents::folders_answer(&own)) + }; + Ok(Arc::new(HeadlessRoute { session: Arc::new(Mutex::new(Headless::new(Headless::default_session(), fs))), folders: answer })) + }; + let mut cfg = shared::LiveConfig::new(APP_NAME, config_dir, consent, connect, headless); + cfg.when_closed = when_closed; + cfg.read_roots = read_root.into_iter().collect(); + cfg.write_root = write_root; + cfg.launch = launch; + cfg.launch_timeout = launch_timeout; + cfg.default_folder = default_folder; + Live { shared: Arc::new(shared::Live::new(cfg)) } + } + + /// Find the app (or apply the closed-app choice) before a tool call. The error is the tool's + /// result: it tells the agent, and through it the person, what to do. The lookup blocks (file + /// reads, a loopback probe, polling while the app starts), so it runs off the async runtime. + pub async fn resolve(&self) -> Result { + let shared = self.shared.clone(); + tokio::task::spawn_blocking(move || shared.resolve().map(Target::from)).await.map_err(|e| format!("task failed: {e}"))? + } +} diff --git a/crates/automation/src/server/backend.rs b/crates/automation/src/server/backend.rs index 0d250b712..a8229c8ba 100644 --- a/crates/automation/src/server/backend.rs +++ b/crates/automation/src/server/backend.rs @@ -1,3 +1,4 @@ +use crate::live::Live; use crate::{BridgeClient, Headless}; use std::sync::{Arc, Mutex}; @@ -5,6 +6,8 @@ use std::sync::{Arc, Mutex}; pub enum Backend { /// An in-process session Headless(Arc>), - /// The running desktop app, over its control channel + /// The running desktop app, over its control channel (`materialcraft --control`; deprecated) Bridge(Arc), + /// The open window while agents may use it, otherwise a headless session ([`crate::live`]) + Live(Arc), } diff --git a/crates/automation/src/server/live_tests.rs b/crates/automation/src/server/live_tests.rs new file mode 100644 index 000000000..0f43477ec --- /dev/null +++ b/crates/automation/src/server/live_tests.rs @@ -0,0 +1,185 @@ +//! Live mode: the open window through the ArtCraft Launcher's switch, found through the connection +//! file the app publishes, and the closed-app choice otherwise. + +use std::io::{BufRead, BufReader, Write}; +use std::net::TcpListener; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; + +use rmcp::handler::server::wrapper::Parameters; +use serde_json::{Value, json}; + +use super::{FilterParams, MaterialCraftMcp, SaveParams}; +use crate::BridgeClient; +use crate::agents::SETTINGS_FILE; +use crate::live::LiveConfig; + +const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; +const OTHER: &str = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"; + +/// A stand-in for the window's agent server (`craft_automation::server`): the challenge handshake +/// with `token`, then every request answered with `{"window": true}`. Every line is recorded. +fn agent_server(token: &'static str) -> (u16, Arc>>) { + use craft_automation::security::{AuthStep, ServerHandshake}; + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let seen = Arc::new(Mutex::new(Vec::new())); + let log = seen.clone(); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(stream) = stream else { continue }; + let log = log.clone(); + std::thread::spawn(move || { + let mut out = stream.try_clone().unwrap(); + let mut handshake = ServerHandshake::new(); + let mut signed_in = false; + for line in BufReader::new(stream).lines() { + let Ok(line) = line else { return }; + let request: Value = serde_json::from_str(&line).unwrap_or(Value::Null); + log.lock().unwrap().push(request.clone()); + let reply = if signed_in { + json!({"id": request["id"], "ok": true, "result": {"window": true}}) + } else { + let (reply, step) = handshake.reply(&line, token); + signed_in = step == AuthStep::Authenticated; + if step == AuthStep::Rejected { + let _ = writeln!(out, "{reply}"); + return; + } + reply + }; + if writeln!(out, "{reply}").is_err() { + return; + } + } + }); + } + }); + (port, seen) +} + +/// Publishes a window on `port` in `dir`, as the app's agent link does: the token file and the +/// connection file naming it. +fn publish(dir: &Path, port: u16) { + let token_file = dir.join(craft_control::agents::TOKEN_FILE); + std::fs::write(&token_file, TOKEN).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&token_file, std::fs::Permissions::from_mode(0o600)).unwrap(); + } + craft_control::agents::write_connection(dir, &craft_control::agents::Connection::new(port, token_file, "MaterialCraft test")).unwrap(); +} + +/// Edit › Preferences › AI Agents saved in `dir`, as the app saves them. +fn save_agent_settings(dir: &Path, settings: Value) { + std::fs::write(dir.join(SETTINGS_FILE), settings.to_string()).unwrap(); +} + +/// The default agent folder of the settings folder `dir` in these tests: beside it, since nothing +/// may be written in the settings folder. +fn agent_folder(dir: &Path) -> PathBuf { + PathBuf::from(format!("{}-agents", dir.display())) +} + +/// A live session over the settings folder `dir`, with the launcher's switch given by `allowed` +/// and no app to start. +fn live(dir: &Path, allowed: fn() -> bool) -> MaterialCraftMcp { + let mut config = LiveConfig::new(dir.to_path_buf()); + config.allowed = allowed; + config.default_folder = Some(agent_folder(dir)); + MaterialCraftMcp::live(config) +} + +fn text(r: &rmcp::model::CallToolResult) -> String { + serde_json::to_string(&r.content).unwrap() +} + +/// Switch on and the app open: tool calls land in its window, found through the connection file, +/// and the token never crosses the wire. +#[tokio::test(flavor = "multi_thread")] +async fn live_calls_go_to_the_open_window_while_the_switch_allows() { + let dir = tempfile::tempdir().unwrap(); + let (port, seen) = agent_server(TOKEN); + publish(dir.path(), port); + let m = live(dir.path(), || true); + let r = m.ui_inspect().await.unwrap(); + assert_ne!(r.is_error, Some(true), "{r:?}"); + // The window, not the CLI, decides about paths: the file tools reach it. + let saved = m.package_save(Parameters(SaveParams { path: Some("a.sbs".into()) })).await.unwrap(); + assert_ne!(saved.is_error, Some(true), "{saved:?}"); + let folders = m.agent_folders().await.unwrap(); + assert_ne!(folders.is_error, Some(true), "{folders:?}"); + let seen = seen.lock().unwrap(); + for method in ["ui.inspect", "package.save", crate::agents::FOLDERS_METHOD] { + assert!(seen.iter().any(|line| line["method"] == method), "{method}: {seen:?}"); + } + assert!(!serde_json::to_string(&*seen).unwrap().contains(TOKEN), "the token crossed the wire: {seen:?}"); +} + +/// A program on the port that doesn't hold the token (it took the port of an app that quit) can't +/// answer the challenge: the client stops before it sends anything derived from the token. +#[tokio::test(flavor = "multi_thread")] +async fn a_server_without_the_token_gets_no_proof() { + let (port, seen) = agent_server(OTHER); + let err = BridgeClient::signed_in(port, TOKEN.to_string()).call("ui.inspect", json!({})).await.unwrap_err().to_string(); + assert!(err.contains("did not prove"), "{err}"); + let seen = seen.lock().unwrap(); + assert!(seen.iter().all(|line| line["method"] == "auth.challenge"), "nothing after the challenge: {seen:?}"); +} + +/// Switch off: the app doesn't listen (`materialcraft_ui_egui::agents` tests that side), so the +/// session works without a window and says why the window tools can't run. +#[tokio::test(flavor = "multi_thread")] +async fn live_without_the_switch_works_without_a_window() { + let dir = tempfile::tempdir().unwrap(); + save_agent_settings(dir.path(), json!({"whenAppClosed": "error"})); + let m = live(dir.path(), || false); + let list = m.command_list(Parameters(FilterParams::default())).await.unwrap(); + assert_ne!(list.is_error, Some(true), "{list:?}"); + let r = m.ui_inspect().await.unwrap(); + assert_eq!(r.is_error, Some(true)); + assert!(text(&r).contains("open MaterialCraft window"), "{r:?}"); +} + +/// Switch on but the app closed (a connection file a crashed launch left, nothing listening): the +/// closed-app choice saved in Edit › Preferences › AI Agents decides. +#[tokio::test(flavor = "multi_thread")] +async fn live_with_the_app_closed_follows_the_saved_choice() { + let dir = tempfile::tempdir().unwrap(); + let gone = TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + publish(dir.path(), gone); + + save_agent_settings(dir.path(), json!({"whenAppClosed": "error"})); + let r = live(dir.path(), || true).command_list(Parameters(FilterParams::default())).await.unwrap(); + assert_eq!(r.is_error, Some(true), "{r:?}"); + assert!(text(&r).contains("MaterialCraft isn't running"), "{r:?}"); + + save_agent_settings(dir.path(), json!({"whenAppClosed": "headless"})); + let r = live(dir.path(), || true).command_list(Parameters(FilterParams::default())).await.unwrap(); + assert_ne!(r.is_error, Some(true), "{r:?}"); +} + +/// Without a window and with agents let in, the session works in the app's agent folders (the +/// default one for an empty setting): `agent_folders` names them, and files are saved there only. +#[tokio::test(flavor = "multi_thread")] +async fn a_headless_session_saves_only_in_the_agent_folder() { + let dir = tempfile::tempdir().unwrap(); + let dir = dir.path(); + save_agent_settings(dir, json!({"whenAppClosed": "headless"})); + let m = live(dir, || true); + let r = m.agent_folders().await.unwrap(); + let v: Value = serde_json::from_str(&r.content[0].as_text().unwrap().text).unwrap(); + let agents = agent_folder(dir); + assert_eq!(v["write_folder"], json!(agents.to_string_lossy()), "{v}"); + assert_eq!(v["confined"], true, "{v}"); + + let saved = m.package_save(Parameters(SaveParams { path: Some("made.sbs".into()) })).await.unwrap(); + assert_ne!(saved.is_error, Some(true), "{saved:?}"); + assert!(agents.join("made.sbs").is_file()); + let outside = dir.join("outside.sbs").to_string_lossy().into_owned(); + let refused = m.package_save(Parameters(SaveParams { path: Some(outside) })).await.unwrap(); + assert_eq!(refused.is_error, Some(true), "saved outside the agent folder: {refused:?}"); + assert!(!dir.join("outside.sbs").exists()); + let _ = std::fs::remove_dir_all(agents); +} diff --git a/crates/automation/src/server/material_craft_mcp.rs b/crates/automation/src/server/material_craft_mcp.rs index 387e02a0d..2e1a59a44 100644 --- a/crates/automation/src/server/material_craft_mcp.rs +++ b/crates/automation/src/server/material_craft_mcp.rs @@ -11,10 +11,24 @@ use serde_json::{Value, json}; use crate::budgets::{MAX_PNG_SIDE, check_png, fit_png, json_text}; use crate::headless::batch_reply; +use crate::live::{Live, LiveConfig, Target}; use crate::security::MAX_BATCH_STEPS; use crate::workspace::authorize_command; use crate::{AutomationError, BridgeClient, Headless, bad}; +/// Where one tool call runs, found once per call ([`MaterialCraftMcp::on`]). A call made of several +/// requests (a batch) keeps it, so a live session that finds the app gone halfway doesn't finish the +/// call in another session. +#[derive(Clone)] +enum On { + /// An in-process session; `folders` is its `agent_folders` answer. + Session(Arc>, Option), + /// An app started with `--control`: path tools are refused here, the app has no folders. + Bridge(Arc), + /// The open window's agent server: the window holds requests to the agent folders itself. + Window(Arc), +} + #[derive(Clone)] pub struct MaterialCraftMcp { backend: Arc, @@ -69,6 +83,12 @@ impl MaterialCraftMcp { Self::with_backend(Backend::Bridge(Arc::new(client))) } + /// Plain `mcp` with the suite's `AI-MCP` flag: the open window while agents may use it, + /// otherwise headless ([`crate::live`]). + pub fn live(config: LiveConfig) -> Self { + Self::with_backend(Backend::Live(Arc::new(Live::new(config)))) + } + pub fn with_backend(backend: Backend) -> Self { MaterialCraftMcp { backend: Arc::new(backend), tool_router: Self::tool_router() } } @@ -80,21 +100,43 @@ impl MaterialCraftMcp { Ok(()) } - fn is_bridge(&self) -> bool { - matches!(*self.backend, Backend::Bridge(_)) + /// Where the next call runs. A live session looks for the app first (or applies the closed-app + /// choice); its error tells the agent what to do. + async fn on(&self) -> Result { + match &*self.backend { + Backend::Headless(h) => Ok(On::Session(h.clone(), None)), + Backend::Bridge(b) => Ok(On::Bridge(b.clone())), + Backend::Live(live) => match live.resolve().await.map_err(AutomationError::Other)? { + Target::Window(b) => Ok(On::Window(b)), + Target::Headless(h) => Ok(On::Session(h.session.clone(), Some(h.folders.clone()))), + }, + } } /// One control-channel method on the backend async fn call(&self, method: &str, p: Value) -> Result { - match &*self.backend { - Backend::Headless(h) => { + let on = self.on().await?; + self.call_on(&on, method, p).await + } + + /// One control-channel method where `on` says + async fn call_on(&self, on: &On, method: &str, p: Value) -> Result { + match on { + On::Session(h, _) => { let (h, m) = (h.clone(), method.to_string()); // Edits run on snapshots (`Session::edit`), so a panicking command leaves the session consistent: keep serving after a poisoned lock tokio::task::spawn_blocking(move || h.lock().unwrap_or_else(PoisonError::into_inner).handle(&m, &p)) .await .unwrap_or_else(|_| Err(AutomationError::Other(format!("internal error in `{method}`")))) } - Backend::Bridge(b) => match method { + // The window refuses host paths and opens and saves files in the agent folders itself. + On::Window(b) => match method { + "command.batch" | "render" => { + Err(bad(format!("`{method}` runs without a window; in the open window use command_run, view_screenshot and ui_screenshot"))) + } + _ => b.call(method, p).await, + }, + On::Bridge(b) => match method { "command.run" => { let id = p.get("id").and_then(Value::as_str).unwrap_or_default(); authorize_command(id, p.get("params").unwrap_or(&Value::Null))?; @@ -114,12 +156,38 @@ impl MaterialCraftMcp { } async fn bridge_only(&self, method: &str, p: Value) -> Result { - if self.is_bridge() { - self.call(method, p).await - } else { - Err(bad(format!( - "`{method}` needs the running app: start `materialcraft --control ` and run `materialcraft-cli mcp --bridge ` (headless renders: view_render)" - ))) + match self.on().await? { + on @ (On::Bridge(_) | On::Window(_)) => self.call_on(&on, method, p).await, + On::Session(..) => Err(bad(self.no_window(method))), + } + } + + /// Why a tool that needs the open window has none in this session. + fn no_window(&self, method: &str) -> String { + match &*self.backend { + Backend::Live(_) => format!( + "`{method}` needs the open MaterialCraft window, and this MCP session works without one: the ArtCraft Launcher's AI agents \ + switch doesn't let agents use MaterialCraft, or MaterialCraft was closed and Edit › Preferences › AI Agents › When \ + MaterialCraft Is Closed is set to work without a window (or `--when-closed headless`). The session stays without a window; \ + start a new MCP session once MaterialCraft is open (headless renders: view_render)" + ), + _ => format!( + "`{method}` needs the open MaterialCraft window: turn on ArtCraft Launcher › Settings › AI agents for MaterialCraft and run \ + plain `materialcraft-cli mcp` (without --headless; headless renders: view_render)" + ), + } + } + + /// `agent_folders`: the folders this session opens and saves files in. + async fn folders(&self) -> Result { + match self.on().await? { + On::Window(b) => b.call(crate::agents::FOLDERS_METHOD, json!({})).await, + On::Session(_, Some(folders)) => Ok(folders), + On::Session(_, None) | On::Bridge(_) => Ok(json!({ + "read_folder": null, + "write_folder": null, + "note": "This session has no agent folders: its file tools use the folders it was started with (--automation-read-root, --automation-write-root), or none.", + })), } } } @@ -151,11 +219,15 @@ impl MaterialCraftMcp { if p.steps.len() > MAX_BATCH_STEPS { return Ok(fail(format!("at most {MAX_BATCH_STEPS} steps per batch"))); } - let reply = if self.is_bridge() { + let on = match self.on().await { + Ok(on) => on, + Err(e) => return Ok(fail(e)), + }; + let reply = if !matches!(on, On::Session(..)) { let mut results = Vec::new(); let mut failed = None; for (i, s) in p.steps.iter().enumerate() { - match self.call("command.run", params(s)).await { + match self.call_on(&on, "command.run", params(s)).await { Ok(v) => results.push(v), Err(e) => { failed = Some((i, s.id.as_str(), e.to_string())); @@ -165,7 +237,7 @@ impl MaterialCraftMcp { } batch_reply(results, failed) } else { - match self.call("command.batch", params(&p)).await { + match self.call_on(&on, "command.batch", params(&p)).await { Ok(v) => v, Err(e) => return Ok(fail(e)), } @@ -200,14 +272,14 @@ impl MaterialCraftMcp { } #[tool( - description = "Open an .sbs or .mcraft package (path relative to the read root). Returns the session; `package.warnings` lists unsupported content (missing nodes are kept as placeholders)." + description = "Open an .sbs or .mcraft package (path relative to the read root; in the open window, to the agent read folder that agent_folders names). Returns the session; `package.warnings` lists unsupported content (missing nodes are kept as placeholders)." )] async fn package_open(&self, Parameters(p): Parameters) -> Result { to_result(self.call("package.open", params(&p)).await) } #[tool( - description = "Save the package (path relative to the write root; omit to save to its own file). Writes .sbs XML with adjacent resources/ or a self-contained .mcraft ZIP. In bridge mode, saving without a path runs File > Save and returns an error while a dialog or prompt blocks it." + description = "Save the package (path relative to the write root; omit to save to its own file). Writes .sbs XML with adjacent resources/ or a self-contained .mcraft ZIP. In the open window, paths are relative to the agent write folder (agent_folders), and saving without a path saves the package's own file only when it is in that folder. With the deprecated bridge, saving without a path runs File > Save and returns an error while a dialog or prompt blocks it." )] async fn package_save(&self, Parameters(p): Parameters) -> Result { to_result(self.call("package.save", params(&p)).await) @@ -233,39 +305,47 @@ impl MaterialCraftMcp { } #[tool(description = "Headless: render the material on the 3D view's scene, or a node's output (view 2d), as a PNG up to \ - 2048 px a side. In bridge mode use view_screenshot.")] + 2048 px a side. In the open window use view_screenshot.")] async fn view_render(&self, Parameters(p): Parameters) -> Result { let note = format!("render {}", params(&p)); image_result(self.call("render", params(&p)).await, ¬e, false) } - #[tool(description = "Bridge mode: PNG of the live app's 3D or 2D view.")] + #[tool(description = "Open window (or bridge): PNG of the live app's 3D or 2D view.")] async fn view_screenshot(&self, Parameters(p): Parameters) -> Result { image_result(self.bridge_only("view.screenshot", params(&p)).await, "screenshot of an app view", true) } - #[tool(description = "Bridge mode: PNG of the whole app window (downscaled to 2048 px a side at most).")] + #[tool(description = "Open window (or bridge): PNG of the whole app window (downscaled to 2048 px a side at most).")] async fn ui_screenshot(&self) -> Result { image_result(self.bridge_only("ui.screenshot", json!({})).await, "screenshot of the app window", true) } - #[tool(description = "Bridge mode: the app's UI state (panels, windows, graph view camera, node rectangles on screen, toasts).")] + #[tool(description = "Open window (or bridge): the app's UI state (panels, windows, graph view camera, node rectangles on screen, toasts).")] async fn ui_inspect(&self) -> Result { to_result(self.bridge_only("ui.inspect", json!({})).await) } #[tool( - description = "Bridge mode: activate a menu item by id like a click (may open a window); returns an error while a dialog or prompt blocks it. ui.menu.list lists ids and which are enabled." + description = "Open window (or bridge): activate a menu item by id like a click (may open a window); returns an error while a dialog or prompt blocks it. ui.menu.list lists ids and which are enabled." )] async fn ui_menu_invoke(&self, Parameters(p): Parameters) -> Result { to_result(self.bridge_only("ui.menu.invoke", params(&p)).await) } - #[tool(description = "Bridge mode: synthesize mouse, keyboard and text input in the app window (clicks, drags between \ + #[tool(description = "Open window (or bridge): synthesize mouse, keyboard and text input in the app window (clicks, drags between \ node ports, scrolling, shortcuts, typing). Positions are window points (see ui_inspect for node rectangles).")] async fn ui_input(&self, Parameters(p): Parameters) -> Result { to_result(self.bridge_only("ui.input", params(&p)).await) } + + #[tool(description = "Where MaterialCraft opens and saves files for agents. Put files MaterialCraft should open in read_folder \ + (or a folder below it) and find what it saves in write_folder; the file tools take forward-slash paths relative to them. \ + Both are usually MaterialCraft's agent folder in Documents/ArtCraft/Agents; the person may have set others in Edit > \ + Preferences > AI Agents. null means there is no such folder now. `confined` says that MaterialCraft refuses paths outside them.")] + async fn agent_folders(&self) -> Result { + to_result(self.folders().await) + } } #[tool_handler( @@ -275,10 +355,16 @@ impl MaterialCraftMcp { (usages baseColor, normal, roughness, metallic, height, ambientOcclusion) make a PBR material. Start with graph_new \ (templates: empty, pbr, atomics) or package_open, browse nodes with library_list, build with node_add / node_connect \ / node_param (or command_run/command_batch for anything else: command_list), check your work with session_inspect and \ - view_render (3d, or 2d for one node), then package_save, outputs_export or material_export. Undo: command_run edit.undo." + view_render (3d, or 2d for one node), then package_save, outputs_export or material_export. Undo: command_run edit.undo. \ + `agent_folders` tells where to put files for MaterialCraft and where it saves; with the open app the `ui_*` and \ + `view_screenshot` tools show its window." )] impl ServerHandler for MaterialCraftMcp {} +#[cfg(test)] +#[path = "live_tests.rs"] +mod live_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/automation/src/server/mod.rs b/crates/automation/src/server/mod.rs index 29444de26..3fbd508da 100644 --- a/crates/automation/src/server/mod.rs +++ b/crates/automation/src/server/mod.rs @@ -1,3 +1,8 @@ +//! The MCP server (rmcp). Tool names are `snake_case`; each tool maps to one control-channel +//! method (see [`crate::rpc`]), answered in process (headless), by the open window while the +//! ArtCraft Launcher's switch lets agents use it ([`crate::live`]), or by an app started with +//! `materialcraft --control` (bridge, deprecated). + mod backend; mod material_craft_mcp; mod parameter; diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs index f3870e7af..f4bf3c97b 100644 --- a/crates/automation/src/workspace.rs +++ b/crates/automation/src/workspace.rs @@ -20,6 +20,9 @@ pub struct AuthorizedWorkspace { read_path: Option, write: Option>, write_path: Option, + /// A folder nothing may be written in, canonical: the app's settings folder, which a write + /// root chosen wide may hold ([`Self::denying_writes_in`]). + denied_write: Option, } impl AuthorizedWorkspace { @@ -28,7 +31,30 @@ impl AuthorizedWorkspace { let read_path = read_root.map(std::fs::canonicalize).transpose().map_err(|e| bad(e.to_string()))?; let write = open_root(write_root, "write")?; let write_path = write_root.map(std::fs::canonicalize).transpose().map_err(|e| bad(e.to_string()))?; - Ok(Self { read, read_path, write, write_path }) + Ok(Self { read, read_path, write, write_path, denied_write: None }) + } + + /// The same roots with nothing written in `dir` or below it (an app's settings folder, where the + /// agent settings choose these very folders). A write root inside `dir` can't be written at all. + pub fn denying_writes_in(mut self, dir: &Path) -> Self { + self.denied_write = Some(canonical_lenient(dir)); + self + } + + /// Refuses `rel` (already validated) when it lies in the folder writes are denied in. The deepest + /// part of `rel` that exists is resolved inside the write capability, so a link below the root + /// can't stand in for the denied folder. + fn check_guard(&self, root: &Dir, rel: &Path, path: &str) -> Result<(), AutomationError> { + let (Some(denied), Some(base)) = (&self.denied_write, &self.write_path) else { return Ok(()) }; + let resolved = rel.ancestors().find_map(|ancestor| { + let existing = if ancestor.as_os_str().is_empty() { Path::new(".") } else { ancestor }; + let rest = rel.strip_prefix(ancestor).ok()?; + root.canonicalize(existing).ok().map(|found| base.join(found).join(rest)) + }); + if inside(&resolved.unwrap_or_else(|| base.join(rel)), denied) { + return Err(bad(format!("`{path}` is in MaterialCraft's settings folder, which agents can't write to"))); + } + Ok(()) } /// Engine identities are absolute. Actual dependency reads still go through the directory capability. @@ -71,7 +97,10 @@ impl AuthorizedWorkspace { // Writes through this handle no longer traverse the original directory alias let dir = root.open_dir(&resolved_ancestor).map_err(|error| file_error("resolve destination", path, error))?; let destination = write_path.join(relative); - let workspace = Self { write: Some(Arc::new(dir)), write_path: Some(write_path), ..Self::default() }; + let workspace = Self { write: Some(Arc::new(dir)), write_path: Some(write_path), denied_write: self.denied_write.clone(), ..Self::default() }; + if workspace.denied_write.as_deref().is_some_and(|denied| inside(&destination, denied)) { + return Err(bad(format!("`{path}` is in MaterialCraft's settings folder, which agents can't write to"))); + } Ok((destination, workspace, save_path)) } @@ -111,6 +140,7 @@ impl AuthorizedWorkspace { pub fn write(&self, path: &str, bytes: &[u8]) -> Result<(), AutomationError> { let rel = relative_path(path)?; let root = self.write.as_ref().ok_or_else(|| denied("write"))?; + self.check_guard(root, &rel, path)?; let leaf = rel.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); let tmp = rel.with_file_name(format!(".{leaf}.{}.tmp", std::process::id())); let mut options = OpenOptions::new(); @@ -131,14 +161,16 @@ impl AuthorizedWorkspace { /// Validate the write capability and relative path before cooking pub fn check_write(&self, path: &str) -> Result<(), AutomationError> { - relative_path(path)?; - self.write.as_ref().map(|_| ()).ok_or_else(|| denied("write")) + let rel = relative_path(path)?; + let root = self.write.as_ref().ok_or_else(|| denied("write"))?; + self.check_guard(root, &rel, path) } /// Create a directory and its parents below the write root pub fn create_dir_all(&self, path: &str) -> Result<(), AutomationError> { let rel = relative_path(path)?; let root = self.write.as_ref().ok_or_else(|| denied("write"))?; + self.check_guard(root, &rel, path)?; root.create_dir_all(&rel).map_err(|e| file_error("create", path, e)) } @@ -146,6 +178,7 @@ impl AuthorizedWorkspace { pub fn write_resource(&self, path: &str, bytes: &[u8]) -> Result<(), AutomationError> { let rel = relative_path(path)?; let root = self.write.as_ref().ok_or_else(|| denied("write"))?; + self.check_guard(root, &rel, path)?; let mut options = OpenOptions::new(); options.write(true).create_new(true); match root.open_with(&rel, &options) { @@ -205,6 +238,30 @@ fn regular_read_options() -> OpenOptions { options } +/// `path` canonical where it exists: its deepest existing ancestor resolved, the rest appended. +fn canonical_lenient(path: &Path) -> PathBuf { + path.ancestors() + .find_map(|ancestor| { + let found = std::fs::canonicalize(ancestor).ok()?; + Some(found.join(path.strip_prefix(ancestor).ok()?)) + }) + .unwrap_or_else(|| path.to_path_buf()) +} + +/// Whether `path` is `dir` or below it; letter case is ignored where the file system ignores it. +fn inside(path: &Path, dir: &Path) -> bool { + let parts = |p: &Path| -> Vec { + p.components() + .map(|c| { + let part = c.as_os_str().to_string_lossy(); + if cfg!(any(windows, target_os = "macos")) { part.to_lowercase() } else { part.into_owned() } + }) + .collect() + }; + let (path, dir) = (parts(path), parts(dir)); + path.len() >= dir.len() && path[..dir.len()] == dir[..] +} + fn open_root(path: Option<&Path>, authority: &str) -> Result>, AutomationError> { let Some(path) = path else { return Ok(None) }; if path.as_os_str().is_empty() { @@ -265,7 +322,9 @@ fn file_error(op: &str, path: &str, e: std::io::Error) -> AutomationError { /// Route file access through the workspace boundary pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError> { - let has_path = ["path", "dir"].iter().any(|k| params.get(k).is_some_and(|v| !v.is_null())); + let has_path = ["path", "dir"].iter().any(|k| params.get(k).is_some_and(|v| !v.is_null())) + // The 2D view's background image is a file the window reads when it draws + || (id == "view.2d" && params.get("background").is_some_and(|v| !v.is_null())); let ok = match id { "material.cook" => !has_path && params.get("inputs").is_none_or(|v| v.is_null() || v.as_object().is_some_and(|o| o.is_empty())), "file.new" | "file.newPackage" | "file.newAtomicSample" => !has_path, @@ -465,6 +524,8 @@ mod tests { assert!(authorize_command(id, &json!({"dir": "/etc"})).is_err(), "{id}"); } assert!(authorize_command("file.new", &json!({"template": "atomics"})).is_ok()); + assert!(authorize_command("view.2d", &json!({"background": "/etc/x.png"})).is_err(), "the 2D view reads its background image"); + assert!(authorize_command("view.2d", &json!({"background": null, "tiling": true})).is_ok(), "clearing it reads nothing"); assert!(authorize_command("graph.node.add", &json!({"def": "blur", "path": null})).is_ok()); } diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 9104a4416..12b308441 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -35,6 +35,12 @@ sha2 = { workspace = true } sys-locale = "0.3" craft-update = { workspace = true } craft-dialogs = { workspace = true } +# Agents in the open window: the agent link (control server, token, connection file), the launcher's +# switch and the AI Agents page of Preferences (agents.rs); the agent folders and the file tools' code +# the window runs agent requests with. The web build has no control server. +craft-automation = { workspace = true, features = ["ui", "agents"] } +craft-control = { workspace = true, features = ["agents"] } +materialcraft-automation = { workspace = true } # Browser file I/O (web_files.rs): async pickers and Blob downloads. [target.'cfg(target_arch = "wasm32")'.dependencies] diff --git a/crates/ui-egui/src/agents.rs b/crates/ui-egui/src/agents.rs new file mode 100644 index 000000000..ea337c7c6 --- /dev/null +++ b/crates/ui-egui/src/agents.rs @@ -0,0 +1,303 @@ +//! Agents in the open window. While the ArtCraft Launcher's switch (Settings › AI agents) lets agents +//! use MaterialCraft, the window serves its control channel on loopback for them, with a token kept +//! in its settings folder, and publishes where in `agent-connection.json` beside it; +//! `materialcraft-cli mcp` reads that file on every tool call. When the switch turns off, the server +//! stops and the file goes, without a restart. The link, the switch and the AI Agents page are the +//! framework's (`craft_automation::agents`, `craft_automation::ui::agents`); MaterialCraft runs the +//! requests through its own control methods ([`crate::control`]) and holds them to the agent +//! folders: the folders set in Edit › Preferences › AI Agents, or +//! `Documents/ArtCraft/Agents/MaterialCraft` for an empty one ([`AgentScope`]). +//! +//! `materialcraft --control` manages its own server for the whole run instead; the AI Agents page +//! then says the launch options manage the connection. + +use std::path::PathBuf; +use std::sync::Arc; + +use craft_automation::ControlChannel; +use craft_automation::agents::{AgentLink, AgentLinkStatus, AgentSettings, AgentSwitch, LinkProblem}; +use craft_control::agents::AgentFolders; +use craft_ui::patterns::preferences::SettingsDraft; +use craft_ui::runtime::windows::WindowHost; +use materialcraft_automation::AuthorizedWorkspace; +use materialcraft_automation::agents::APP_NAME; +use serde_json::{Value, json}; + +use crate::control::ControlRequest; + +/// Saves the agent settings where `materialcraft-cli mcp` reads them; `Err` says why it couldn't. +pub type SaveFn = Box Result<(), String>>; + +/// The key the AI Agents page keeps the agent settings under in its draft. +const PAGE: &str = "agents"; + +/// What an agent request may do with files: open and save only below the agent folders. +pub struct AgentScope { + /// The folders as the person set them (the default agent folder for an empty one), for + /// `agent_folders` and the paths the window shows. + pub folders: AgentFolders, + pub workspace: AuthorizedWorkspace, +} + +impl AgentScope { + /// The scope of `folders`, with nothing written in the settings folder `settings`. + pub fn new(folders: AgentFolders, settings: Option<&std::path::Path>) -> Result { + let workspace = materialcraft_automation::agents::workspace(&folders, settings).map_err(|e| e.to_string())?; + Ok(AgentScope { folders, workspace }) + } + + /// The folder agents open files from (the write folder when there is none). + pub fn read_folder(&self) -> Option<&std::path::Path> { + self.folders.read.as_deref().or(self.folders.write.as_deref()) + } + + /// The folder agents save to. + pub fn write_folder(&self) -> Option<&std::path::Path> { + self.folders.write.as_deref() + } +} + +/// The agents link of the open window. +pub struct Agents { + /// The link; `None` while the launch options (`--control`) manage the control channel. + link: Option, + /// The status shown while the launch options manage the control channel. + launch: AgentLinkStatus, + switch: AgentSwitch, + settings: AgentSettings, + /// The settings folder: the link's token and connection file, and the agent settings. + dir: Option, + save: SaveFn, + channel: Option, + /// What agent requests may do now; `None` until the link runs. + scope: Option>, + default_folder: Option, + /// The AI Agents page's working copy while Preferences is open. + draft: Option, +} + +impl Agents { + /// The link for the window, keeping its token and connection file in the settings folder + /// `dir`, naming `app` (the version string) in the connection file, following `switch` with the + /// saved `settings`; `save` stores the settings when Edit › Preferences › AI Agents changes them. + pub fn new(dir: Option, app: String, switch: AgentSwitch, settings: AgentSettings, save: SaveFn) -> Self { + Self { + link: Some(AgentLink::new(dir.clone(), app)), + launch: AgentLinkStatus::default(), + switch, + settings, + dir, + save, + channel: None, + scope: None, + default_folder: craft_control::agents::default_folder(APP_NAME), + draft: None, + } + } + + /// The window was started with `--control port`: that channel stays as it is for the whole run + /// and the AI Agents page says the launch options manage it. + pub fn launched_with_control(mut self, port: u16) -> Self { + self.link = None; + self.launch.port = Some(port); + self.launch.launch_flags = true; + self + } + + /// `default` replaces the default agent folder (tests). + pub fn with_default_folder(mut self, default: Option) -> Self { + self.default_folder = default; + self + } + + /// The saved agent settings. + pub fn settings(&self) -> &AgentSettings { + &self.settings + } + + /// Where the link stands, for the AI Agents page and `ui.inspect`. + pub fn status(&self) -> &AgentLinkStatus { + self.link.as_ref().map_or(&self.launch, AgentLink::status) + } + + /// The suite's `AI-MCP` flag: the launcher's switch decides, and Preferences shows the AI Agents page. + pub fn mcp_flag(&self) -> bool { + self.switch.mcp_flag() + } + + /// Whether the launcher's switch lets agents use MaterialCraft now. + pub fn allowed(&self) -> bool { + // MaterialCraft had no agent consent of its own before the switch. + self.switch.allows(false) + } + + /// Saves `settings` and applies them on the next [`Self::sync`]. + pub fn set(&mut self, settings: AgentSettings) -> Result<(), String> { + (self.save)(&settings)?; + self.settings = settings; + Ok(()) + } + + /// Where the link stands, the switch and the folders, for `ui.inspect`. + pub fn inspect(&self) -> Value { + let mut v = serde_json::to_value(self.status()).unwrap_or(Value::Null); + v["mcpFlag"] = json!(self.mcp_flag()); + v["allowed"] = json!(self.allowed()); + v + } + + /// The AI Agents page of Preferences over its working copy (made from the saved settings the + /// first time the page shows). + pub(crate) fn page(&mut self, ui: &mut egui::Ui) { + let status = self.link.as_ref().map_or(&self.launch, AgentLink::status); + let settings = &self.settings; + let draft = self.draft.get_or_insert_with(|| { + let mut draft = SettingsDraft::default(); + if let Err(error) = draft.replace(&json!({ PAGE: settings })) { + log::warn!("the agent settings could not be shown: {error}"); + } + draft + }); + craft_automation::ui::agents::AgentsPage::new(PAGE, draft, status).mcp_flag(true).show(ui); + } + + /// The settings the AI Agents page shows, when they differ from the saved ones. + pub(crate) fn edited(&self) -> Option { + self.draft.as_ref().and_then(|draft| draft.get::(PAGE)).filter(|next| next != &self.settings) + } + + /// Preferences closed (or Cancel): the page's working copy goes, the next opening starts from + /// the saved settings. + pub(crate) fn discard_draft(&mut self) { + self.draft = None; + } + + /// Once per frame: brings the link in line with the switch and the settings (the control server + /// starts, moves or stops, and the agent folders are opened again when they changed), then hands + /// over the requests its server received as the app's own control requests, each with what it may + /// do. + pub(crate) fn sync(&mut self, ctx: &egui::Context) -> Vec { + let allowed = self.allowed(); + let Some(link) = self.link.as_mut() else { return Vec::new() }; + let update = link.sync(allowed.then_some(&self.settings), &WindowHost::of(ctx)); + if update.stopped { + self.channel = None; + } + if let Some(requests) = update.requests { + self.channel = Some(ControlChannel::new(requests)); + } + if update.changed { + self.scope = None; + if link.status().port.is_some() { + let folders = self.settings.folders_with(self.default_folder.as_deref()); + let settings_dir = self.dir.as_deref(); + let scope = AgentScope::new(folders, settings_dir).or_else(|e| { + link.note(LinkProblem::App(format!("Agents can't open or save files: {e}"))); + AgentScope::new(AgentFolders::default(), settings_dir) + }); + self.scope = scope.ok().map(Arc::new); + } + } + // Without a scope nothing an agent sends may run. + let (Some(scope), Some(channel)) = (self.scope.as_ref(), self.channel.as_mut()) else { return Vec::new() }; + std::iter::from_fn(|| channel.next_request()).map(|r| ControlRequest::for_agent(r.method, r.params, r.reply, scope.clone())).collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use craft_control::agents::{CONNECTION_FILE, TOKEN_FILE, read_connection}; + use std::path::Path; + use std::time::{Duration, Instant}; + + fn agents(dir: &Path, switch: AgentSwitch) -> Agents { + Agents::new(Some(dir.to_path_buf()), "MaterialCraft test".into(), switch, AgentSettings::default(), Box::new(|_| Ok(()))) + .with_default_folder(Some(dir.join("Agents"))) + } + + type Conn = (std::io::BufReader, std::net::TcpStream); + + /// One line out, one line back. + fn round_trip(conn: &mut Conn, request: Value) -> Value { + use std::io::{BufRead, Write}; + writeln!(conn.1, "{request}").unwrap(); + let mut line = String::new(); + conn.0.read_line(&mut line).unwrap(); + serde_json::from_str(&line).unwrap_or(Value::Null) + } + + /// A connection to the window's agent server, signed in with `token` through the challenge + /// handshake; `Err` with the refusal when the window doesn't accept the proof. + fn signed_in(port: u16, token: &str) -> Result { + use craft_automation::security::{self, ProofRole}; + let stream = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap(); + stream.set_read_timeout(Some(Duration::from_secs(20))).unwrap(); + let mut conn = (std::io::BufReader::new(stream.try_clone().unwrap()), stream); + let client_nonce = security::generate_nonce().unwrap(); + let challenge = round_trip(&mut conn, json!({"id": 0, "method": security::CHALLENGE_METHOD, "params": {"clientNonce": client_nonce}})); + let server_nonce = challenge["result"]["serverNonce"].as_str().unwrap().to_string(); + let proof = security::handshake_proof(token, ProofRole::Client, &client_nonce, &server_nonce).unwrap(); + let auth = round_trip(&mut conn, json!({"id": 0, "method": security::AUTH_METHOD, "params": {"proof": proof}})); + if auth["ok"] == true { Ok(conn) } else { Err(auth) } + } + + /// The link follows the launcher's switch without a restart: on, it listens and publishes the + /// connection, and a signed-in client's request reaches the app with the agent folders attached; + /// a wrong token is refused; off, the server stops and the connection file goes. + #[test] + fn the_link_follows_the_switch_and_hands_requests_to_the_app() { + let dir = tempfile::tempdir().unwrap(); + let dir = dir.path(); + let ctx = egui::Context::default(); + crate::framework::install_headless(&ctx); + let mut on = agents(dir, AgentSwitch::fixed(true, true)); + assert!(on.sync(&ctx).is_empty()); + let port = on.status().port.expect("listening while the switch allows"); + assert!(read_connection(dir).unwrap().is_some_and(|c| c.port == port), "the CLI finds the window through the connection file"); + + let token = std::fs::read_to_string(dir.join(TOKEN_FILE)).unwrap().trim().to_string(); + let client = std::thread::spawn(move || { + let stranger = signed_in(port, &craft_automation::security::generate_token().unwrap()).expect_err("a wrong token was accepted"); + let mut conn = signed_in(port, &token).expect("the window's own token was refused"); + (stranger, round_trip(&mut conn, json!({"id": 1, "method": "ping", "params": {}}))) + }); + let deadline = Instant::now() + Duration::from_secs(20); + let request = loop { + if let Some(request) = on.sync(&ctx).pop() { + break request; + } + assert!(Instant::now() < deadline, "the request never reached the app"); + std::thread::sleep(Duration::from_millis(10)); + }; + assert_eq!(request.method, "ping"); + let scope = request.agent.clone().expect("an agent request carries its folders"); + assert_eq!(scope.write_folder(), Some(dir.join("Agents").as_path()), "an empty setting is the default agent folder"); + request.reply.send(json!({"ok": true, "result": "pong"})).unwrap(); + let (stranger, pong) = client.join().unwrap(); + assert_eq!(stranger["ok"], false, "{stranger}"); + assert_eq!(pong["result"], "pong", "{pong}"); + + on.switch = AgentSwitch::fixed(true, false); + on.sync(&ctx); + assert_eq!(on.status().port, None, "stopped when the switch turned off"); + assert!(!dir.join(CONNECTION_FILE).exists(), "and its connection file is gone"); + } + + /// Without the suite's `AI-MCP` flag MaterialCraft takes no agents this way: it had no consent of + /// its own before the launcher's switch. With `--control` the launch options manage the channel. + #[test] + fn without_the_flag_or_with_control_nothing_listens() { + let dir = tempfile::tempdir().unwrap(); + let dir = dir.path(); + let ctx = egui::Context::default(); + crate::framework::install_headless(&ctx); + let mut off = agents(dir, AgentSwitch::fixed(false, true)); + off.sync(&ctx); + assert_eq!(off.status().port, None); + let mut control = agents(dir, AgentSwitch::fixed(true, true)).launched_with_control(7); + control.sync(&ctx); + assert!(control.status().launch_flags); + assert!(!dir.join(CONNECTION_FILE).exists()); + } +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index c42ff15d1..4eb4708e4 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -15,6 +15,12 @@ //! - `view.screenshot {view?: "3d"|"2d"}`: PNG of a view, base64. //! - `ui.screenshot`: PNG of the whole window (replies after the next frame). //! - `ui.resize {width, height}`: the window's inner size in points. +//! +//! Requests from agents (the ArtCraft Launcher's switch, [`crate::agents`]) also have +//! `agent.folders` and the file tools' methods (`package.open`, `package.save`, `bitmap.import`, +//! `outputs.export`, `material.export`), which open and save files only below the agent folders; +//! host paths, menu items that write the package's own file and UI state that names files are +//! refused for them, also for the clicks and shortcuts their `ui.input` makes ([`handle_agent`]). use std::sync::mpsc::{Receiver, Sender, channel}; @@ -28,12 +34,31 @@ pub struct ControlRequest { pub method: String, pub params: Value, pub reply: Sender, + /// An agent's request (the open window's agent link) and the folders it is held to; `None` for + /// the person's own `--control` channel. + #[cfg(not(target_arch = "wasm32"))] + pub agent: Option>, } impl ControlRequest { pub fn new(method: String, params: Value) -> (ControlRequest, Receiver) { let (tx, rx) = channel(); - (ControlRequest { method, params, reply: tx }, rx) + ( + ControlRequest { + method, + params, + reply: tx, + #[cfg(not(target_arch = "wasm32"))] + agent: None, + }, + rx, + ) + } + + /// An agent's request, held to the folders of `scope`. + #[cfg(not(target_arch = "wasm32"))] + pub fn for_agent(method: String, params: Value, reply: Sender, scope: std::sync::Arc) -> ControlRequest { + ControlRequest { method, params, reply, agent: Some(scope) } } } @@ -52,22 +77,217 @@ fn err(e: impl std::fmt::Display) -> Value { } pub fn poll(app: &mut MaterialCraftApp, ctx: &egui::Context) { - let Some(rx) = app.control.as_ref() else { return }; - let reqs: Vec = rx.try_iter().collect(); + // The `--control` channel and the agent link's server (the ArtCraft Launcher's switch) feed the same method table + let own: Vec = app.control.as_ref().map(|rx| rx.try_iter().collect()).unwrap_or_default(); + let reqs: Vec = own.into_iter().chain(agent_requests(app, ctx)).collect(); for r in reqs { + #[cfg(not(target_arch = "wasm32"))] + let fit = r.agent.is_some(); + #[cfg(target_arch = "wasm32")] + let fit = false; if r.method == "ui.screenshot" { // Captured from the UI pass (`request_screenshots`), where viewport commands land - app.pending_screenshots.push(r.reply); + app.pending_screenshots.push((r.reply, fit)); ctx.request_repaint(); continue; } + #[cfg(not(target_arch = "wasm32"))] + let reply = match &r.agent { + Some(scope) => handle_agent(app, ctx, &r.method, &r.params, scope), + None => handle(app, ctx, &r.method, &r.params), + }; + #[cfg(target_arch = "wasm32")] let reply = handle(app, ctx, &r.method, &r.params); let _ = r.reply.send(reply); ctx.request_repaint(); } } +/// This frame's requests from the agent link (the ArtCraft Launcher's switch). +#[cfg(not(target_arch = "wasm32"))] +fn agent_requests(app: &mut MaterialCraftApp, ctx: &egui::Context) -> Vec { + app.agents.as_mut().map(|agents| agents.sync(ctx)).unwrap_or_default() +} + +#[cfg(target_arch = "wasm32")] +fn agent_requests(_: &mut MaterialCraftApp, _: &egui::Context) -> Vec { + Vec::new() +} + +/// Agents in the open window: where the link stands (`port`, `launchFlags`, `problem`), the suite's +/// `AI-MCP` flag and whether the launcher's switch lets agents in now; `null` without a link. +#[cfg(not(target_arch = "wasm32"))] +fn agents_state(app: &MaterialCraftApp) -> Value { + app.agents.as_ref().map_or(Value::Null, crate::agents::Agents::inspect) +} + +#[cfg(target_arch = "wasm32")] +fn agents_state(_: &MaterialCraftApp) -> Value { + Value::Null +} + +/// A screenshot reply: `{width, height, png}` with the PNG in base64. `fit` downscales it to the +/// size an agent's reply may have (the agent link's server sends at most 8 MiB per reply). +fn png_reply(w: u32, h: u32, png: Vec, fit: bool) -> Result { + #[cfg(not(target_arch = "wasm32"))] + let (w, h, png) = if fit { + use materialcraft_automation::budgets::{MAX_PNG_SIDE, fit_png}; + let png = fit_png(png, MAX_PNG_SIDE).map_err(|e| e.to_string())?; + // The size from the refit PNG's header (IHDR: width and height, big-endian, at bytes 16 and 20) + let at = |i: usize| png.get(i..i + 4).and_then(|b| b.try_into().ok()).map(u32::from_be_bytes); + (at(16).unwrap_or(w), at(20).unwrap_or(h), png) + } else { + (w, h, png) + }; + #[cfg(target_arch = "wasm32")] + let _ = fit; + Ok(json!({ "width": w, "height": h, "png": base64::engine::general_purpose::STANDARD.encode(png) })) +} + +/// The file tools' methods: an agent opens and saves files only below its agent folders. +#[cfg(not(target_arch = "wasm32"))] +const AGENT_FILE_METHODS: [&str; 5] = ["package.open", "package.save", "bitmap.import", "outputs.export", "material.export"]; + +/// Menu items that write a package's own file, or hand it to another program, without asking where. +#[cfg(not(target_arch = "wasm32"))] +const WRITES_OWN_FILE: [&str; 3] = ["file.save", "file.saveAll", "file.sendToTextureCraft"]; + +/// UI state that names files and folders on this computer (the recent list, the Export window's +/// destinations): an agent's `ui.set` may not change it. +#[cfg(not(target_arch = "wasm32"))] +const NAMES_FILES: [&str; 3] = ["recent", "export", "exportDraft"]; + +/// An agent's request: the agent folders' file tools, and the methods every caller has with what +/// could reach files outside the agent folders refused. What it starts runs as agent-driven +/// ([`MaterialCraftApp::agent_driven`]), and so do the frames of input it queues. The person's own +/// `--control` channel is [`handle`]. +#[cfg(not(target_arch = "wasm32"))] +pub fn handle_agent(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, params: &Value, scope: &crate::agents::AgentScope) -> Value { + let id = params.get("id").and_then(Value::as_str).unwrap_or_default(); + let refused = match method { + materialcraft_automation::agents::FOLDERS_METHOD => return ok(materialcraft_automation::agents::folders_answer(&scope.folders)), + m if AGENT_FILE_METHODS.contains(&m) => return agent_files(app, m, params, scope).map_or_else(err, ok), + "command.run" => materialcraft_automation::workspace::authorize_command(id, params.get("params").unwrap_or(&Value::Null)).err().map(|e| e.to_string()), + "ui.menu.invoke" if WRITES_OWN_FILE.contains(&id) => Some(format!( + "`{id}` writes a package's own file, which may be outside the agent folders: use package_save with a path relative to the write folder (agent_folders)" + )), + "ui.set" => NAMES_FILES.iter().find(|key| params.get(**key).is_some()).map(|key| { + format!("agents can't set `{key}`: it names files and folders on this computer; use the file tools with paths relative to the agent folders (agent_folders)") + }), + "view.screenshot" => { + let shown = if params.get("view").and_then(Value::as_str) == Some("2d") { &app.view2d.shown } else { &app.view3d.shown }; + return match shown.as_ref().and_then(|(w, h, px)| encode_png(*w, *h, px.as_ref().clone())) { + Some((w, h, png)) => png_reply(w, h, png, true).map_or_else(err, ok), + None => err("that view has not drawn anything yet"), + }; + } + _ => None, + }; + if let Some(why) = refused { + return err(why); + } + let queued = app.input_queue.len(); + app.agent_request = true; + let reply = handle(app, ctx, method, params); + app.agent_request = false; + // The clicks and shortcuts of the input it queued run in the next frames, still as the agent's + if app.input_queue.len() > queued { + app.agent_input = true; + } + reply +} + +/// A file tool's method on the window's package, with file access only below the agent folders: the +/// headless session's own code ([`materialcraft_automation::Headless`]) runs on the window's session +/// for this one request. +#[cfg(not(target_arch = "wasm32"))] +fn agent_files(app: &mut MaterialCraftApp, method: &str, params: &Value, scope: &crate::agents::AgentScope) -> Result { + let mut params = params.clone(); + let rel = |folder: Option<&std::path::Path>, path: &str| relative_in(folder, std::path::Path::new(path)); + match method { + // The package's own file, when it is in the write folder + "package.save" if params.get("path").is_none_or(Value::is_null) => { + let own = app.session.path.clone().ok_or("the package has no file yet: give `path`, relative to the write folder (agent_folders)")?; + let inside = rel(scope.write_folder(), &own) + .ok_or("the package's own file is outside the folder agents can save to: give `path`, relative to the write folder (agent_folders)")?; + params["path"] = json!(inside); + } + // As File > Save As does: a file another open package uses is not written over + "package.save" => { + if let (Some(folder), Some(path)) = (scope.write_folder(), params.get("path").and_then(Value::as_str)) + && let Ok(relative) = materialcraft_automation::workspace::relative_path(&materialcraft_engine::file_cmds::package_path(path)) + && another_package_uses(app, &folder.join(relative)) + { + return Err("another open package already uses this file: save to another name".into()); + } + } + // A package the window already has open from the read folder is brought forward, not opened twice + "package.open" => { + // Only a path the workspace accepts (relative, inside the read folder) may name an open package; any other goes + // to the confined open below, which refuses it + if let (Some(folder), Some(path)) = (scope.read_folder(), params.get("path").and_then(Value::as_str)) + && let Ok(relative) = materialcraft_automation::workspace::relative_path(path) + { + let full = folder.join(relative).display().to_string(); + if let Some((document, ..)) = app.session.open_packages().into_iter().find(|entry| entry.2 == Some(full.as_str())) { + app.session.activate_document(document).map_err(|e| e.to_string())?; + return Ok(materialcraft_engine::inspect::session(&app.session, None)); + } + } + } + _ => {} + } + crate::properties::GraphPropertyDraft::commit(app); + let spare = match app.agent_spare.take() { + Some(spare) => spare, + None => materialcraft_engine::Session::new(Default::default()), + }; + let session = std::mem::replace(&mut app.session, spare); + let mut headless = materialcraft_automation::Headless::confined(session, scope.workspace.clone()); + let result = headless.handle(method, ¶ms); + app.agent_spare = Some(std::mem::replace(&mut app.session, headless.into_session())); + // Workspace paths are relative; the window keeps the file's real path, so Save and the title + // name the file the agent opened or saved + let folder = if method == "package.save" { scope.write_folder() } else { scope.read_folder() }; + if let (Some(folder), Some(path)) = (folder, app.session.path.clone().filter(|p| std::path::Path::new(p).is_relative())) { + app.session.path = Some(folder.join(path).display().to_string()); + } + let result = result.map_err(|e| e.to_string())?; + match method { + "package.open" => { + app.ui.frame_all = true; + app.toast(format!("{} {}", crate::i18n::tr("An AI agent opened"), app.session.path.clone().unwrap_or_default()), false); + crate::windows::after_open(app); + } + "package.save" => app.toast(format!("{} {}", crate::i18n::tr("An AI agent saved"), app.session.path.clone().unwrap_or_default()), false), + _ => {} + } + // The views and thumbnails follow what the agent opened or imported + if matches!(method, "package.open" | "bitmap.import") { + app.session.dirty = true; + } + Ok(result) +} + +/// Whether an open package other than the active one has its file at `destination`. +#[cfg(not(target_arch = "wasm32"))] +fn another_package_uses(app: &MaterialCraftApp, destination: &std::path::Path) -> bool { + let same = |path: &str| { + let path = std::path::Path::new(path); + path == destination || std::fs::canonicalize(path).is_ok_and(|a| std::fs::canonicalize(destination).is_ok_and(|b| a == b)) + }; + app.session.open_packages().into_iter().any(|entry| entry.0 != app.session.document_id && entry.2.is_some_and(same)) +} + +/// `path` relative to `folder` with forward slashes, when it lies below it. +#[cfg(not(target_arch = "wasm32"))] +fn relative_in(folder: Option<&std::path::Path>, path: &std::path::Path) -> Option { + let rel = path.strip_prefix(folder?).ok()?; + let parts: Vec = rel.components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect(); + (!parts.is_empty()).then(|| parts.join("/")) +} + /// Ask for one window capture answering every pending `ui.screenshot` (call from the UI pass). pub fn request_screenshots(app: &mut MaterialCraftApp, ctx: &egui::Context) { if app.pending_screenshots.is_empty() { @@ -77,11 +297,14 @@ pub fn request_screenshots(app: &mut MaterialCraftApp, ctx: &egui::Context) { let replies = std::mem::take(&mut app.pending_screenshots); let repaint = ctx.clone(); let callback = egui::ScreenshotCallback::new(move |img| { - let answer = encode_png(img.size[0] as u32, img.size[1] as u32, img.pixels.iter().flat_map(|c| c.to_array()).collect()) - .map(|(w, h, png)| ok(json!({ "width": w, "height": h, "png": base64::engine::general_purpose::STANDARD.encode(png) }))) - .unwrap_or_else(|| err("could not encode the screenshot")); - for r in &replies { - let _ = r.send(answer.clone()); + let encoded = encode_png(img.size[0] as u32, img.size[1] as u32, img.pixels.iter().flat_map(|c| c.to_array()).collect()); + for (r, fit) in &replies { + let answer = encoded + .clone() + .ok_or_else(|| "could not encode the screenshot".to_string()) + .and_then(|(w, h, png)| png_reply(w, h, png, *fit)) + .map_or_else(err, ok); + let _ = r.send(answer); } repaint.request_repaint(); @@ -100,6 +323,11 @@ pub(crate) fn encode_png(w: u32, h: u32, rgba: Vec) -> Option<(u32, u32, Vec /// Feed the next frame of scripted input to egui (from `eframe::App::raw_input_hook`). pub fn feed_input(app: &mut MaterialCraftApp, raw: &mut egui::RawInput) { + // Input an agent queued stays its own through the frame that ran its last step: shortcuts and + // clicks act in the frame their events arrive + if app.input_queue.is_empty() { + app.agent_input = false; + } if let Some(step) = app.input_queue.pop_front() { raw.events.extend(step.events); } @@ -333,6 +561,7 @@ fn handle_inner(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p "cooking": app.cooker.busy(), "render3dMs": app.view3d.render_ms, "toasts": app.toasts.iter().map(|t| json!({"text": t.text, "error": t.error})).collect::>(), + "agents": agents_state(app), })) } "ui.menu.list" => ok(crate::menus::list(app, ctx)), diff --git a/crates/ui-egui/src/export/mod.rs b/crates/ui-egui/src/export/mod.rs index 813bd5e88..6c0848c21 100644 --- a/crates/ui-egui/src/export/mod.rs +++ b/crates/ui-egui/src/export/mod.rs @@ -298,6 +298,11 @@ fn footer(ui: &mut Ui, tab: ExportTab) -> Option { /// Export what the current tab describes; true when the window can close fn export(app: &mut MaterialCraftApp, settings: &ExportSettings) -> bool { + // The window's destination may be anywhere: an agent exports with outputs_export or material_export into its folders + if app.agent_driven() { + app.toast(tr("An AI agent can't export from this window: it writes outside the agent folders"), true); + return false; + } match app.ui.export_tab { ExportTab::MaterialX | ExportTab::Mcmat => publish(app, settings), ExportTab::FromGraph => { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9cc1721fd..b132fd802 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1,6 +1,8 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#[cfg(not(target_arch = "wasm32"))] +pub mod agents; mod annotation; pub mod control; pub mod cook; diff --git a/crates/ui-egui/src/material_craft_app.rs b/crates/ui-egui/src/material_craft_app.rs index 93ddcf7dd..037a0ca5b 100644 --- a/crates/ui-egui/src/material_craft_app.rs +++ b/crates/ui-egui/src/material_craft_app.rs @@ -10,6 +10,19 @@ pub struct MaterialCraftApp { pub session: Session, pub ui: UiState, pub control: Option>, + /// Agents in the open window through the ArtCraft Launcher's switch (set by the host) + #[cfg(not(target_arch = "wasm32"))] + pub agents: Option, + /// An agent's request is running ([`crate::control`]); what it starts may not reach files + /// outside the agent folders ([`Self::agent_driven`]) + pub(crate) agent_request: bool, + /// Input an agent queued (`ui.input`) is still being fed, or was fed last frame: the shortcuts + /// and clicks it makes may not reach files outside the agent folders either + pub(crate) agent_input: bool, + /// The session the window holds while an agent's file tool runs on its own one + /// ([`crate::control::handle_agent`]), kept for the next such request + #[cfg(not(target_arch = "wasm32"))] + pub(crate) agent_spare: Option, pub toasts: Vec, /// Background cooking of the open graph pub cooker: cook::Cooker, @@ -31,8 +44,9 @@ pub struct MaterialCraftApp { pub(crate) graph_parents: Vec, /// Synthetic input from the control channel, fed to egui on the next frames pub input_queue: VecDeque, - /// Replies waiting for the next window capture (`ui.screenshot`) - pub pending_screenshots: Vec>, + /// Replies waiting for the next window capture (`ui.screenshot`), each with whether it goes to + /// an agent (downscaled to what the agent link's server sends) + pub pending_screenshots: Vec<(std::sync::mpsc::Sender, bool)>, pub fps: f32, /// Smoothed CPU time spent building the UI per frame (ms) pub ui_ms: f32, @@ -67,6 +81,10 @@ pub struct MaterialCraftApp { pub framework_dialogs: craft_ui::dialog::DialogHost, /// Who MaterialCraft is to the framework's dialogs pub(crate) framework_host: std::sync::Arc, + /// The native file panels behind the framework host's file service (Browse on the AI Agents + /// page), shown once per pass; `None` without a window + #[cfg(not(target_arch = "wasm32"))] + framework_files: Option, /// What Copy or Cut put on the clipboard this frame, for the system clipboard pub(crate) system_clipboard: Option, /// Fallback fonts for Arabic @@ -98,6 +116,11 @@ impl MaterialCraftApp { { app.dialogs = crate::native_dialogs::attached(&cc.egui_ctx); app.thumbs.enable_persistence(app.ui.prefs.library_cache); + // The framework's file picks (Browse on the AI Agents page) go to native panels shown by `ui` + let ctx = cc.egui_ctx.clone(); + let (files, panels) = craft_dialogs::service::FileService::new(craft_dialogs::Wake::new(move || ctx.request_repaint())); + app.framework_host = std::sync::Arc::new(crate::framework::host().with_files(std::sync::Arc::new(files))); + app.framework_files = Some(panels); } app @@ -112,6 +135,12 @@ impl MaterialCraftApp { session, ui, control: None, + #[cfg(not(target_arch = "wasm32"))] + agents: None, + agent_request: false, + agent_input: false, + #[cfg(not(target_arch = "wasm32"))] + agent_spare: None, toasts: Vec::new(), cooker: cook::Cooker::default(), thumbs: thumbs::Thumbs::default(), @@ -153,6 +182,8 @@ impl MaterialCraftApp { docks: docking::LiveDock::default(), framework_dialogs: craft_ui::dialog::DialogHost::new(), framework_host: crate::framework::host(), + #[cfg(not(target_arch = "wasm32"))] + framework_files: None, system_clipboard: None, fonts: fonts::UiFonts::default(), fonts_ready: false, @@ -229,8 +260,23 @@ impl MaterialCraftApp { (result, output) } + /// Whether an agent drives the window now: its request runs, or input it queued is being fed + pub fn agent_driven(&self) -> bool { + self.agent_request || self.agent_input + } + /// Run an engine command, reporting errors as toasts. Returns the result on success pub fn run(&mut self, id: &str, mut params: Value) -> Option { + // What an agent's clicks and shortcuts start may not read or write files outside the agent + // folders (File > Save to the package's own file, Open Recent, Send to TextureCraft): the same + // rule as for its command_run + #[cfg(not(target_arch = "wasm32"))] + if self.agent_driven() + && let Err(error) = materialcraft_automation::workspace::authorize_command(id, ¶ms) + { + self.toast(format!("{} ({id}): {error}", crate::i18n::tr("An AI agent can't do this")), true); + return None; + } if id.starts_with("graph.annotation.") || id.starts_with("graph.frame.") || id.starts_with("graph.comment.") @@ -489,6 +535,10 @@ impl eframe::App for MaterialCraftApp { self.draw(ui); #[cfg(not(target_arch = "wasm32"))] self.dialogs.show_pending(Some(&*frame)); + #[cfg(not(target_arch = "wasm32"))] + if let Some(files) = &mut self.framework_files { + files.pump(Some(&*frame)); + } #[cfg(target_arch = "wasm32")] let _ = frame; } diff --git a/crates/ui-egui/src/native_dialogs.rs b/crates/ui-egui/src/native_dialogs.rs index f70c93614..a2a2f0de0 100644 --- a/crates/ui-egui/src/native_dialogs.rs +++ b/crates/ui-egui/src/native_dialogs.rs @@ -135,6 +135,13 @@ pub(crate) fn save_before_action(app: &mut MaterialCraftApp) { /// Apply the answers that arrived since the last frame. Call once per frame pub(crate) fn poll(app: &mut MaterialCraftApp) { + // A file dialog's answer is the person's pick, even when an agent's click opened the dialog + let agent_input = std::mem::take(&mut app.agent_input); + poll_answers(app); + app.agent_input = agent_input; +} + +fn poll_answers(app: &mut MaterialCraftApp) { for (then, answer) in app.dialogs.take_answers() { match answer { Answer::Paths(paths) => match paths.into_iter().next() { diff --git a/crates/ui-egui/src/preference/mod.rs b/crates/ui-egui/src/preference/mod.rs index 01a2f88fd..3563697ba 100644 --- a/crates/ui-egui/src/preference/mod.rs +++ b/crates/ui-egui/src/preference/mod.rs @@ -51,6 +51,12 @@ pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { app.ui.preferences.applied = Some(app.ui.prefs.clone()); } + // The AI Agents page: on the desktop, with the suite's `AI-MCP` flag (MaterialCraft had no agent settings + // before the ArtCraft Launcher's switch, so without the flag there is nothing to set) + if app.ui.preferences.page == PreferencesPage::Agents && !agents_page_shown(app) { + app.ui.preferences.page = PreferencesPage::General; + } + let size = crate::windows::dialog_size(ctx, WINDOW_SIZE); let mut open = true; let mut choice = None; @@ -74,6 +80,7 @@ pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { PreferencesPage::View3d => view3d_page::show(app, ui), PreferencesPage::Library => rebuild_previews = library_page::show(app, ui), PreferencesPage::Shortcuts => shortcuts_page::show(app, ui), + PreferencesPage::Agents => agents_page(app, ui), } }); @@ -96,20 +103,30 @@ pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) { // Closing the window is Cancel let choice = if open { choice } else { Some(PreferenceAction::Cancel) }; match choice { - Some(PreferenceAction::Apply) => app.ui.preferences.applied = Some(app.ui.prefs.clone()), + Some(PreferenceAction::Apply) => { + // A failed agent-settings save keeps its edits on the AI Agents page; the other pages apply as before + apply_agent_settings(app); + app.ui.preferences.applied = Some(app.ui.prefs.clone()); + } Some(PreferenceAction::Cancel) => { if let Some(applied) = app.ui.preferences.applied.take() { app.ui.prefs = applied; } close(app); } - Some(PreferenceAction::Ok) => close(app), + // A save that failed keeps the window open with the person's edits, to try again + Some(PreferenceAction::Ok) if apply_agent_settings(app) => close(app), + Some(PreferenceAction::Ok) => {} None => {} } app.apply_prefs(); } fn close(app: &mut MaterialCraftApp) { + #[cfg(not(target_arch = "wasm32"))] + if let Some(agents) = app.agents.as_mut() { + agents.discard_draft(); + } app.ui.windows.preferences = false; app.ui.preferences.applied = None; app.ui.preferences.capturing = None; @@ -120,7 +137,7 @@ fn page_list(app: &mut MaterialCraftApp, ui: &mut Ui) { let tokens = Tokens::get(ui.ctx()); ui.painter().rect_filled(ui.max_rect(), 0.0, tokens.row); - for page in PreferencesPage::ALL { + for page in PreferencesPage::ALL.into_iter().chain(agents_page_shown(app).then_some(PreferencesPage::Agents)) { let chosen = app.ui.preferences.page == page; let label = RichText::new(tr(page.label()).to_uppercase()).size(14.0).color(if chosen { tokens.text_strong } else { tokens.text }); let button = egui::Button::selectable(chosen, label).frame_when_inactive(false); @@ -138,3 +155,54 @@ fn page_list(app: &mut MaterialCraftApp, ui: &mut Ui) { } } } + +/// Whether Preferences shows the AI Agents page: on the desktop with the suite's `AI-MCP` flag +#[cfg(not(target_arch = "wasm32"))] +fn agents_page_shown(app: &MaterialCraftApp) -> bool { + app.agents.as_ref().is_some_and(crate::agents::Agents::mcp_flag) +} + +#[cfg(target_arch = "wasm32")] +fn agents_page_shown(_: &MaterialCraftApp) -> bool { + false +} + +/// The AI Agents page: the shared page over the agent settings (the launcher's switch, the control port, the agent +/// folders and what happens while MaterialCraft is closed) +#[cfg(not(target_arch = "wasm32"))] +fn agents_page(app: &mut MaterialCraftApp, ui: &mut Ui) { + if let Some(agents) = app.agents.as_mut() { + agents.page(ui); + } +} + +#[cfg(target_arch = "wasm32")] +fn agents_page(_: &mut MaterialCraftApp, _: &mut Ui) {} + +/// Apply or OK: the agent settings saved where `materialcraft-cli mcp` reads them and applied to the agent link; false +/// when they were not saved. Only the person changes them: while an agent drives the window (its clicks may have +/// reached this button) nothing is saved. Either way the settings in use stay, the edits stay on the page and the +/// window stays open, so the person can press it again; a toast says why. +#[cfg(not(target_arch = "wasm32"))] +fn apply_agent_settings(app: &mut MaterialCraftApp) -> bool { + let driven = app.agent_driven(); + let Some(agents) = app.agents.as_mut() else { return true }; + let Some(next) = agents.edited() else { return true }; + if driven { + let why = tr("an AI agent is using the window; press the button again once it has finished"); + app.toast(format!("{}: {why}", tr("The AI agent settings were not saved")), true); + return false; + } + match agents.set(next) { + Ok(()) => true, + Err(error) => { + app.toast(format!("{}: {error}", tr("The AI agent settings were not saved")), true); + false + } + } +} + +#[cfg(target_arch = "wasm32")] +fn apply_agent_settings(_: &mut MaterialCraftApp) -> bool { + true +} diff --git a/crates/ui-egui/src/preference/preferences_page.rs b/crates/ui-egui/src/preference/preferences_page.rs index 9eb94b02d..077c9a6b7 100644 --- a/crates/ui-egui/src/preference/preferences_page.rs +++ b/crates/ui-egui/src/preference/preferences_page.rs @@ -8,9 +8,12 @@ pub enum PreferencesPage { View3d, Library, Shortcuts, + /// AI agents in the open window: shown on the desktop with the suite's `AI-MCP` flag + Agents, } impl PreferencesPage { + /// The pages every build shows; [`PreferencesPage::Agents`] follows them where it is shown pub const ALL: [PreferencesPage; 6] = [ PreferencesPage::General, PreferencesPage::Projects, @@ -29,6 +32,7 @@ impl PreferencesPage { PreferencesPage::View3d => "3D View", PreferencesPage::Library => "Library", PreferencesPage::Shortcuts => "Shortcuts", + PreferencesPage::Agents => "AI Agents", } } } diff --git a/crates/ui-egui/tests/it/agent_requests.rs b/crates/ui-egui/tests/it/agent_requests.rs new file mode 100644 index 000000000..1ebfa2f4a --- /dev/null +++ b/crates/ui-egui/tests/it/agent_requests.rs @@ -0,0 +1,132 @@ +//! Agent requests in the open window (the ArtCraft Launcher's switch): files are opened and saved +//! only in the agent folders, also by the clicks and shortcuts an agent's input makes, and the +//! person's own control channel stays as it was. + +use craft_control::agents::AgentFolders; +use materialcraft_ui_egui::agents::AgentScope; +use materialcraft_ui_egui::control::{feed_input, handle, handle_agent}; +use materialcraft_ui_egui::{MaterialCraftApp, UiState}; +use serde_json::{Value, json}; + +fn app() -> MaterialCraftApp { + let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default()); + app.ui.windows.home = false; + app +} + +fn scope(folder: &std::path::Path) -> AgentScope { + let mut folders = AgentFolders::default(); + folders.write = Some(folder.to_path_buf()); + AgentScope::new(folders, None).unwrap() +} + +fn path_text(path: &std::path::Path) -> String { + path.to_string_lossy().into_owned() +} + +#[test] +fn an_agent_opens_and_saves_only_in_its_folders() { + let (folder, outside) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()); + let scope = scope(folder.path()); + let ctx = egui::Context::default(); + let mut app = app(); + let agent = |app: &mut MaterialCraftApp, method: &str, params: Value| handle_agent(app, &ctx, method, ¶ms, &scope); + + // Host paths are refused, through the file tools and through engine commands alike. + let elsewhere = path_text(&outside.path().join("x.sbs")); + assert_eq!(agent(&mut app, "package.save", json!({"path": elsewhere}))["ok"], false); + assert_eq!(agent(&mut app, "command.run", json!({"id": "file.saveAs", "params": {"path": path_text(&outside.path().join("y.sbs"))}}))["ok"], false); + // Menu items that write the package's own file, and UI state that names files, are the person's. + assert_eq!(agent(&mut app, "ui.menu.invoke", json!({"id": "file.save"}))["ok"], false); + assert_eq!(agent(&mut app, "ui.set", json!({"recent": [path_text(&outside.path().join("z.sbs"))]}))["ok"], false); + assert!(std::fs::read_dir(outside.path()).unwrap().next().is_none(), "something was written outside the agent folder"); + + // Inside the folder: saved there, and the window keeps the file's real path for Save and the title. + let saved = agent(&mut app, "package.save", json!({"path": "made.sbs"})); + assert_eq!(saved["ok"], true, "{saved}"); + let made = folder.path().join("made.sbs"); + assert!(made.is_file()); + assert_eq!(app.session.path.as_deref(), Some(path_text(&made).as_str())); + // Without a path: the package's own file, which is in the folder now. + assert_eq!(agent(&mut app, "package.save", json!({}))["ok"], true); + let opened = agent(&mut app, "package.open", json!({"path": "made.sbs"})); + assert_eq!(opened["ok"], true, "{opened}"); + assert_eq!(app.session.path.as_deref(), Some(path_text(&made).as_str())); + + let folders = agent(&mut app, "agent.folders", json!({})); + assert_eq!(folders["result"]["write_folder"], json!(path_text(folder.path())), "{folders}"); + assert_eq!(folders["result"]["confined"], true); + assert!(!app.agent_driven(), "nothing an agent sent is still running"); + + // The person's own `--control` channel is not held to the agent folders. + let mine = outside.path().join("mine.sbs"); + let r = handle(&mut app, &ctx, "command.run", &json!({"id": "file.saveAs", "params": {"path": path_text(&mine)}})); + assert_eq!(r["ok"], true, "{r}"); + assert!(mine.is_file()); +} + +/// File > Save writes the package's own file, wherever it is: while an agent's input drives the +/// window its shortcut and menu click save nothing, through the frame that ran the input's last step. +#[test] +fn an_agents_shortcuts_and_clicks_dont_save_outside_its_folders() { + let (folder, outside) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()); + let scope = scope(folder.path()); + let ctx = egui::Context::default(); + let mut app = app(); + let own = outside.path().join("own.sbs"); + assert_eq!(handle(&mut app, &ctx, "command.run", &json!({"id": "file.saveAs", "params": {"path": path_text(&own)}}))["ok"], true); + std::fs::remove_file(&own).unwrap(); + app.session.modified = true; + + let queued = handle_agent(&mut app, &ctx, "ui.input", &json!({"events": [{"type": "key", "key": "S", "modifiers": ["ctrl"]}]}), &scope); + assert_eq!(queued["ok"], true, "{queued}"); + assert!(app.agent_driven(), "the agent's input drives the window until it has run"); + let mut raw = egui::RawInput::default(); + while !app.input_queue.is_empty() { + feed_input(&mut app, &mut raw); + assert!(app.agent_driven(), "a frame of the agent's input ran as the person's"); + materialcraft_ui_egui::menus::invoke(&mut app, &ctx, "file.save"); + } + assert!(!own.exists(), "the agent's shortcut saved outside its folders"); + feed_input(&mut app, &mut raw); + assert!(!app.agent_driven(), "the window is the person's again once the agent's input has run"); + materialcraft_ui_egui::menus::invoke(&mut app, &ctx, "file.save"); + assert!(own.is_file(), "the person's own File > Save stopped working"); +} + +/// A package the person has open outside the agent folders isn't brought forward for an agent that +/// names its host path: only paths inside the read folder reuse an open package. +#[test] +fn an_agent_cant_reach_an_open_package_outside_its_folders() { + let (folder, outside) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap()); + let scope = scope(folder.path()); + let ctx = egui::Context::default(); + let mut app = app(); + let private = outside.path().join("private.sbs"); + assert_eq!(handle(&mut app, &ctx, "command.run", &json!({"id": "file.saveAs", "params": {"path": path_text(&private)}}))["ok"], true); + assert_eq!(handle(&mut app, &ctx, "command.run", &json!({"id": "file.newPackage"}))["ok"], true); + let active = app.session.document_id; + + let r = handle_agent(&mut app, &ctx, "package.open", &json!({"path": path_text(&private)}), &scope); + assert_eq!(r["ok"], false, "{r}"); + assert_eq!(app.session.document_id, active, "the person's package outside the agent folders came forward"); +} + +/// An agent saving the active package doesn't write over the file of another open package, as +/// File > Save As refuses it too; a new name is fine. +#[test] +fn an_agent_doesnt_save_over_another_open_package() { + let folder = tempfile::tempdir().unwrap(); + let scope = scope(folder.path()); + let ctx = egui::Context::default(); + let mut app = app(); + assert_eq!(handle_agent(&mut app, &ctx, "package.save", &json!({"path": "a.sbs"}), &scope)["ok"], true); + let first = app.session.document_id; + assert_eq!(handle(&mut app, &ctx, "command.run", &json!({"id": "file.newPackage"}))["ok"], true); + assert_ne!(app.session.document_id, first); + + let r = handle_agent(&mut app, &ctx, "package.save", &json!({"path": "a"}), &scope); + assert_eq!(r["ok"], false, "{r}"); + assert!(r["error"].as_str().unwrap_or_default().contains("another open package"), "{r}"); + assert_eq!(handle_agent(&mut app, &ctx, "package.save", &json!({"path": "b.sbs"}), &scope)["ok"], true); +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 755ca4cda..547fdb4a9 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -2,6 +2,7 @@ //! Keep snapshot.rs standalone; language_switching.rs needs process isolation for global locale state. //! resize.rs isolates its bounded render wait from unrelated tests sharing the global Rayon pool. +mod agent_requests; mod canvas_focus; mod clipboard_shortcuts; mod dialogs; diff --git a/docs/control-protocol.md b/docs/control-protocol.md index b91b9fe65..ea50a6023 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -1,12 +1,14 @@ # Control protocol and MCP -> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-11-03 · **Change:** minor (`material_export` MCP tool) · **Target:** the professional node-based material workflow +> **Last reviewed:** 2026-11-02 · **Last updated:** 2026-12-03 · **Change:** minor (agents in the open window through the ArtCraft Launcher's switch, `agent_folders`) · **Target:** the professional node-based material workflow Agents drive MaterialCraft three ways, all dispatching the same engine commands: -1. **MCP** (`materialcraft-cli mcp`): headless (an in-process session, files only below - `--read-root` / `--write-root`, also spelled `--automation-read-root` / - `--automation-write-root` as in the other crafting apps; `serve` takes them too) or bridged to the running app (`--bridge `). +1. **MCP** (`materialcraft-cli mcp`): the open window while the ArtCraft Launcher's AI agents + switch names MaterialCraft ([Agents in the open window](#agents-in-the-open-window)), or headless + (an in-process session, files only below `--read-root` / `--write-root`, also spelled + `--automation-read-root` / `--automation-write-root` as in the other crafting apps; `serve` takes + them too). Bridging to an app started with `--control` (`--bridge `) is deprecated. 2. **JSON lines** (`materialcraft-cli serve`): the same methods on stdio, or on `127.0.0.1:` behind a token. 3. **The app's control channel** (`materialcraft --control `): one JSON request per line, @@ -392,14 +394,71 @@ The named profiles choose their own file names and formats. Use `--format` and ` | `library.functions` | `{filter?}`: list reusable SBS functions with package URI, full graph path, typed ports and missing status | | `library.function.add` | `{graph, package? (default: sbs://functions.sbs), function?: FunctionGraphTarget, at?, snapToGrid?}`: insert a reference into the active Function or processor canvas | +## Agents in the open window + +With the suite's `AI-MCP` flag, the ArtCraft Launcher's *Settings › AI agents* switch decides +whether agents may use the open window; MaterialCraft has no agents switch of its own. While it +names MaterialCraft, the window serves its control channel on loopback (`127.0.0.1`, Edit › +Preferences › AI Agents › *Control Port*, 0 picks a free port) and publishes where in its settings +folder (`agent-connection.json`, beside `app.ron`: the port, its process id and the token file +`agent-control.token`, owner-only). Plain `materialcraft-cli mcp` reads that file before every tool +call, checks that the process is still running, and signs in with the challenge handshake: the +window first proves it holds the token, and the token itself never crosses the wire. Requests are +at most 1 MiB. When the switch turns off, the server stops and the file goes, without a restart; a +file a crashed run left behind is removed at the next start. A Nightly profile and a run with +`MATERIALCRAFT_NO_PREFS` take no agents; with `--control` the launch options manage the control +channel for the whole run. + +Agents open and save files only in the agent folders of Edit › Preferences › AI Agents (*Folder +agents can open from*, *Folder agents can save to*), or `Documents/ArtCraft/Agents/MaterialCraft` +for an empty one; `agent_folders` names them. Only the person changes these settings: Apply and OK +save nothing while an agent drives the window (the edits stay on the page for the person to save). In the window: + +- The path tools (`package_open`, `package_save`, `bitmap_import`, `outputs_export`, + `material_export`) take forward-slash paths relative to those folders, as without a window. + `package_save` without a path saves the package's own file only when it is in the save folder. +- The window itself refuses host paths in `command_run` (the same rules as headless), File › Save, + Save all and Send to TextureCraft through `ui_menu_invoke`, and `ui.set` of `recent`, `export` and + `exportDraft` (they name files). The clicks and shortcuts an agent's `ui_input` makes are held to + the same rules through the frame that runs its last event (File › Save by Ctrl+S, Open Recent, the + Export window's Export). A file dialog an agent's click opens is the person's: what they pick is + used. Nothing is written in the settings folder, even when a save folder holds it. +- `command_batch` runs its steps one by one in the window, stopping at the first error. `view_render` + runs without a window; in the window use `view_screenshot` and `ui_screenshot`. Screenshots are downscaled to 2048 px a side, so a reply + stays within the agent server's 8 MiB. + +The MCP client entry is the launcher's job: it adds one `ArtCraft` entry to Claude Desktop, Claude +Code, Cursor and LM Studio for every Craft app. MaterialCraft writes no client configuration. + ## MCP tools +`materialcraft-cli mcp` speaks MCP on stdin/stdout (stdout carries only protocol messages): + +- **Open window** (plain `mcp` with the suite's `AI-MCP` flag): while ArtCraft Launcher › + Settings › AI agents › *Let AI agents use Craft apps* names MaterialCraft, each tool call goes to + the open window, which `mcp` finds by itself before every call: no port or token in the MCP + client's configuration. While the switch doesn't let agents in, the session works without a + window (headless, below). While agents may use MaterialCraft but it is closed, Edit › Preferences › + AI Agents › *When MaterialCraft is closed* decides (`--when-closed launch|headless|error` overrides + it): open MaterialCraft and wait for it, work without a window in the agent folders, or answer + with an error asking to open it. A session that went without a window stays so until the MCP + client restarts it, so the package doesn't move under the agent. `--read-root` / `--write-root`, + when given, replace the agent folders. +- **Headless** (`--headless`, or no `AI-MCP` flag): an in-process session on the atomic sample, with + files only below the roots (none without them). +- **Bridge** (deprecated, goes away in the next release; it says so on stderr): `--bridge ` + forwards to a running `materialcraft --control `. It takes neither `--headless` nor + `--when-closed`. + `session_inspect`, `command_list`, `command_run`, `command_batch`, `library_list`, `graph_new`, `node_add`, `node_connect`, `node_param`, `package_open`, `package_save`, `bitmap_import`, -`outputs_export`, `material_export`, `view_render` (headless) and, bridged to the app, `view_screenshot`, -`ui_screenshot`, `ui_inspect`, `ui_menu_invoke`, `ui_input`. Bridged to the app, `package_save` -without a path runs File > Save through `ui.menu.invoke`, so it returns that call's error when a -dialog or prompt blocks it. `package_open` opens `.mcmat` files +`outputs_export`, `material_export`, `view_render` (headless), `agent_folders` and, in the open +window (or bridged to the app), `view_screenshot`, `ui_screenshot`, `ui_inspect` (with `agents`: +`port`, `launchFlags`, `problem`, `mcpFlag`, `allowed`), `ui_menu_invoke`, `ui_input`. +`agent_folders` answers where the session opens and saves files: `{read_folder, write_folder, +confined}`, each folder a path or `null`. Bridged to the app, `package_save` without a path runs +File > Save through `ui.menu.invoke`, so it returns that call's error when a dialog or prompt +blocks it. `package_open` opens `.mcmat` files too. `material_export` accepts `{path, graph?}` and publishes below the write root. Use `outputs_export` to bake variations with `profile`, `size`, `preset`, `values` and `inputs`. Image paths are relative to the read root and the destination is relative to the write root.