mirror of
https://github.com/storytold/cadcraft.git
synced 2026-12-04 00:28:24 +00:00
Merge pull request #3770 from davidmann4/feat/agents-open-window
feat(automation): agents in the open window through the ArtCraft Launcher's switch
This commit is contained in:
29 files changed
+1762
-68
No files matched your search
Generated
+94
-5
@@ -759,6 +759,7 @@ dependencies = [
|
||||
"cadcraft-ui-egui",
|
||||
"chrono",
|
||||
"clap",
|
||||
"craft-automation",
|
||||
"craft-nightly",
|
||||
"craft-quit",
|
||||
"craft-update",
|
||||
@@ -842,6 +843,7 @@ dependencies = [
|
||||
"cadcraft-geom",
|
||||
"cadcraft-io",
|
||||
"cadcraft-render",
|
||||
"craft-control",
|
||||
"craft-csv",
|
||||
"craft-docpath",
|
||||
"craft-dxf",
|
||||
@@ -910,6 +912,8 @@ dependencies = [
|
||||
"cadcraft-io",
|
||||
"cadcraft-render",
|
||||
"clap",
|
||||
"craft-automation",
|
||||
"craft-control",
|
||||
"craft-jsonrpc",
|
||||
"craft-mcp",
|
||||
"getrandom 0.4.3",
|
||||
@@ -946,7 +950,9 @@ dependencies = [
|
||||
"cadcraft-io",
|
||||
"cadcraft-render",
|
||||
"chrono",
|
||||
"craft-automation",
|
||||
"craft-behavior",
|
||||
"craft-control",
|
||||
"craft-host",
|
||||
"craft-image-codecs",
|
||||
"craft-keymap",
|
||||
@@ -1381,6 +1387,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"
|
||||
@@ -1399,6 +1415,31 @@ dependencies = [
|
||||
"rustix 1.1.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-automation"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
|
||||
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"
|
||||
@@ -1430,6 +1471,21 @@ name = "craft-codepage"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
|
||||
|
||||
[[package]]
|
||||
name = "craft-control"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
|
||||
dependencies = [
|
||||
"craft-ai-agents",
|
||||
"craft-atomic",
|
||||
"craft-flags",
|
||||
"dirs",
|
||||
"getrandom 0.3.4",
|
||||
"log",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-csv"
|
||||
version = "0.1.0"
|
||||
@@ -1475,6 +1531,16 @@ dependencies = [
|
||||
"thiserror 2.0.21",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-flags"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
|
||||
dependencies = [
|
||||
"craft-atomic",
|
||||
"dirs",
|
||||
"toml_edit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-font-catalog"
|
||||
version = "0.1.0"
|
||||
@@ -1552,7 +1618,7 @@ dependencies = [
|
||||
"image",
|
||||
"image-webp",
|
||||
"jpeg-encoder",
|
||||
"png",
|
||||
"png 0.18.1",
|
||||
"rayon",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2107,6 +2173,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3273,6 +3340,15 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[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"
|
||||
@@ -3622,7 +3698,7 @@ dependencies = [
|
||||
"gif",
|
||||
"moxcms",
|
||||
"num-traits",
|
||||
"png",
|
||||
"png 0.18.1",
|
||||
"qoi",
|
||||
"tiff",
|
||||
"zune-core",
|
||||
@@ -3855,7 +3931,7 @@ dependencies = [
|
||||
"imagesize 0.14.0",
|
||||
"indexmap",
|
||||
"pdf-writer",
|
||||
"png",
|
||||
"png 0.18.1",
|
||||
"rustc-hash 2.1.3",
|
||||
"siphasher",
|
||||
"skrifa 0.42.1",
|
||||
@@ -4156,7 +4232,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.61.2",
|
||||
]
|
||||
@@ -5213,6 +5289,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"
|
||||
@@ -6460,7 +6549,7 @@ dependencies = [
|
||||
"bytemuck",
|
||||
"cfg-if",
|
||||
"log",
|
||||
"png",
|
||||
"png 0.18.1",
|
||||
"tiny-skia-path",
|
||||
]
|
||||
|
||||
|
||||
@@ -33,6 +33,11 @@ cadcraft-ui-egui = { path = "crates/ui-egui" }
|
||||
cadcraft-mcp = { path = "crates/mcp" }
|
||||
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
# Agents in the open window: the agent settings, the ArtCraft Launcher's switch, the connection file and
|
||||
# the CLI's live client (`agents`), shared by every Craft app.
|
||||
craft-control = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
# The agent link host (the window's control server for agents) and the Agents page of Options.
|
||||
craft-automation = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
# SVG/SVGZ import and export geometry (craft-libs#778).
|
||||
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
|
||||
# Which paths stored in a drawing (xrefs, data links) may be opened.
|
||||
|
||||
@@ -11,6 +11,7 @@ use std::path::{Path, PathBuf};
|
||||
use cadcraft_engine::geom::{Bounds2, Vec2};
|
||||
use cadcraft_io::Format;
|
||||
use cadcraft_mcp::args::{blank_env_is_unset, name_env_vars};
|
||||
use cadcraft_mcp::live::WhenAppClosed;
|
||||
use clap::builder::{OsStringValueParser, PathBufValueParser, TypedValueParser};
|
||||
use clap::error::ErrorKind;
|
||||
use clap::parser::ValueSource;
|
||||
@@ -262,12 +263,23 @@ pub(crate) struct CommandsArgs {
|
||||
pub(crate) compact: bool,
|
||||
}
|
||||
|
||||
/// Run the MCP server on stdio: a headless drawing session, or a bridge to the running app
|
||||
/// Run the MCP server on stdio: the open CADCraft window while ArtCraft Launcher › Settings › AI
|
||||
/// agents lets agents use it, otherwise a headless drawing session
|
||||
#[derive(Args)]
|
||||
pub(crate) struct McpArgs {
|
||||
/// Bridge to the app's control channel (its --control port, e.g. 127.0.0.1:7979)
|
||||
/// Deprecated: plain `mcp` finds the open window by itself while the ArtCraft Launcher lets
|
||||
/// agents use CADCraft. Bridges to the app's --control port (e.g. 127.0.0.1:7979); goes in a
|
||||
/// later release
|
||||
#[arg(long, value_name = "HOST:PORT", value_parser = connect_addr)]
|
||||
pub(crate) connect: Option<String>,
|
||||
/// Never the open window: a headless drawing session, also while the ArtCraft Launcher lets
|
||||
/// agents use CADCraft
|
||||
#[arg(long, conflicts_with = "connect")]
|
||||
pub(crate) headless: bool,
|
||||
/// While agents may use CADCraft but it is closed: `launch` (open it and wait), `headless`
|
||||
/// (work without a window) or `error`. Default: Options › AI Agents › When CADCraft is closed
|
||||
#[arg(long, value_name = "CHOICE", value_parser = when_closed, conflicts_with_all = ["connect", "headless"])]
|
||||
pub(crate) when_closed: Option<WhenAppClosed>,
|
||||
/// Reach the app at the first call instead of at startup, so the server can start before the
|
||||
/// app is open
|
||||
#[arg(long, requires = "connect")]
|
||||
@@ -404,6 +416,8 @@ pub(crate) enum ValueError {
|
||||
CmdJson(#[from] serde_json::Error),
|
||||
#[error("expected a number of 0 or more, got `{0}`")]
|
||||
Tolerance(String),
|
||||
#[error("expected one of launch, headless, error, got `{0}`")]
|
||||
WhenClosed(String),
|
||||
}
|
||||
|
||||
/// Why `parse` refuses flags clap accepted: clap prints it as a usage error (exit 2).
|
||||
@@ -523,8 +537,12 @@ fn out_is_input(cli: &Cli) -> Option<UsageError> {
|
||||
/// The backend `cadcraft-cli mcp` serves from.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) enum McpTarget {
|
||||
/// An in-process drawing session (no `--connect`), optionally confined to the two folders.
|
||||
/// An in-process drawing session (`--headless`), optionally confined to the two folders.
|
||||
Headless { read_root: Option<String>, write_root: Option<String> },
|
||||
/// Plain `mcp`: the open window while the ArtCraft Launcher's switch lets agents use CADCraft,
|
||||
/// otherwise a headless session with the two folders (`cadcraft_mcp::Live`); headless without
|
||||
/// the suite's `AI-MCP` flag, as before.
|
||||
Live { read_root: Option<String>, write_root: Option<String>, when_closed: Option<WhenAppClosed> },
|
||||
/// The running app's control channel at `HOST:PORT`; `lazy`: reached at the first call;
|
||||
/// `launch`: opened then if it isn't running.
|
||||
Connect { addr: String, lazy: bool, launch: bool },
|
||||
@@ -533,10 +551,12 @@ pub(crate) enum McpTarget {
|
||||
impl McpArgs {
|
||||
/// What these arguments ask the server to talk to.
|
||||
pub(crate) fn target(&self) -> McpTarget {
|
||||
let (read_root, write_root) = (self.automation_read_root.clone(), self.automation_write_root.clone());
|
||||
match &self.connect {
|
||||
// `--launch` connects at the first call too (the app opens then).
|
||||
Some(addr) => McpTarget::Connect { addr: addr.clone(), lazy: self.lazy || self.launch, launch: self.launch },
|
||||
None => McpTarget::Headless { read_root: self.automation_read_root.clone(), write_root: self.automation_write_root.clone() },
|
||||
None if self.headless => McpTarget::Headless { read_root, write_root },
|
||||
None => McpTarget::Live { read_root, write_root, when_closed: self.when_closed },
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -553,6 +573,11 @@ fn connect_addr(s: &str) -> Result<String, ValueError> {
|
||||
if valid { Ok(s.to_string()) } else { Err(ValueError::Connect) }
|
||||
}
|
||||
|
||||
/// `mcp --when-closed`: one of [`WhenAppClosed::NAMES`].
|
||||
fn when_closed(s: &str) -> Result<WhenAppClosed, ValueError> {
|
||||
WhenAppClosed::parse(s.trim()).ok_or_else(|| ValueError::WhenClosed(s.to_string()))
|
||||
}
|
||||
|
||||
/// The values of `id` with their command-line indices.
|
||||
fn indexed<'a, T: Clone + Send + Sync + 'static>(m: &'a ArgMatches, id: &str) -> impl Iterator<Item = (usize, &'a T)> {
|
||||
let at = m.indices_of(id).into_iter().flatten();
|
||||
@@ -665,10 +690,21 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Without `--connect` the server runs headless, confining nothing unless asked.
|
||||
/// Plain `mcp` looks for the open window (headless while the launcher doesn't let agents in);
|
||||
/// `--headless` never does. Neither confines anything unless asked.
|
||||
#[test]
|
||||
fn mcp_without_connect_is_headless() {
|
||||
assert_eq!(mcp(&[]).unwrap(), McpTarget::Headless { read_root: None, write_root: None });
|
||||
fn plain_mcp_looks_for_the_window_and_headless_never_does() {
|
||||
assert_eq!(mcp(&[]).unwrap(), McpTarget::Live { read_root: None, write_root: None, when_closed: None });
|
||||
assert_eq!(mcp(&["--headless"]).unwrap(), McpTarget::Headless { read_root: None, write_root: None });
|
||||
assert_eq!(
|
||||
mcp(&["--when-closed", "headless"]).unwrap(),
|
||||
McpTarget::Live { read_root: None, write_root: None, when_closed: Some(WhenAppClosed::Headless) }
|
||||
);
|
||||
assert!(mcp(&["--when-closed", "later"]).unwrap_err().to_string().contains("launch, headless, error"));
|
||||
// A closed-app choice means nothing without the window, and --connect names its own app.
|
||||
for conflict in [&["--headless", "--when-closed", "error"][..], &["--headless", "--connect", "127.0.0.1:7979"]] {
|
||||
assert_eq!(mcp(conflict).unwrap_err().kind(), clap::error::ErrorKind::ArgumentConflict, "{conflict:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The automation roots confine a headless server; `--connect` is refused with the reason
|
||||
@@ -676,9 +712,13 @@ mod tests {
|
||||
#[test]
|
||||
fn mcp_automation_roots_confine_a_headless_server_only() {
|
||||
assert_eq!(
|
||||
mcp(&["--automation-read-root", "/work", "--automation-write-root=/work/out"]).unwrap(),
|
||||
mcp(&["--headless", "--automation-read-root", "/work", "--automation-write-root=/work/out"]).unwrap(),
|
||||
McpTarget::Headless { read_root: Some("/work".into()), write_root: Some("/work/out".into()) }
|
||||
);
|
||||
assert_eq!(
|
||||
mcp(&["--automation-read-root", "/work"]).unwrap(),
|
||||
McpTarget::Live { read_root: Some("/work".into()), write_root: None, when_closed: None }
|
||||
);
|
||||
let e = mcp(&["--connect", "127.0.0.1:7979", "--automation-read-root", "/work"]).unwrap_err().to_string();
|
||||
assert!(e.contains("headless MCP server") && e.contains("#1585"), "{e}");
|
||||
let e = mcp(&["--automation-write-root=/work", "--connect", "127.0.0.1:7979"]).unwrap_err().to_string();
|
||||
|
||||
@@ -1,25 +1,96 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use super::args::{McpArgs, McpTarget};
|
||||
use super::error::{CliError, Result};
|
||||
|
||||
/// Serve MCP on stdin and stdout against the running app or a headless session held to any roots given.
|
||||
/// Serve MCP on stdin and stdout: plain `mcp` against the open window while the ArtCraft Launcher
|
||||
/// lets agents use CADCraft, otherwise (and with `--headless`) a headless session held to any roots
|
||||
/// given; `--connect` against an app's `--control` port.
|
||||
pub(crate) fn mcp(a: &McpArgs) -> Result {
|
||||
let backend: Box<dyn cadcraft_mcp::Backend> = match a.target() {
|
||||
McpTarget::Connect { addr, lazy: true, launch } => Box::new(cadcraft_mcp::Remote::lazy(&addr, launch)),
|
||||
McpTarget::Connect { addr, .. } => match cadcraft_mcp::Remote::connect(&addr) {
|
||||
Ok(r) => Box::new(r),
|
||||
Err(source) => return Err(CliError::McpConnect { addr, source }),
|
||||
},
|
||||
McpTarget::Headless { read_root, write_root } => {
|
||||
let roots = cadcraft_engine::file_access::AutomationRoots::new(
|
||||
read_root.as_deref().map(std::path::Path::new),
|
||||
write_root.as_deref().map(std::path::Path::new),
|
||||
)
|
||||
.map_err(CliError::AutomationRoots)?;
|
||||
Box::new(cadcraft_mcp::Headless::default().with_automation_roots(roots))
|
||||
McpTarget::Connect { addr, lazy, launch } => {
|
||||
let remote = if lazy {
|
||||
cadcraft_mcp::Remote::lazy(&addr, launch)
|
||||
} else {
|
||||
cadcraft_mcp::Remote::connect(&addr).map_err(|source| CliError::McpConnect { addr, source })?
|
||||
};
|
||||
// Once the bridge serves: a failed start says only why it failed.
|
||||
eprintln!(
|
||||
"cadcraft-cli: `mcp --connect` is deprecated and goes in a later release; plain `cadcraft-cli mcp` finds the open CADCraft window while ArtCraft Launcher › Settings › AI agents lets agents use it"
|
||||
);
|
||||
Box::new(remote)
|
||||
}
|
||||
McpTarget::Live { read_root, write_root, when_closed } => {
|
||||
match config_dir(a.settings.config_dir.as_deref()).filter(|_| cadcraft_mcp::live::mcp_flag()) {
|
||||
Some(dir) => {
|
||||
// Roots that can't be opened stop the server now, as they do headless.
|
||||
headless(read_root.as_deref(), write_root.as_deref())?;
|
||||
let mut cfg = cadcraft_mcp::LiveConfig::new(dir);
|
||||
cfg.when_closed = when_closed;
|
||||
cfg.read_root = read_root.map(PathBuf::from);
|
||||
cfg.write_root = write_root.map(PathBuf::from);
|
||||
cfg.launch = std::env::current_exe().ok().and_then(|cli| cadcraft_mcp::live::launcher(&cli));
|
||||
Box::new(cadcraft_mcp::Live::new(cfg))
|
||||
}
|
||||
// Without the suite's flag (or a settings folder) agents work without a window, as before.
|
||||
None => headless(read_root.as_deref(), write_root.as_deref())?,
|
||||
}
|
||||
}
|
||||
McpTarget::Headless { read_root, write_root } => headless(read_root.as_deref(), write_root.as_deref())?,
|
||||
};
|
||||
let stdin = std::io::stdin();
|
||||
let stdout = std::io::stdout();
|
||||
cadcraft_mcp::Server::new(backend).serve(stdin.lock(), stdout.lock())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A headless session held to the roots given, if any.
|
||||
fn headless(read_root: Option<&str>, write_root: Option<&str>) -> Result<Box<dyn cadcraft_mcp::Backend>> {
|
||||
let roots =
|
||||
cadcraft_engine::file_access::AutomationRoots::new(read_root.map(Path::new), write_root.map(Path::new)).map_err(CliError::AutomationRoots)?;
|
||||
Ok(Box::new(cadcraft_mcp::Headless::default().with_automation_roots(roots)))
|
||||
}
|
||||
|
||||
/// The app's settings folder, where it publishes the agent connection: `--config-dir` or
|
||||
/// `CADCRAFT_CONFIG_DIR` (`given`; blank: none), else a portable copy's `CADCraftData` beside the
|
||||
/// CLI, else the platform's, as the app resolves it.
|
||||
fn config_dir(given: Option<&Path>) -> Option<PathBuf> {
|
||||
let exe_dir = std::env::current_exe().ok().and_then(|p| p.parent().map(Path::to_path_buf));
|
||||
config_dir_from(given, exe_dir.as_deref(), |k| std::env::var_os(k))
|
||||
}
|
||||
|
||||
/// [`config_dir`] with the CLI in `exe_dir` and `var` looking the platform's variables up.
|
||||
fn config_dir_from(given: Option<&Path>, exe_dir: Option<&Path>, var: impl Fn(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
|
||||
match given {
|
||||
Some(dir) if dir.to_str().is_some_and(|d| d.trim().is_empty()) => None,
|
||||
Some(dir) => Some(dir.to_path_buf()),
|
||||
None => match exe_dir.filter(|d| d.join("portable.txt").is_file()) {
|
||||
Some(exe) => Some(exe.join("CADCraftData")),
|
||||
None => cadcraft_engine::settings_dir::platform(var),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::ffi::OsString;
|
||||
|
||||
/// The CLI looks for the connection where the app publishes it: `--config-dir` (or its
|
||||
/// variable), a portable copy's folder beside it, or the platform's.
|
||||
#[test]
|
||||
fn the_settings_folder_is_the_apps() {
|
||||
let exe = std::env::temp_dir().join(format!("cadcraft-cli-portable-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&exe);
|
||||
std::fs::create_dir_all(&exe).unwrap();
|
||||
let none = |_: &str| None::<OsString>;
|
||||
let given = Path::new("/private/cc");
|
||||
assert_eq!(config_dir_from(Some(given), Some(&exe), none), Some(given.to_path_buf()));
|
||||
assert_eq!(config_dir_from(Some(Path::new(" ")), Some(&exe), none), None);
|
||||
assert_eq!(config_dir_from(None, Some(&exe), none), cadcraft_engine::settings_dir::platform(none));
|
||||
std::fs::write(exe.join("portable.txt"), b"").unwrap();
|
||||
assert_eq!(config_dir_from(None, Some(&exe), none), Some(exe.join("CADCraftData")));
|
||||
assert_eq!(config_dir_from(Some(given), Some(&exe), none), Some(given.to_path_buf()), "the folder given wins");
|
||||
std::fs::remove_dir_all(exe).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,9 @@ fn mcp(args: &[&str], input: &str) -> Output {
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli"))
|
||||
.arg("mcp")
|
||||
.args(args)
|
||||
// No settings folder: plain `mcp` can't find a window and serves headless, whatever the
|
||||
// ArtCraft Launcher's switch says on this computer.
|
||||
.env("CADCRAFT_CONFIG_DIR", "")
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
@@ -81,6 +84,8 @@ fn connect_with_address_routes_to_that_endpoint() {
|
||||
assert!(instructions.contains(&format!("connected to CADCraft at {addr}")), "{instructions}");
|
||||
let text = r.iter().find(|v| v["id"] == 2).and_then(|v| v["result"]["content"][0]["text"].as_str()).unwrap_or_default();
|
||||
assert!(text.contains("loopback"), "{r:?}");
|
||||
// Still served for one release, with the way forward on stderr.
|
||||
assert!(String::from_utf8_lossy(&out.stderr).contains("`mcp --connect` is deprecated"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -151,7 +151,9 @@ fn subcommand_help_requests() {
|
||||
"mcp --help",
|
||||
&["mcp", "--help"],
|
||||
0,
|
||||
Line("Run the MCP server on stdio: a headless drawing session, or a bridge to the running app"),
|
||||
Line(
|
||||
"Run the MCP server on stdio: the open CADCraft window while ArtCraft Launcher › Settings › AI agents lets agents use it, otherwise a headless drawing session",
|
||||
),
|
||||
Empty,
|
||||
),
|
||||
case(
|
||||
|
||||
@@ -53,6 +53,8 @@ zbus = { version = "=5.19.0", default-features = false, features = ["async-io",
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
craft-update = { workspace = true }
|
||||
# The ArtCraft Launcher's switch and the agent link (main.rs `agents`).
|
||||
craft-automation = { workspace = true, features = ["ui", "agents"] }
|
||||
rfd = { workspace = true }
|
||||
sys-locale = "0.3"
|
||||
|
||||
|
||||
@@ -428,6 +428,32 @@ fn log_version() -> String {
|
||||
format!("{} ({})", reported_version(), option_env!("CADCRAFT_BUILD_SHA").unwrap_or("dev"))
|
||||
}
|
||||
|
||||
/// Agents in the open window: while the ArtCraft Launcher's switch (Settings › AI agents) names
|
||||
/// CADCraft, the agent link serves the control channel for `cadcraft-cli mcp` and publishes
|
||||
/// `agent-connection.json` in the settings folder (`cadcraft_ui_egui::agents`). `--control` manages
|
||||
/// its own server for the whole run instead. A Nightly build is not the app the launcher's switch
|
||||
/// names, so it takes no agents this way.
|
||||
fn agents(control_port: Option<u16>, settings_dir: Option<std::path::PathBuf>, ctx: &egui::Context) -> cadcraft_ui_egui::agents::Agents {
|
||||
use craft_automation::agents::{AgentLink, AgentSwitch, remove_stale_connection};
|
||||
if is_nightly() {
|
||||
return Default::default();
|
||||
}
|
||||
// A file a crashed launch left behind names a port nothing serves.
|
||||
if let Some(dir) = &settings_dir {
|
||||
remove_stale_connection(dir);
|
||||
}
|
||||
let wake = ctx.clone();
|
||||
// The launcher's app list names CADCraft by its catalog id.
|
||||
let switch = AgentSwitch::watch(profile_root::APP_ID, move || wake.request_repaint());
|
||||
match control_port {
|
||||
Some(port) => cadcraft_ui_egui::agents::Agents::managed_by_launch(port, switch, settings_dir),
|
||||
None => {
|
||||
let link = AgentLink::new(settings_dir.clone(), format!("CADCraft {}", cadcraft_engine::build_version()));
|
||||
cadcraft_ui_egui::agents::Agents::new(link, switch, settings_dir)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this start runs the isolated Nightly flavor.
|
||||
fn is_nightly() -> bool {
|
||||
launch_profile::current().is_nightly()
|
||||
@@ -768,6 +794,7 @@ fn main() -> eframe::Result {
|
||||
let rx = control_server::start(port, cc.egui_ctx.clone());
|
||||
app = app.with_control(rx);
|
||||
}
|
||||
app.agents = agents(control_port, vars.config_dir.clone(), &cc.egui_ctx);
|
||||
if sample {
|
||||
let _ = app.run("ui.sample", serde_json::json!({}));
|
||||
}
|
||||
|
||||
@@ -19,6 +19,8 @@ cadcraft-constraints = { workspace = true }
|
||||
cadcraft-fonts = { workspace = true }
|
||||
cadcraft-render = { workspace = true }
|
||||
craft-docpath = { workspace = true }
|
||||
# The agent settings (Options › AI Agents) the app and `cadcraft-cli mcp` share.
|
||||
craft-control = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
//! The agent settings of Options › AI Agents, shared by the app and `cadcraft-cli mcp`: the
|
||||
//! control port agents connect on, the folders they may open from and save to, and what the CLI
|
||||
//! does while CADCraft is closed. They are kept in [`FILE`] in the settings folder, beside the
|
||||
//! connection file the app publishes for agents, so the CLI reads them without the app.
|
||||
//!
|
||||
//! Only the person changes them, in the Options dialog: the OPTIONS JSON form has no such keys,
|
||||
//! so an agent can't widen its own folders through a command.
|
||||
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub use craft_control::agents::{AgentSettings, WhenAppClosed};
|
||||
|
||||
use crate::file_access::AutomationRoots;
|
||||
|
||||
/// The settings file in the settings folder.
|
||||
pub const FILE: &str = "agent-settings.json";
|
||||
|
||||
/// The largest settings file read; the settings are a few short fields.
|
||||
const MAX_BYTES: usize = 64 * 1024;
|
||||
|
||||
/// The agent settings saved in the settings folder `dir`; the defaults when none are saved or the
|
||||
/// file can't be read (the reason is logged), so neither the app nor the CLI fails over them.
|
||||
pub fn load(dir: &Path) -> AgentSettings {
|
||||
let path = dir.join(FILE);
|
||||
match crate::capped_read::read_capped(&path, MAX_BYTES) {
|
||||
Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|e| {
|
||||
log::warn!("agent settings {}: {e}; using the defaults", path.display());
|
||||
AgentSettings::default()
|
||||
}),
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => AgentSettings::default(),
|
||||
Err(e) => {
|
||||
log::warn!("agent settings {}: {e}; using the defaults", path.display());
|
||||
AgentSettings::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Saves `settings` in the settings folder `dir` (made if missing), replacing the file whole.
|
||||
pub fn save(dir: &Path, settings: &AgentSettings) -> io::Result<()> {
|
||||
let json = serde_json::to_vec_pretty(settings).map_err(io::Error::other)?;
|
||||
crate::atomic_write::write_atomic_making_folders(&dir.join(FILE), &json)
|
||||
}
|
||||
|
||||
/// The roots agent requests run in, for the agent folders `read` and `write`. A folder that is
|
||||
/// missing or can't be opened grants nothing in its direction, and with neither every file is
|
||||
/// refused: leaving the roots out would confine nothing. The error names the folders that could
|
||||
/// not be used.
|
||||
pub fn roots(read: Option<&Path>, write: Option<&Path>) -> (Arc<AutomationRoots>, Option<String>) {
|
||||
let mut problems = Vec::new();
|
||||
let read = read.filter(|r| AutomationRoots::new(Some(r), None).map_err(|e| problems.push(e)).is_ok());
|
||||
let write = write.filter(|w| AutomationRoots::new(None, Some(w)).map_err(|e| problems.push(e)).is_ok());
|
||||
let roots = AutomationRoots::new(read, write).ok().flatten().unwrap_or_else(AutomationRoots::none);
|
||||
(roots, (!problems.is_empty()).then(|| problems.join("; ")))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
use crate::file_access::{check_read, check_write, confine};
|
||||
|
||||
fn temp(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-agent-settings-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// What the dialog saves is what the CLI reads; a damaged file reads as the defaults.
|
||||
#[test]
|
||||
fn saved_settings_read_back_and_a_damaged_file_is_the_defaults() {
|
||||
let dir = temp("round-trip");
|
||||
let mut settings = AgentSettings::default();
|
||||
settings.read_root = "/agents/in".into();
|
||||
settings.when_app_closed = WhenAppClosed::Headless;
|
||||
save(&dir, &settings).unwrap();
|
||||
assert_eq!(load(&dir), settings);
|
||||
std::fs::write(dir.join(FILE), b"{not json").unwrap();
|
||||
assert_eq!(load(&dir), AgentSettings::default());
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
/// Agent folders that can't be used refuse every file instead of confining nothing.
|
||||
#[test]
|
||||
fn folders_that_cannot_be_used_refuse_every_file() {
|
||||
let dir = temp("roots");
|
||||
let file = dir.join("plan.dxf");
|
||||
let (roots, problem) = roots(Some(&dir.join("missing")), None);
|
||||
assert!(problem.is_some());
|
||||
confine(Some(&roots), || {
|
||||
assert!(check_read(&file).is_err());
|
||||
assert!(check_write(&file).is_err());
|
||||
});
|
||||
let (roots, problem) = super::roots(Some(&dir), Some(&dir.join("gone")));
|
||||
assert!(problem.is_some(), "the missing write folder is named");
|
||||
confine(Some(&roots), || {
|
||||
assert!(check_read(&file).is_ok(), "the usable read folder still applies");
|
||||
assert!(check_write(&file).is_err());
|
||||
});
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -74,6 +74,12 @@ impl AutomationRoots {
|
||||
Ok(Some(Arc::new(Self { read, write })))
|
||||
}
|
||||
|
||||
/// Roots that grant nothing: every read and write is refused. For agents whose folders can't
|
||||
/// be used, where leaving the roots out would confine nothing.
|
||||
pub fn none() -> Arc<Self> {
|
||||
Arc::new(Self { read: None, write: None })
|
||||
}
|
||||
|
||||
/// The read root, absolute with its links followed.
|
||||
pub fn read_root(&self) -> Option<&Path> {
|
||||
self.read.as_deref()
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
//! [`Session::input`], [`Session::cmdline`]) exactly like typing at AutoCAD's command line.
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![forbid(unsafe_code)]
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod agent_settings;
|
||||
pub mod array_live;
|
||||
|
||||
pub mod assoc;
|
||||
|
||||
@@ -11,6 +11,10 @@ workspace = true
|
||||
[dependencies]
|
||||
craft-mcp = { workspace = true }
|
||||
craft-jsonrpc = { workspace = true }
|
||||
# The live client: tool calls go to the open window while the ArtCraft Launcher's switch allows it.
|
||||
craft-control = { workspace = true, features = ["agents"] }
|
||||
# The challenge handshake of the window's agent server (`craft_automation::security`; no egui without `ui`).
|
||||
craft-automation = { workspace = true }
|
||||
cadcraft-engine = { workspace = true }
|
||||
cadcraft-render = { workspace = true }
|
||||
cadcraft-io = { workspace = true }
|
||||
|
||||
+107
-4
@@ -2,6 +2,7 @@
|
||||
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::{Ipv4Addr, SocketAddr, TcpStream, ToSocketAddrs};
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -18,6 +19,9 @@ pub trait Backend {
|
||||
fn has_ui(&self) -> bool;
|
||||
/// Describe the backend connection for client-facing status.
|
||||
fn describe(&self) -> String;
|
||||
/// The `agent_folders` tool's answer: the folders this session may open from and save to, and
|
||||
/// whether files outside them are refused ([`crate::live::folders_reply`]).
|
||||
fn agent_folders(&mut self) -> Result<Value, String>;
|
||||
}
|
||||
|
||||
/// A running CADCraft app reached through its loopback control port.
|
||||
@@ -35,6 +39,10 @@ pub struct Remote {
|
||||
authed: bool,
|
||||
/// Longest reply line accepted (`MAX_REPLY_LINE`; smaller in tests).
|
||||
max_reply: usize,
|
||||
/// The open window's agent server ([`Remote::signed_in`]): each connection signs in once with
|
||||
/// the challenge handshake and this token, which never crosses the wire. `None`: the `--control`
|
||||
/// server, which takes the token from its token file on every request.
|
||||
handshake: Option<String>,
|
||||
}
|
||||
|
||||
/// The port component of a `HOST:PORT` address, for locating the token file.
|
||||
@@ -42,6 +50,15 @@ fn port_of(addr: &str) -> Option<u16> {
|
||||
addr.rsplit(':').next().and_then(|p| p.parse::<u16>().ok())
|
||||
}
|
||||
|
||||
/// How long a reply may take; the app answers a request within its own 60 s deadline.
|
||||
const REPLY_WAIT: Duration = Duration::from_secs(90);
|
||||
|
||||
/// How long each sign-in reply of the agent server may take.
|
||||
const SIGN_IN_WAIT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// Longest sign-in reply read (two nonces and a proof).
|
||||
const SIGN_IN_REPLY: usize = 64 * 1024;
|
||||
|
||||
/// How long a launched app has to open its control port.
|
||||
const LAUNCH_WAIT: Duration = Duration::from_secs(30);
|
||||
|
||||
@@ -67,7 +84,17 @@ fn read_reply_line(reader: &mut impl BufRead, reply: &mut String, max: usize) ->
|
||||
impl Remote {
|
||||
/// Connect to a running control server; its session token is read lazily when the first request is sent.
|
||||
pub fn connect(addr: &str) -> std::io::Result<Self> {
|
||||
let mut r = Self { addr: addr.to_string(), conn: None, next_id: 1, launch: false, token: None, authed: false, max_reply: MAX_REPLY_LINE };
|
||||
let mut r = Self::lazy(addr, false);
|
||||
r.reconnect()?;
|
||||
Ok(r)
|
||||
}
|
||||
/// The open window's agent server at `addr` (`127.0.0.1:<port>` from the connection file the
|
||||
/// app publishes while the ArtCraft Launcher's switch lets agents in), signed in with the
|
||||
/// challenge handshake and `token` from the token file it names: the app proves it holds the
|
||||
/// token before anything derived from it is sent, so a program that took the port of an app
|
||||
/// that quit learns nothing.
|
||||
pub fn signed_in(addr: &str, token: String) -> std::io::Result<Self> {
|
||||
let mut r = Self { handshake: Some(token), ..Self::lazy(addr, false) };
|
||||
r.reconnect()?;
|
||||
Ok(r)
|
||||
}
|
||||
@@ -75,7 +102,7 @@ impl Remote {
|
||||
/// the server before the app is open. With `launch`, a call that finds nothing at `addr`
|
||||
/// opens the app with that control port first (macOS) and waits for it.
|
||||
pub fn lazy(addr: &str, launch: bool) -> Self {
|
||||
Self { addr: addr.to_string(), conn: None, next_id: 1, launch, token: None, authed: false, max_reply: MAX_REPLY_LINE }
|
||||
Self { addr: addr.to_string(), conn: None, next_id: 1, launch, token: None, authed: false, max_reply: MAX_REPLY_LINE, handshake: None }
|
||||
}
|
||||
|
||||
/// The per-session token for this port, read (and cached) from the owner-only token file. A
|
||||
@@ -86,6 +113,10 @@ impl Remote {
|
||||
/// peer: a name that also resolves elsewhere (`localhost` → `::1`, where another local account
|
||||
/// may listen on the same port) must not be handed the desktop's credential (CWE-522).
|
||||
fn token(&mut self) -> Option<&str> {
|
||||
// The agent server took the handshake: no request carries the token.
|
||||
if self.handshake.is_some() {
|
||||
return None;
|
||||
}
|
||||
let port = port_of(&self.addr)?;
|
||||
let peer = self.conn.as_ref().and_then(|(_, s)| s.peer_addr().ok());
|
||||
if peer != Some(SocketAddr::from((Ipv4Addr::LOCALHOST, port))) {
|
||||
@@ -131,9 +162,12 @@ impl Remote {
|
||||
match TcpStream::connect_timeout(&sa, Duration::from_millis(800)) {
|
||||
Ok(s) => {
|
||||
s.set_nodelay(true).ok();
|
||||
s.set_read_timeout(Some(Duration::from_secs(90))).ok();
|
||||
s.set_read_timeout(Some(REPLY_WAIT)).ok();
|
||||
let read = s.try_clone()?;
|
||||
self.conn = Some((BufReader::new(read), s));
|
||||
if let Some(token) = self.handshake.clone() {
|
||||
return self.sign_in(&token).inspect_err(|_| self.conn = None);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) => last = e,
|
||||
@@ -141,6 +175,52 @@ impl Remote {
|
||||
}
|
||||
Err(last)
|
||||
}
|
||||
/// The challenge handshake of the agent server (`craft_automation::security`) on the new
|
||||
/// connection: send a nonce, check the app's proof that it holds the token, then send this
|
||||
/// side's proof.
|
||||
fn sign_in(&mut self, token: &str) -> std::io::Result<()> {
|
||||
use craft_automation::security::{AUTH_METHOD, CHALLENGE_METHOD, ProofRole, generate_nonce, handshake_proof, proof_matches};
|
||||
let addr = self.addr.clone();
|
||||
let refused =
|
||||
|why: &str| std::io::Error::new(std::io::ErrorKind::PermissionDenied, format!("CADCraft at {addr} refused the agent connection: {why}"));
|
||||
let client_nonce = generate_nonce().map_err(|e| std::io::Error::other(e.to_string()))?;
|
||||
let challenge = self.sign_in_frame(CHALLENGE_METHOD, json!({"clientNonce": client_nonce}))?;
|
||||
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(token, ProofRole::Server, &client_nonce, &server_nonce, &server_proof) {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
format!("the program on {addr} did not prove it is the CADCraft that published the agent connection; start CADCraft again"),
|
||||
));
|
||||
}
|
||||
let proof = handshake_proof(token, ProofRole::Client, &client_nonce, &server_nonce).map_err(|e| std::io::Error::other(e.to_string()))?;
|
||||
let signed = self.sign_in_frame(AUTH_METHOD, json!({"proof": proof}))?;
|
||||
if signed.get("ok") != Some(&Value::Bool(true)) {
|
||||
return Err(refused(signed.get("error").and_then(Value::as_str).unwrap_or("authentication failed")));
|
||||
}
|
||||
self.authed = true;
|
||||
Ok(())
|
||||
}
|
||||
/// One sign-in frame (id 0; requests count from 1) and its reply, within [`SIGN_IN_WAIT`].
|
||||
fn sign_in_frame(&mut self, method: &str, params: Value) -> std::io::Result<Value> {
|
||||
let addr = self.addr.clone();
|
||||
let Some((reader, writer)) = self.conn.as_mut() else { return Err(std::io::Error::other("not connected")) };
|
||||
writer.set_read_timeout(Some(SIGN_IN_WAIT)).ok();
|
||||
writeln!(writer, "{}", json!({"id": 0, "method": method, "params": params}))?;
|
||||
writer.flush()?;
|
||||
let mut reply = String::new();
|
||||
let n = read_reply_line(reader, &mut reply, SIGN_IN_REPLY)?;
|
||||
writer.set_read_timeout(Some(REPLY_WAIT)).ok();
|
||||
if n == 0 {
|
||||
return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, format!("{addr} closed the connection during the sign-in")));
|
||||
}
|
||||
serde_json::from_str(&reply).map_err(|_| {
|
||||
std::io::Error::new(std::io::ErrorKind::InvalidData, format!("{addr} did not answer the sign-in; is that CADCraft's agent connection?"))
|
||||
})
|
||||
}
|
||||
/// On failure the flag says whether the request may already have reached the server.
|
||||
fn roundtrip(&mut self, line: &str) -> Result<String, (std::io::Error, bool)> {
|
||||
if self.conn.is_none() {
|
||||
@@ -230,6 +310,11 @@ impl Remote {
|
||||
}
|
||||
self.set_token(req);
|
||||
let line = req.to_string();
|
||||
// The agent server refuses a longer line and closes the connection; nothing was sent.
|
||||
if self.handshake.is_some() && line.len() > craft_automation::security::MAX_REQUEST_BYTES {
|
||||
let why = format!("the request is longer than the {} bytes the agent connection takes", craft_automation::security::MAX_REQUEST_BYTES);
|
||||
return Err((std::io::Error::new(std::io::ErrorKind::InvalidInput, why), false));
|
||||
}
|
||||
if !self.authed && line.len() > crate::control_token::MAX_UNAUTHENTICATED_LINE {
|
||||
let mut ping = json!({"id": req.get("id").cloned().unwrap_or(Value::Null), "method": "ping"});
|
||||
self.set_token(&mut ping);
|
||||
@@ -333,7 +418,18 @@ impl Backend for Remote {
|
||||
}
|
||||
/// What this backend talks to, for messages.
|
||||
fn describe(&self) -> String {
|
||||
format!("connected to CADCraft at {}", self.addr)
|
||||
if self.handshake.is_some() {
|
||||
format!("the open CADCraft window at {}", self.addr)
|
||||
} else {
|
||||
format!("connected to CADCraft at {}", self.addr)
|
||||
}
|
||||
}
|
||||
/// The window's agent server holds requests to Options › AI Agents' folders; `--control` to none.
|
||||
fn agent_folders(&mut self) -> Result<Value, String> {
|
||||
if self.handshake.is_some() {
|
||||
return Err("the window holds agents to the folders of Options › AI Agents; `cadcraft-cli mcp` answers `agent_folders` for it".into());
|
||||
}
|
||||
Ok(crate::live::folders_reply(&craft_control::agents::AgentFolders::default(), false))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -525,6 +621,13 @@ impl Backend for Headless {
|
||||
fn describe(&self) -> String {
|
||||
"headless CADCraft session".into()
|
||||
}
|
||||
/// The automation roots it runs in, if any.
|
||||
fn agent_folders(&mut self) -> Result<Value, String> {
|
||||
let mut folders = craft_control::agents::AgentFolders::default();
|
||||
folders.read = self.roots.as_ref().and_then(|r| r.read_root().map(Path::to_path_buf));
|
||||
folders.write = self.roots.as_ref().and_then(|r| r.write_root().map(Path::to_path_buf));
|
||||
Ok(crate::live::folders_reply(&folders, self.roots.is_some()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -11,10 +11,12 @@
|
||||
pub mod args;
|
||||
mod backend;
|
||||
pub mod control_token;
|
||||
pub mod live;
|
||||
mod server;
|
||||
mod tools;
|
||||
|
||||
pub use backend::{Backend, Headless, Remote};
|
||||
pub use live::{Live, LiveConfig};
|
||||
pub use server::{PROTOCOL_VERSION, Server};
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
//! Plain `cadcraft-cli mcp` with the suite's `AI-MCP` flag: tools go to the open CADCraft 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, Options › AI Agents › When CADCraft 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 drawing doesn't move under the agent.
|
||||
//!
|
||||
//! The lookup is the framework's, shared by every Craft app ([`craft_control::agents::Live`]); this
|
||||
//! module supplies CADCraft's parts: where its settings are, its window client
|
||||
//! ([`Remote::signed_in`]) and its headless session ([`Headless`]).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
use cadcraft_engine::agent_settings;
|
||||
use cadcraft_engine::file_access::AutomationRoots;
|
||||
use craft_control::agents::{self, AgentFolders, Consent, HeadlessFolders, Route, Window};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub use craft_control::agents::{LAUNCH_TIMEOUT, LaunchFn, WhenAppClosed, mcp_flag};
|
||||
|
||||
use crate::backend::{Backend, Headless, Remote};
|
||||
|
||||
/// The id the ArtCraft Launcher's app list names CADCraft by (its catalog id).
|
||||
pub const LAUNCHER_APP_ID: &str = "cadcraft";
|
||||
/// The app's name in the lookup's messages and in its default agent folder,
|
||||
/// `Documents/ArtCraft/Agents/CADCraft`.
|
||||
pub const APP_NAME: &str = "CADCraft";
|
||||
/// The desktop app's file name beside the CLI (without `.exe`).
|
||||
const APP_EXE: &str = "cadcraft";
|
||||
|
||||
/// Whether agents may use the open window now: with the suite's `AI-MCP` flag, the ArtCraft
|
||||
/// Launcher's switch. CADCraft had no agent consent of its own before the switch (`--control` is a
|
||||
/// launch option, not a consent), so without the flag agents get no window this way.
|
||||
pub fn agents_allowed_now() -> bool {
|
||||
agents::agents_allowed(agents::mcp_flag(), agents::launcher_allows(LAUNCHER_APP_ID), false)
|
||||
}
|
||||
|
||||
/// The default agent folder, `Documents/ArtCraft/Agents/CADCraft`.
|
||||
pub fn default_folder() -> Option<PathBuf> {
|
||||
agents::default_folder(APP_NAME)
|
||||
}
|
||||
|
||||
/// The folders the open window holds agent requests to: Options › AI Agents' folders, the default
|
||||
/// agent folder for an empty one (made when used). The app uses the same.
|
||||
pub fn window_folders(settings: &agent_settings::AgentSettings, default: Option<&Path>) -> AgentFolders {
|
||||
settings.folders_with(default)
|
||||
}
|
||||
|
||||
/// The `agent_folders` tool's answer: the folders, and whether files outside them are refused.
|
||||
pub fn folders_reply(folders: &AgentFolders, confined: bool) -> Value {
|
||||
let mut answer = agents::folders_answer(folders);
|
||||
answer["confined"] = json!(confined);
|
||||
if !confined {
|
||||
answer["note"] = json!("This session is not held to folders: keep to the files the person gave you.");
|
||||
}
|
||||
answer
|
||||
}
|
||||
|
||||
/// What [`Live`] needs from the CLI.
|
||||
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<WhenAppClosed>,
|
||||
/// The CLI's `--automation-read-root` and `--automation-write-root`.
|
||||
pub read_root: Option<PathBuf>,
|
||||
pub write_root: Option<PathBuf>,
|
||||
/// Starts the app; `None` when this install can't (no app beside the CLI).
|
||||
pub launch: Option<LaunchFn>,
|
||||
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 ([`default_folder`]); tests replace it.
|
||||
pub default_folder: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl LiveConfig {
|
||||
/// The lookup for the app with its settings in `config_dir`.
|
||||
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: default_folder(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A session without a window and the folders it is held to.
|
||||
struct HeadlessSession {
|
||||
backend: Headless,
|
||||
folders: AgentFolders,
|
||||
confined: bool,
|
||||
}
|
||||
|
||||
type Shared = agents::Live<Arc<Mutex<Remote>>, Arc<Mutex<HeadlessSession>>>;
|
||||
|
||||
/// The backend of plain `cadcraft-cli mcp` with the `AI-MCP` flag: each call goes where
|
||||
/// [`craft_control::agents::Live::resolve`] says.
|
||||
pub struct Live {
|
||||
shared: Shared,
|
||||
config_dir: PathBuf,
|
||||
default_folder: Option<PathBuf>,
|
||||
allowed: fn() -> bool,
|
||||
}
|
||||
|
||||
impl Live {
|
||||
/// The lookup with `cfg`; nothing is looked up until the first call.
|
||||
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(), agent_settings::load(dir));
|
||||
let connect = |w: &Window| Remote::signed_in(&w.addr(), w.token.clone()).map(|r| Arc::new(Mutex::new(r))).map_err(|e| e.to_string());
|
||||
let headless = move |folders: &HeadlessFolders| headless_session(folders, allowed()).map(|h| Arc::new(Mutex::new(h)));
|
||||
let mut shared = agents::LiveConfig::new(APP_NAME, config_dir.clone(), consent, connect, headless);
|
||||
shared.when_closed = when_closed;
|
||||
shared.read_roots = read_root.into_iter().collect();
|
||||
shared.write_root = write_root;
|
||||
shared.launch = launch;
|
||||
shared.launch_timeout = launch_timeout;
|
||||
shared.default_folder = default_folder.clone();
|
||||
Live { shared: agents::Live::new(shared), config_dir, default_folder, allowed }
|
||||
}
|
||||
}
|
||||
|
||||
/// The headless session for `folders`. Without folders it is held to none, as `mcp` always was,
|
||||
/// unless agents are `allowed`: then the folders are the app's agent folders, and having none
|
||||
/// (the default folder couldn't be made) refuses every file rather than none.
|
||||
fn headless_session(folders: &HeadlessFolders, allowed: bool) -> Result<HeadlessSession, String> {
|
||||
// The CLI takes one read root, and the agent settings name one read folder.
|
||||
let read = folders.read.first().map(PathBuf::as_path);
|
||||
let write = folders.write.as_deref();
|
||||
let roots = match AutomationRoots::new(read, write)? {
|
||||
Some(roots) => Some(roots),
|
||||
None if allowed => Some(AutomationRoots::none()),
|
||||
None => None,
|
||||
};
|
||||
let mut shown = AgentFolders::default();
|
||||
shown.read = read.map(Path::to_path_buf);
|
||||
shown.write = write.map(Path::to_path_buf);
|
||||
Ok(HeadlessSession { confined: roots.is_some(), backend: Headless::default().with_automation_roots(roots), folders: shown })
|
||||
}
|
||||
|
||||
impl Backend for Live {
|
||||
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
|
||||
match self.shared.resolve()? {
|
||||
Route::Window(window) => window.lock().unwrap_or_else(PoisonError::into_inner).call(method, params),
|
||||
Route::Headless(session) => session.lock().unwrap_or_else(PoisonError::into_inner).backend.call(method, params),
|
||||
}
|
||||
}
|
||||
/// A window may answer while agents are allowed and the session hasn't gone headless.
|
||||
fn has_ui(&self) -> bool {
|
||||
match self.shared.current() {
|
||||
Some(Route::Window(_)) => true,
|
||||
Some(Route::Headless(_)) => false,
|
||||
None => (self.allowed)(),
|
||||
}
|
||||
}
|
||||
fn describe(&self) -> String {
|
||||
match self.shared.current() {
|
||||
Some(Route::Window(window)) => window.lock().unwrap_or_else(PoisonError::into_inner).describe(),
|
||||
Some(Route::Headless(session)) => session.lock().unwrap_or_else(PoisonError::into_inner).backend.describe(),
|
||||
None => "the open CADCraft window while ArtCraft Launcher › Settings › AI agents lets agents use it, otherwise a headless session".into(),
|
||||
}
|
||||
}
|
||||
fn agent_folders(&mut self) -> Result<Value, String> {
|
||||
match self.shared.resolve()? {
|
||||
Route::Window(_) => {
|
||||
let settings = agent_settings::load(&self.config_dir);
|
||||
Ok(folders_reply(&window_folders(&settings, self.default_folder.as_deref()), true))
|
||||
}
|
||||
Route::Headless(session) => {
|
||||
let session = session.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
Ok(folders_reply(&session.folders, session.confined))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How to start the desktop app that ships with the CLI at `cli` (detached, with no standard
|
||||
/// streams: the CLI's carry the MCP protocol, and the app must outlive the MCP client).
|
||||
pub fn launcher(cli: &Path) -> Option<LaunchFn> {
|
||||
agents::launcher(cli, APP_EXE)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use super::*;
|
||||
use craft_automation::security::{AuthStep, ServerHandshake};
|
||||
use craft_control::agents::{Connection, TOKEN_FILE, write_connection};
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpListener;
|
||||
|
||||
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
const OTHER: &str = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210";
|
||||
|
||||
fn temp(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-live-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// A stand-in for the window's agent server (`craft_automation::server`): the challenge
|
||||
/// handshake with `token`, then every request answered `{"window": true}`. Returns the port and
|
||||
/// every line it read.
|
||||
fn agent_server(token: &'static str) -> (u16, Arc<Mutex<Vec<Value>>>) {
|
||||
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 = Arc::clone(&seen);
|
||||
std::thread::spawn(move || {
|
||||
for conn in listener.incoming() {
|
||||
let Ok(conn) = conn else { continue };
|
||||
let log = Arc::clone(&log);
|
||||
std::thread::spawn(move || {
|
||||
let mut out = conn.try_clone().unwrap();
|
||||
let mut handshake = ServerHandshake::new();
|
||||
let mut signed_in = false;
|
||||
for line in BufReader::new(conn).lines() {
|
||||
let Ok(line) = line else { return };
|
||||
let req: Value = serde_json::from_str(&line).unwrap();
|
||||
log.lock().unwrap().push(req.clone());
|
||||
let reply = if signed_in {
|
||||
json!({"id": req["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)
|
||||
}
|
||||
|
||||
/// Publish a window on `port` in `dir` with `token` in its token file, as the app's link does.
|
||||
fn publish(dir: &Path, port: u16, token: &str) {
|
||||
let token_file = dir.join(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();
|
||||
}
|
||||
write_connection(dir, &Connection::new(port, token_file, "CADCraft test")).unwrap();
|
||||
}
|
||||
|
||||
fn live(dir: &Path, allowed: fn() -> bool, when_closed: Option<WhenAppClosed>) -> Live {
|
||||
let mut cfg = LiveConfig::new(dir.to_path_buf());
|
||||
cfg.allowed = allowed;
|
||||
cfg.when_closed = when_closed;
|
||||
cfg.default_folder = Some(dir.join("Agents"));
|
||||
Live::new(cfg)
|
||||
}
|
||||
|
||||
/// With the window published, calls go to it after the challenge handshake, and nothing sent
|
||||
/// carries the token.
|
||||
#[test]
|
||||
fn live_calls_go_to_the_open_window_while_the_switch_allows() {
|
||||
let dir = temp("window");
|
||||
let (port, seen) = agent_server(TOKEN);
|
||||
publish(&dir, port, TOKEN);
|
||||
let mut live = live(&dir, || true, None);
|
||||
assert_eq!(live.call("ping", json!({})), Ok(json!({"window": true})));
|
||||
assert_eq!(live.call("drawing.inspect", json!({})), Ok(json!({"window": true})));
|
||||
assert!(live.has_ui());
|
||||
let seen = seen.lock().unwrap();
|
||||
assert!(seen.iter().any(|req| req["method"] == "drawing.inspect"), "{seen:?}");
|
||||
assert!(!serde_json::to_string(&*seen).unwrap().contains(TOKEN), "the token crossed the wire: {seen:?}");
|
||||
drop(seen);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// While the launcher's switch doesn't let agents in and no window is published, calls work
|
||||
/// without a window, as plain `mcp` always did, held to no folders the command didn't give.
|
||||
#[test]
|
||||
fn live_without_the_switch_works_without_a_window() {
|
||||
let dir = temp("no-switch");
|
||||
let mut live = live(&dir, || false, None);
|
||||
assert_eq!(live.call("ping", json!({})), Ok(json!("pong")));
|
||||
assert!(!live.has_ui());
|
||||
assert_eq!(live.agent_folders().unwrap()["confined"], json!(false));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// A connection file a crashed app left behind (nothing listens on its port) is not a window:
|
||||
/// the closed-app choice decides, and a headless session is held to the agent folders.
|
||||
#[test]
|
||||
fn live_with_the_app_closed_follows_the_closed_app_choice() {
|
||||
let dir = temp("closed");
|
||||
let gone = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = gone.local_addr().unwrap().port();
|
||||
drop(gone);
|
||||
publish(&dir, port, TOKEN);
|
||||
|
||||
let err = live(&dir, || true, Some(WhenAppClosed::Error)).call("ping", json!({})).unwrap_err();
|
||||
assert!(err.contains("isn't running"), "{err}");
|
||||
|
||||
let mut headless = live(&dir, || true, Some(WhenAppClosed::Headless));
|
||||
assert_eq!(headless.call("ping", json!({})), Ok(json!("pong")));
|
||||
let folders = headless.agent_folders().unwrap();
|
||||
assert_eq!(folders["confined"], json!(true));
|
||||
assert_eq!(folders["write_folder"], json!(dir.join("Agents").to_string_lossy()));
|
||||
let outside = dir.parent().unwrap().join("outside.png");
|
||||
let err = headless.call("ui.render", json!({"path": outside.to_string_lossy()})).unwrap_err();
|
||||
assert!(err.contains("outside the write root"), "a file outside the agent folder is refused: {err}");
|
||||
let inside = dir.join("Agents").join("plan.png");
|
||||
assert!(headless.call("ui.render", json!({"path": inside.to_string_lossy()})).is_ok(), "one inside it is written");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// A program on the published port that doesn't hold the token gets nothing from the client:
|
||||
/// it can't prove itself, so no request is sent.
|
||||
#[test]
|
||||
fn a_window_without_the_token_is_refused() {
|
||||
let dir = temp("bad-token");
|
||||
let (port, seen) = agent_server(OTHER);
|
||||
publish(&dir, port, TOKEN);
|
||||
let err = live(&dir, || true, Some(WhenAppClosed::Error)).call("drawing.inspect", json!({})).unwrap_err();
|
||||
assert!(err.contains("did not prove"), "{err}");
|
||||
assert!(seen.lock().unwrap().iter().all(|req| req["method"] != "drawing.inspect"));
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,7 @@ pub fn tool_definitions(has_ui: bool) -> Value {
|
||||
json!({"name": "open", "description": "Open a DXF or DWG file.", "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}),
|
||||
json!({"name": "save", "description": "Save the drawing (DXF or DWG by extension). A .svg, .png or .pdf path exports instead: the drawing keeps its name and unsaved changes.", "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}}}),
|
||||
json!({"name": "cancel", "description": "Press Escape: cancel the running command (or clear the selection).", "inputSchema": {"type": "object", "properties": {}}}),
|
||||
craft_control::agents::folders_tool(),
|
||||
];
|
||||
if has_ui {
|
||||
tools.push(json!({"name": "screenshot", "description": "Screenshot the CADCraft window (PNG).", "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}}}));
|
||||
@@ -137,6 +138,7 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> Result<Value,
|
||||
"open" => b.call("app.open", a),
|
||||
"save" => b.call("app.save", a),
|
||||
"cancel" => b.call("cmdline.key", json!({"key": "escape"})),
|
||||
craft_control::agents::FOLDERS_TOOL => b.agent_folders(),
|
||||
"screenshot" => b.call("ui.screenshot", a),
|
||||
"ui_inspect" => b.call("ui.inspect", json!({})),
|
||||
"ui_click" => b.call("ui.pointer", a),
|
||||
|
||||
@@ -37,6 +37,9 @@ web-time = { workspace = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
craft-update = { workspace = true }
|
||||
# Agents in the open window: the agent link host and the Agents page of Options.
|
||||
craft-automation = { workspace = true, features = ["ui", "agents"] }
|
||||
craft-control = { workspace = true, features = ["agents"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# `Updater::ready_for_tests`.
|
||||
|
||||
@@ -0,0 +1,487 @@
|
||||
//! Agents in the open window. While the ArtCraft Launcher's switch (Settings › AI agents) lets agents
|
||||
//! use CADCraft, the app 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; `cadcraft-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 Agents page are the framework's
|
||||
//! (`craft_automation::agents`, `craft_automation::ui::agents`); CADCraft runs the requests through
|
||||
//! its own control methods ([`crate::control::handle`]), held to the agent folders of Options › AI
|
||||
//! Agents ([`Agents::roots`]), as the headless server is held to its automation roots.
|
||||
//!
|
||||
//! `cadcraft --control` manages its own server for the whole run instead; the Agents page then says
|
||||
//! the launch options manage the connection.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc::Receiver;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use cadcraft_engine::agent_settings::{self, AgentSettings};
|
||||
use cadcraft_engine::file_access::AutomationRoots;
|
||||
use craft_automation::agents::{AgentLink, AgentLinkStatus, AgentSwitch, LinkProblem};
|
||||
use craft_ui::runtime::windows::WindowHost;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::control::ControlRequest;
|
||||
|
||||
/// The agent link, the switch it follows, the agent settings and the requests of the server it runs.
|
||||
pub struct Agents {
|
||||
link: Option<AgentLink>,
|
||||
switch: Option<AgentSwitch>,
|
||||
requests: Option<Receiver<craft_automation::ControlRequest>>,
|
||||
/// `--control` runs a server of its own: the page names the launch options.
|
||||
launch_flags: Option<u16>,
|
||||
/// Where the agent settings are saved; `None`: nowhere (no settings folder).
|
||||
settings_dir: Option<PathBuf>,
|
||||
settings: AgentSettings,
|
||||
/// The default agent folder for an empty folder setting, `Documents/ArtCraft/Agents/CADCraft`.
|
||||
default_folder: Option<PathBuf>,
|
||||
/// What agent requests may read and write, from the settings' folders.
|
||||
roots: Arc<AutomationRoots>,
|
||||
/// Another CADCraft window with the same settings folder serves agents: this one waits, and
|
||||
/// takes over once that window has closed ([`Self::sync`]).
|
||||
other_window: bool,
|
||||
/// When the last look for another window was, and how often to look.
|
||||
looked: Option<Instant>,
|
||||
look_every: Duration,
|
||||
/// The app named in a connection this window publishes again ([`Self::sync`]).
|
||||
app: String,
|
||||
/// The AI Agents tab was shown in a pass with agent folders in force (an agent opened or drove
|
||||
/// it): until the person shows it afresh, nothing typed there is saved, also when a later pass
|
||||
/// commits it ([`Self::page_shown`]).
|
||||
page_tainted: bool,
|
||||
/// The frame the tab was last shown in.
|
||||
page_frame: Option<u64>,
|
||||
}
|
||||
|
||||
/// How often a window that waits for another one looks whether that one has closed.
|
||||
const LOOK_EVERY: Duration = Duration::from_secs(2);
|
||||
|
||||
/// Whether another running CADCraft window has published the agent connection in `dir`: one this
|
||||
/// window must not replace, or closing it would leave that window unreachable.
|
||||
fn other_window_serves(dir: &Path) -> bool {
|
||||
use craft_control::agents::{PROBE_TIMEOUT, probe, read_connection};
|
||||
read_connection(dir).ok().flatten().is_some_and(|c| c.pid != std::process::id() && probe(c.port, PROBE_TIMEOUT))
|
||||
}
|
||||
|
||||
impl Default for Agents {
|
||||
/// No link: agents get no window (a Nightly build, the tests).
|
||||
fn default() -> Self {
|
||||
Agents {
|
||||
link: None,
|
||||
switch: None,
|
||||
requests: None,
|
||||
launch_flags: None,
|
||||
settings_dir: None,
|
||||
settings: AgentSettings::default(),
|
||||
default_folder: None,
|
||||
roots: AutomationRoots::none(),
|
||||
other_window: false,
|
||||
looked: None,
|
||||
look_every: LOOK_EVERY,
|
||||
app: format!("CADCraft {}", cadcraft_engine::build_version()),
|
||||
page_tainted: false,
|
||||
page_frame: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Agents {
|
||||
/// The link the app runs while `switch` lets agents in, with the agent settings saved in
|
||||
/// `settings_dir`.
|
||||
pub fn new(link: AgentLink, switch: AgentSwitch, settings_dir: Option<PathBuf>) -> Self {
|
||||
let settings = settings_dir.as_deref().map(agent_settings::load).unwrap_or_default();
|
||||
Agents {
|
||||
link: Some(link),
|
||||
switch: Some(switch),
|
||||
settings_dir,
|
||||
settings,
|
||||
default_folder: craft_control::agents::default_folder("CADCraft"),
|
||||
..Agents::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// `cadcraft --control <port>` serves the control channel for the whole run: no agent link.
|
||||
pub fn managed_by_launch(port: u16, switch: AgentSwitch, settings_dir: Option<PathBuf>) -> Self {
|
||||
let settings = settings_dir.as_deref().map(agent_settings::load).unwrap_or_default();
|
||||
Agents { switch: Some(switch), launch_flags: Some(port), settings_dir, settings, ..Agents::default() }
|
||||
}
|
||||
|
||||
/// [`LOOK_EVERY`] replaced by `every` (tests).
|
||||
#[doc(hidden)]
|
||||
pub fn look_every(mut self, every: Duration) -> Self {
|
||||
self.look_every = every;
|
||||
self
|
||||
}
|
||||
|
||||
/// The default agent folder replaced by `folder` (tests).
|
||||
#[doc(hidden)]
|
||||
pub fn with_default_folder(mut self, folder: Option<PathBuf>) -> Self {
|
||||
self.default_folder = folder;
|
||||
self
|
||||
}
|
||||
|
||||
/// Where the link stands, for the Agents page and `ui.inspect`.
|
||||
pub fn status(&self) -> AgentLinkStatus {
|
||||
let mut status = self.link.as_ref().map(|link| link.status().clone()).unwrap_or_default();
|
||||
if let Some(port) = self.launch_flags {
|
||||
status.launch_flags = true;
|
||||
status.port = Some(port);
|
||||
} else if self.other_window && status.port.is_none() {
|
||||
status.problem =
|
||||
Some(LinkProblem::App("Another CADCraft window takes the agents; this one takes over when that window closes.".to_string()));
|
||||
}
|
||||
status
|
||||
}
|
||||
|
||||
/// The suite's `AI-MCP` flag: the Agents page points to the launcher's switch.
|
||||
pub fn mcp_flag(&self) -> bool {
|
||||
self.switch.as_ref().is_some_and(AgentSwitch::mcp_flag)
|
||||
}
|
||||
|
||||
/// Whether the launcher's switch lets agents use CADCraft now.
|
||||
pub fn allowed(&self) -> bool {
|
||||
// CADCraft had no consent of its own before the switch.
|
||||
self.switch.as_ref().is_some_and(|switch| switch.allows(false))
|
||||
}
|
||||
|
||||
/// The agent settings of Options › AI Agents.
|
||||
pub fn settings(&self) -> &AgentSettings {
|
||||
&self.settings
|
||||
}
|
||||
|
||||
/// Options › AI Agents changed: save the settings for `cadcraft-cli mcp` too. The next
|
||||
/// [`Self::sync`] applies them (another port, other folders). No command reaches this, and
|
||||
/// while agent folders are in force (an agent request, or the frames that handle input an agent
|
||||
/// queued, `CadApp::agent_input_roots`) it refuses, so an agent can't widen its own folders by
|
||||
/// clicking and typing in the tab either.
|
||||
pub fn set_settings(&mut self, settings: AgentSettings) -> Result<(), String> {
|
||||
if self.page_tainted {
|
||||
return Err(
|
||||
"An AI agent used the AI Agents settings while they were open, so changes made there aren't saved; close Options, open it again and make the change yourself".to_string(),
|
||||
);
|
||||
}
|
||||
if cadcraft_engine::file_access::current().is_some() {
|
||||
return Err(
|
||||
"The AI Agents settings can't be saved while an AI agent's work is running in CADCraft; save them again once it has finished"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
let saved = match &self.settings_dir {
|
||||
Some(dir) => agent_settings::save(dir, &settings).map_err(|e| format!("couldn't save the agent settings: {e}")),
|
||||
None => Err("couldn't save the agent settings: CADCraft has no settings folder".to_string()),
|
||||
};
|
||||
self.settings = settings;
|
||||
saved
|
||||
}
|
||||
|
||||
/// The AI Agents tab is shown in `frame`. Shown in a pass with agent folders in force (an agent
|
||||
/// request or input), it stays tainted, refusing every save, until the person shows it afresh
|
||||
/// (after a frame it wasn't shown in) with no agent folders in force.
|
||||
pub(crate) fn page_shown(&mut self, frame: u64) {
|
||||
let afresh = self.page_frame.is_none_or(|last| frame > last.saturating_add(1));
|
||||
self.page_frame = Some(frame);
|
||||
if cadcraft_engine::file_access::current().is_some() {
|
||||
self.page_tainted = true;
|
||||
} else if afresh {
|
||||
self.page_tainted = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// What agent requests may read and write.
|
||||
pub fn roots(&self) -> Arc<AutomationRoots> {
|
||||
Arc::clone(&self.roots)
|
||||
}
|
||||
|
||||
/// `ui.inspect`'s `agents`: the link's status, the flag and the switch.
|
||||
pub fn inspect(&self) -> Value {
|
||||
let mut v = serde_json::to_value(self.status()).unwrap_or_default();
|
||||
v["mcpFlag"] = json!(self.mcp_flag());
|
||||
v["allowed"] = json!(self.allowed());
|
||||
v
|
||||
}
|
||||
|
||||
/// Once per frame: brings the link in line with the switch and Options › AI Agents (start, move,
|
||||
/// stop, or nothing while neither changed), rebuilds the folders agent requests are held to when
|
||||
/// that changed, then hands over the requests its server received as the app's own control
|
||||
/// requests. A request whose client already gave up is dropped.
|
||||
pub(crate) fn sync(&mut self, ctx: &egui::Context) -> Vec<ControlRequest> {
|
||||
let allowed = self.allowed();
|
||||
let Some(link) = self.link.as_mut() else { return Vec::new() };
|
||||
// Before this window starts serving agents: another window that already does keeps the
|
||||
// connection, and this one looks again now and then to take over once it has closed.
|
||||
if allowed && link.status().port.is_none() {
|
||||
let due = self.looked.is_none_or(|at| at.elapsed() >= self.look_every);
|
||||
if due {
|
||||
self.looked = Some(Instant::now());
|
||||
self.other_window = self.settings_dir.as_deref().is_some_and(other_window_serves);
|
||||
}
|
||||
if self.other_window {
|
||||
ctx.request_repaint_after(self.look_every);
|
||||
return Vec::new();
|
||||
}
|
||||
}
|
||||
let update = link.sync(allowed.then_some(&self.settings), &WindowHost::of(ctx));
|
||||
if update.changed {
|
||||
let folders = self.settings.folders_with(self.default_folder.as_deref());
|
||||
let (roots, problem) = agent_settings::roots(folders.read.as_deref(), folders.write.as_deref());
|
||||
self.roots = roots;
|
||||
if let Some(problem) = problem {
|
||||
log::warn!("agent folders: {problem}");
|
||||
link.note(LinkProblem::App(format!("Agents can't use a folder: {problem}")));
|
||||
}
|
||||
}
|
||||
// After the sync, so the frame that starts the server schedules its first check too.
|
||||
// While serving: two windows that started at the same moment may both serve, and the
|
||||
// connection names only one. If that one has closed (no file, or one nothing answers on),
|
||||
// this window publishes its own again, so agents still find an open window.
|
||||
if let (true, Some(port), Some(dir)) = (allowed, self.link.as_ref().and_then(|l| l.status().port), self.settings_dir.as_deref()) {
|
||||
if self.looked.is_none_or(|at| at.elapsed() >= self.look_every) {
|
||||
self.looked = Some(Instant::now());
|
||||
let ours = craft_control::agents::read_connection(dir).ok().flatten().is_some_and(|c| c.pid == std::process::id() && c.port == port);
|
||||
if !ours && !other_window_serves(dir) {
|
||||
let connection = craft_control::agents::Connection::new(port, dir.join(craft_control::agents::TOKEN_FILE), self.app.clone());
|
||||
if let Err(e) = craft_control::agents::write_connection(dir, &connection) {
|
||||
log::warn!("couldn't publish the agent connection again: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
// The next look runs even while nothing else draws a frame.
|
||||
let since = self.looked.map_or(Duration::ZERO, |at| at.elapsed());
|
||||
ctx.request_repaint_after(self.look_every.saturating_sub(since));
|
||||
}
|
||||
if update.stopped {
|
||||
self.requests = None;
|
||||
}
|
||||
if let Some(requests) = update.requests {
|
||||
self.requests = Some(requests);
|
||||
}
|
||||
let Some(requests) = &self.requests else { return Vec::new() };
|
||||
requests.try_iter().filter(|req| req.dispatch.start()).map(|req| ControlRequest::with_reply(req.method, req.params, req.reply)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use craft_automation::agents::{TOKEN_FILE, read_connection};
|
||||
use craft_automation::client::ControlClient;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
fn temp(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-agents-{name}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// The link follows the launcher's switch without a restart: on, it listens and publishes the
|
||||
/// connection, and a client's request reaches the app as one of its own control requests, its
|
||||
/// reply going back to that client; off, it stops and the connection file goes.
|
||||
#[test]
|
||||
fn the_link_follows_the_switch_and_hands_requests_to_the_app() {
|
||||
let dir = temp("switch");
|
||||
let ctx = egui::Context::default();
|
||||
let link = AgentLink::new(Some(dir.clone()), "CADCraft test");
|
||||
let mut agents = Agents::new(link, AgentSwitch::fixed(true, true), Some(dir.clone())).with_default_folder(Some(dir.join("agents")));
|
||||
assert!(agents.sync(&ctx).is_empty());
|
||||
let port = agents.status().port.expect("listening while the switch allows");
|
||||
assert!(read_connection(&dir).unwrap().is_some_and(|c| c.port == port));
|
||||
|
||||
let token = std::fs::read_to_string(dir.join(TOKEN_FILE)).unwrap().trim().to_string();
|
||||
let client = std::thread::spawn(move || {
|
||||
ControlClient::connect(([127, 0, 0, 1], port).into(), &token).map_err(|e| format!("{e:?}"))?.call("ping", json!({}))
|
||||
});
|
||||
let deadline = Instant::now() + Duration::from_secs(20);
|
||||
let req = loop {
|
||||
if let Some(req) = agents.sync(&ctx).pop() {
|
||||
break req;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "the request never reached the app");
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
assert_eq!(req.method, "ping");
|
||||
req.reply.send(json!({"ok": true, "result": "pong"})).unwrap();
|
||||
assert_eq!(client.join().unwrap(), Ok(json!("pong")));
|
||||
|
||||
agents.switch = Some(AgentSwitch::fixed(true, false));
|
||||
agents.sync(&ctx);
|
||||
assert_eq!(agents.status().port, None, "stopped when the switch turned off");
|
||||
assert!(read_connection(&dir).unwrap().is_none(), "and its connection file is gone");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// A second window with the same settings folder doesn't replace the first one's connection
|
||||
/// (closing it would leave the first unreachable); it takes over once the first has closed.
|
||||
#[test]
|
||||
fn a_second_window_waits_for_the_first_and_takes_over() {
|
||||
let dir = temp("two-windows");
|
||||
let ctx = egui::Context::default();
|
||||
let window = || {
|
||||
Agents::new(AgentLink::new(Some(dir.clone()), "CADCraft test"), AgentSwitch::fixed(true, true), Some(dir.clone()))
|
||||
.with_default_folder(Some(dir.join("agents")))
|
||||
.look_every(Duration::ZERO)
|
||||
};
|
||||
let mut first = window();
|
||||
first.sync(&ctx);
|
||||
let port = first.status().port.expect("the first window serves agents");
|
||||
// The second window runs in this process too: name another process in the first's file.
|
||||
let mut published = read_connection(&dir).unwrap().unwrap();
|
||||
published.pid = std::process::id().wrapping_add(1);
|
||||
craft_control::agents::write_connection(&dir, &published).unwrap();
|
||||
let mut second = window();
|
||||
second.sync(&ctx);
|
||||
assert_eq!(second.status().port, None, "the second waits");
|
||||
assert!(second.status().problem.is_some(), "and says why");
|
||||
assert_eq!(read_connection(&dir).unwrap().map(|c| c.port), Some(port), "the first's connection stays");
|
||||
drop(first);
|
||||
let _ = std::fs::remove_file(dir.join(craft_control::agents::CONNECTION_FILE));
|
||||
second.sync(&ctx);
|
||||
let taken = second.status().port.expect("the second takes over once the first has closed");
|
||||
assert_eq!(read_connection(&dir).unwrap().map(|c| c.port), Some(taken));
|
||||
drop(second);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// Two windows that started at the same moment both serve; when the one the connection names
|
||||
/// closes, the other publishes its own connection again.
|
||||
#[test]
|
||||
fn the_window_left_publishes_again_after_a_race() {
|
||||
let dir = temp("race");
|
||||
let ctx = egui::Context::default();
|
||||
let window = || {
|
||||
Agents::new(AgentLink::new(Some(dir.clone()), "CADCraft test"), AgentSwitch::fixed(true, true), Some(dir.clone()))
|
||||
.with_default_folder(Some(dir.join("agents")))
|
||||
.look_every(Duration::ZERO)
|
||||
};
|
||||
let (mut first, mut second) = (window(), window());
|
||||
first.sync(&ctx);
|
||||
let first_port = first.status().port.unwrap();
|
||||
// The race: the second checked before the first published, so it serves too and replaces the file.
|
||||
let _ = std::fs::remove_file(dir.join(craft_control::agents::CONNECTION_FILE));
|
||||
second.sync(&ctx);
|
||||
let second_port = second.status().port.unwrap();
|
||||
assert_eq!(read_connection(&dir).unwrap().map(|c| c.port), Some(second_port));
|
||||
drop(second);
|
||||
assert!(read_connection(&dir).unwrap().is_none(), "the closed window took its connection with it");
|
||||
first.sync(&ctx);
|
||||
assert_eq!(read_connection(&dir).unwrap().map(|c| c.port), Some(first_port), "the window left publishes again");
|
||||
drop(first);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// A serving window asks for a frame by its next look, so it publishes again after the other
|
||||
/// window closed even when nothing else in the app draws.
|
||||
#[test]
|
||||
fn a_serving_window_schedules_its_next_look() {
|
||||
let dir = temp("schedule");
|
||||
let ctx = egui::Context::default();
|
||||
let every = Duration::from_secs(30);
|
||||
let mut agents = Agents::new(AgentLink::new(Some(dir.clone()), "CADCraft test"), AgentSwitch::fixed(true, true), Some(dir.clone()))
|
||||
.with_default_folder(Some(dir.join("agents")))
|
||||
.look_every(every);
|
||||
// Idle frames first: a fresh context asks for a few of its own.
|
||||
let delay = |out: &mut egui::FullOutput| {
|
||||
out.textures_delta.clear();
|
||||
out.viewport_output.get(&egui::ViewportId::ROOT).map_or(Duration::MAX, |v| v.repaint_delay)
|
||||
};
|
||||
let mut idle = Duration::ZERO;
|
||||
for _ in 0..4 {
|
||||
idle = delay(&mut ctx.run_ui(egui::RawInput::default(), |_| {}));
|
||||
}
|
||||
assert_eq!(idle, Duration::MAX, "the warmed-up idle context asks for no frame");
|
||||
// The frame that starts the server schedules the first look, with no other frames run.
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
|
||||
agents.sync(ui.ctx());
|
||||
});
|
||||
assert!(agents.status().port.is_some());
|
||||
let first = delay(&mut out);
|
||||
assert!(first <= every, "the startup frame schedules the first look: {first:?}");
|
||||
// And each later idle frame the next one.
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
|
||||
agents.sync(ui.ctx());
|
||||
});
|
||||
let next = delay(&mut out);
|
||||
assert!(next <= every, "the next look is scheduled: {next:?}");
|
||||
drop(agents);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// The AI Agents tab an agent opened or drove saves nothing, also from a later pass with no
|
||||
/// agent folders in force (a field committing on focus loss), until the person shows it afresh.
|
||||
#[test]
|
||||
fn a_tab_an_agent_used_saves_nothing_until_shown_afresh() {
|
||||
let dir = temp("taint");
|
||||
let mut agents = Agents::new(AgentLink::new(Some(dir.clone()), "CADCraft test"), AgentSwitch::fixed(true, true), Some(dir.clone()));
|
||||
let mut wider = agents.settings().clone();
|
||||
wider.read_root = "/".into();
|
||||
agents.page_shown(1);
|
||||
let roots = AutomationRoots::none();
|
||||
cadcraft_engine::file_access::confine(Some(&roots), || agents.page_shown(2));
|
||||
agents.page_shown(3);
|
||||
assert!(agents.set_settings(wider.clone()).is_err(), "a later unconfined pass of the same showing");
|
||||
assert_ne!(agent_settings::load(&dir), wider);
|
||||
agents.page_shown(6);
|
||||
agents.set_settings(wider.clone()).unwrap();
|
||||
assert_eq!(agent_settings::load(&dir), wider, "shown afresh by the person");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// While agent folders are in force (an agent's request or input), the agent settings can't be
|
||||
/// changed, also not through the Options tab.
|
||||
#[test]
|
||||
fn agents_cannot_change_the_agent_settings() {
|
||||
let dir = temp("refuse");
|
||||
let mut agents = Agents::new(AgentLink::new(Some(dir.clone()), "CADCraft test"), AgentSwitch::fixed(true, true), Some(dir.clone()));
|
||||
let mut wider = agents.settings().clone();
|
||||
wider.write_root = "/".into();
|
||||
let roots = AutomationRoots::none();
|
||||
assert!(cadcraft_engine::file_access::confine(Some(&roots), || agents.set_settings(wider.clone())).is_err());
|
||||
assert_ne!(agents.settings(), &wider);
|
||||
assert_ne!(agent_settings::load(&dir), wider, "nothing saved");
|
||||
agents.set_settings(wider.clone()).unwrap();
|
||||
assert_eq!(agent_settings::load(&dir), wider, "the person can");
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// Without the suite's `AI-MCP` flag CADCraft takes no agents this way: it had no consent of
|
||||
/// its own before the launcher's switch.
|
||||
#[test]
|
||||
fn without_the_flag_nothing_listens() {
|
||||
let dir = temp("no-flag");
|
||||
let mut agents = Agents::new(AgentLink::new(Some(dir.clone()), "CADCraft test"), AgentSwitch::fixed(false, true), Some(dir.clone()));
|
||||
agents.sync(&egui::Context::default());
|
||||
assert_eq!(agents.status().port, None);
|
||||
assert!(read_connection(&dir).unwrap().is_none());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// Agent requests are held to the agent folders, and a new folder in Options › AI Agents applies
|
||||
/// while the link runs; what the dialog saves is what `cadcraft-cli mcp` reads.
|
||||
#[test]
|
||||
fn agent_requests_are_held_to_the_agent_folders() {
|
||||
use cadcraft_engine::file_access::{check_read, check_write, confine};
|
||||
let dir = temp("folders");
|
||||
let (inbox, other) = (dir.join("inbox"), dir.join("other"));
|
||||
std::fs::create_dir_all(&inbox).unwrap();
|
||||
std::fs::create_dir_all(&other).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
let link = AgentLink::new(Some(dir.clone()), "CADCraft test");
|
||||
let mut agents = Agents::new(link, AgentSwitch::fixed(true, true), Some(dir.clone())).with_default_folder(Some(inbox.clone()));
|
||||
agents.sync(&ctx);
|
||||
let roots = agents.roots();
|
||||
confine(Some(&roots), || {
|
||||
assert!(check_write(inbox.join("plan.dxf")).is_ok(), "the default agent folder");
|
||||
assert!(check_read(other.join("plan.dxf")).is_err(), "nothing outside it");
|
||||
});
|
||||
|
||||
let mut settings = agents.settings().clone();
|
||||
settings.write_root = other.display().to_string();
|
||||
agents.set_settings(settings.clone()).unwrap();
|
||||
agents.sync(&ctx);
|
||||
let roots = agents.roots();
|
||||
confine(Some(&roots), || assert!(check_write(other.join("plan.dxf")).is_ok(), "the new write folder applies at once"));
|
||||
assert_eq!(agent_settings::load(&dir), settings);
|
||||
drop(agents);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,12 @@ impl ControlRequest {
|
||||
(Self { method: method.into(), params, reply: tx, state: state.clone() }, PendingReply { rx, state })
|
||||
}
|
||||
|
||||
/// A request from another transport that waits for `reply` itself (the agent link's server,
|
||||
/// [`crate::agents`]), which has already claimed it to run.
|
||||
pub fn with_reply(method: impl Into<String>, params: Value, reply: Sender<ControlResponse>) -> Self {
|
||||
Self { method: method.into(), params, reply, state: Arc::new(AtomicU8::new(QUEUED)) }
|
||||
}
|
||||
|
||||
/// Mark the request as started. False when the transport already gave up on it
|
||||
/// ([`PendingReply::wait`] timed out): the app must then skip it, since the client was told it
|
||||
/// did not run and may send it again.
|
||||
@@ -291,10 +297,23 @@ pub fn inspect(app: &CadApp, ctx: &egui::Context) -> Value {
|
||||
"snap": app.canvas.snap.map(|s| json!({"point": [s.point.x, s.point.y], "mode": s.name})),
|
||||
"session": app.session.summary(),
|
||||
"closePrompt": app.close_prompt(),
|
||||
"agents": agents_json(app),
|
||||
"perf": {"frameMs": app.frame_ms, "buildMs": app.canvas.build_ms, "drawMs": app.canvas.draw_ms, "meshMs": app.canvas.mesh_ms, "building": app.canvas.building(), "renderer": if app.canvas.gpu.is_some() { "gpu" } else { "cpu" }, "prims": app.canvas.list.as_ref().map(|l| l.prims.len()), "truncated": app.canvas.list.as_ref().map(|l| l.truncated), "uiFrames": app.ui_frames, "passIndex": ctx.current_pass_index()},
|
||||
})
|
||||
}
|
||||
|
||||
/// The agent link's state for `ui.inspect` (`port`, `launchFlags`, `error`, `mcpFlag`, `allowed`).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn agents_json(app: &CadApp) -> Value {
|
||||
app.agents.inspect()
|
||||
}
|
||||
|
||||
/// The browser build takes no agents this way.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn agents_json(_: &CadApp) -> Value {
|
||||
Value::Null
|
||||
}
|
||||
|
||||
fn key_from(name: &str) -> Option<egui::Key> {
|
||||
egui::Key::from_name(name).or(match name.to_ascii_lowercase().as_str() {
|
||||
"enter" | "return" => Some(egui::Key::Enter),
|
||||
@@ -503,7 +522,14 @@ fn handle_request(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(egui::vec2(w as f32, h as f32)));
|
||||
ok(Value::Null)
|
||||
}
|
||||
"ui.screenshot" => Outcome::Screenshot { path: s("path").map(str::to_string) },
|
||||
"ui.screenshot" => {
|
||||
// Agents in the window write only in their folders (`file_access`; nothing is checked
|
||||
// for `--control`).
|
||||
if let Some(Err(e)) = s("path").map(cadcraft_engine::file_access::check_write) {
|
||||
return err(e);
|
||||
}
|
||||
Outcome::Screenshot { path: s("path").map(str::to_string) }
|
||||
}
|
||||
"ui.render" => {
|
||||
let w = f("width").unwrap_or(1600.0).clamp(16.0, 8192.0) as u32;
|
||||
let h = f("height").unwrap_or(1000.0).clamp(16.0, 8192.0) as u32;
|
||||
@@ -534,6 +560,9 @@ fn handle_request(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -
|
||||
};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(path) = s("path") {
|
||||
if let Err(e) = cadcraft_engine::file_access::check_write(path) {
|
||||
return err(e);
|
||||
}
|
||||
let file = std::path::Path::new(&path);
|
||||
let folder = cadcraft_engine::atomic_write::missing_folder(file);
|
||||
if let Err(e) = cadcraft_engine::atomic_write::write_atomic_making_folders(file, &png) {
|
||||
|
||||
@@ -37,14 +37,21 @@ pub struct UiFault {
|
||||
impl CadApp {
|
||||
/// [`CadApp::logic`] under the panic guard.
|
||||
pub fn guarded_logic(&mut self, ctx: &egui::Context) {
|
||||
self.guarded(ctx, |app| app.logic(ctx));
|
||||
let roots = self.agent_input_roots.clone();
|
||||
cadcraft_engine::file_access::confine(roots.as_ref(), || self.guarded(ctx, |app| app.logic(ctx)));
|
||||
}
|
||||
|
||||
/// [`CadApp::ui`] under the panic guard, then the notice about any panic. Once the interface
|
||||
/// has been given up on, only the window that closes the app is drawn.
|
||||
pub fn guarded_ui(&mut self, ui: &mut egui::Ui) {
|
||||
let ctx = ui.ctx().clone();
|
||||
self.guarded(&ctx, |app| app.ui(ui));
|
||||
let roots = self.agent_input_roots.clone();
|
||||
cadcraft_engine::file_access::confine(roots.as_ref(), || self.guarded(&ctx, |app| app.ui(ui)));
|
||||
// The input an agent queued has been handled and its LISP routine has ended: what the
|
||||
// person does next is theirs.
|
||||
if self.synthetic.is_empty() && !self.synthetic_injected && !self.session.lisp_running() {
|
||||
self.agent_input_roots = None;
|
||||
}
|
||||
self.show_fault(&ctx);
|
||||
}
|
||||
|
||||
|
||||
+167
-13
@@ -17,6 +17,8 @@ pub const UPDATE_APP: craft_update::app::App = craft_update::app::App {
|
||||
..craft_update::suite::CADCRAFT
|
||||
};
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub mod agents;
|
||||
pub mod aliasdlg;
|
||||
pub mod animation;
|
||||
pub mod attedit;
|
||||
@@ -333,6 +335,9 @@ pub struct CadApp {
|
||||
/// Both frames of Use system title bar, where it applies ([`title_bar::TitleBar`]).
|
||||
title_bar: Option<title_bar::TitleBar>,
|
||||
control_rx: Option<Receiver<ControlRequest>>,
|
||||
/// Agents in the open window through the ArtCraft Launcher's switch ([`agents`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub agents: agents::Agents,
|
||||
/// Fresh surface and identity snapshot (see [`capture`]).
|
||||
pub(crate) capture_geometry: Option<capture::CaptureGeometry>,
|
||||
/// Monotonic surface epoch, bumped whenever the window/viewport geometry changes.
|
||||
@@ -361,7 +366,11 @@ pub struct CadApp {
|
||||
/// The framework dialogs CADCraft keeps open (the update dialogs), run after its own UI.
|
||||
pub framework_dialogs: craft_ui::dialog::DialogHost,
|
||||
/// One synthetic batch has been put into `RawInput` and is waiting for a real `App::ui` call.
|
||||
synthetic_injected: bool,
|
||||
pub(crate) synthetic_injected: bool,
|
||||
/// The agent folders in force while input an agent queued (`ui.click`, `ui.key`, `ui.text`…)
|
||||
/// waits for the frames that handle it, or a LISP routine it started runs on in later slices,
|
||||
/// so what they do is held to them as the request itself was ([`CadApp::guarded_ui`]).
|
||||
pub(crate) agent_input_roots: Option<std::sync::Arc<cadcraft_engine::file_access::AutomationRoots>>,
|
||||
/// Counts settled UI passes (one per painted frame; never hidden logic-only ticks or
|
||||
/// discarded passes).
|
||||
pub ui_frames: u64,
|
||||
@@ -450,6 +459,8 @@ impl CadApp {
|
||||
integrated_titlebar: false,
|
||||
title_bar: None,
|
||||
control_rx: None,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
agents: agents::Agents::default(),
|
||||
capture_geometry: None,
|
||||
capture_epoch: 0,
|
||||
capture_identity_epoch: 0,
|
||||
@@ -464,6 +475,7 @@ impl CadApp {
|
||||
framework_host: framework::host(),
|
||||
framework_dialogs: craft_ui::dialog::DialogHost::default(),
|
||||
synthetic_injected: false,
|
||||
agent_input_roots: None,
|
||||
ui_frames: 0,
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
frame_cap: None,
|
||||
@@ -1114,7 +1126,13 @@ impl CadApp {
|
||||
}
|
||||
// A long AutoLISP routine runs one bounded slice per frame, including hidden web/native
|
||||
// ticks; it must not depend on a paint or `RequestPaintWhileHidden`.
|
||||
self.session.lisp_tick();
|
||||
// An agent's routine keeps its folders from its first slice on, also when the request that
|
||||
// started it ran earlier in this same call (`drain_control`), after the frame's roots were
|
||||
// taken (`guarded_logic`). A routine without agent roots runs as before.
|
||||
match self.agent_input_roots.clone() {
|
||||
Some(roots) => cadcraft_engine::file_access::confine(Some(&roots), || self.session.lisp_tick()),
|
||||
None => self.session.lisp_tick(),
|
||||
}
|
||||
// Time-based and idempotent by its own deadline; keeps autosave alive while hidden.
|
||||
self.autosave_tick(ctx);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -1344,26 +1362,59 @@ impl CadApp {
|
||||
|
||||
/// Drain each queued control request at most once (timed-out requests are skipped), dispatch it to `control::handle` or `capture::admit`, note the resulting capture identity and request a repaint.
|
||||
fn drain_control(&mut self, ctx: &egui::Context) {
|
||||
self.drain_agents(ctx);
|
||||
let Some(rx) = self.control_rx.take() else { return };
|
||||
while let Ok(req) = rx.try_recv() {
|
||||
// Timed out while queued: the client was told it did not run (#345).
|
||||
if !req.begin() {
|
||||
continue;
|
||||
}
|
||||
let reply = req.reply.clone();
|
||||
match control::handle(self, ctx, &req) {
|
||||
control::Outcome::Done(v) => {
|
||||
let _ = reply.send(v);
|
||||
}
|
||||
control::Outcome::Screenshot { path } => capture::admit(self, ctx, path, reply),
|
||||
}
|
||||
// A command can switch drawings or move the focus; a screenshot queued before it must
|
||||
// see that transition even if a later command returns to the same drawing.
|
||||
capture::note_identity(self, ctx);
|
||||
ctx.request_repaint();
|
||||
self.answer_control(ctx, &req, None);
|
||||
}
|
||||
self.control_rx = Some(rx);
|
||||
}
|
||||
|
||||
/// The agent link's requests, each held to the agent folders ([`agents::Agents::roots`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn drain_agents(&mut self, ctx: &egui::Context) {
|
||||
let requests = self.agents.sync(ctx);
|
||||
if requests.is_empty() {
|
||||
return;
|
||||
}
|
||||
let roots = self.agents.roots();
|
||||
for req in requests {
|
||||
self.answer_control(ctx, &req, Some(&roots));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn drain_agents(&mut self, _: &egui::Context) {}
|
||||
|
||||
/// Run one control request, with `roots` in force while it runs, and send its reply (a
|
||||
/// screenshot's once captured).
|
||||
fn answer_control(
|
||||
&mut self,
|
||||
ctx: &egui::Context,
|
||||
req: &ControlRequest,
|
||||
roots: Option<&std::sync::Arc<cadcraft_engine::file_access::AutomationRoots>>,
|
||||
) {
|
||||
let reply = req.reply.clone();
|
||||
match cadcraft_engine::file_access::confine(roots, || control::handle(self, ctx, req)) {
|
||||
control::Outcome::Done(v) => {
|
||||
let _ = reply.send(v);
|
||||
}
|
||||
control::Outcome::Screenshot { path } => capture::admit(self, ctx, path, reply),
|
||||
}
|
||||
// Input the agent queued, or a LISP routine it started that goes on in later frames' slices,
|
||||
// stays held to its folders.
|
||||
if roots.is_some() && (!self.synthetic.is_empty() || self.session.lisp_running()) {
|
||||
self.agent_input_roots = roots.cloned();
|
||||
}
|
||||
// A command can switch drawings or move the focus; a screenshot queued before it must
|
||||
// see that transition even if a later command returns to the same drawing.
|
||||
capture::note_identity(self, ctx);
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask for a painted frame while no frame is being painted. Native eframe honours the viewport
|
||||
@@ -1623,6 +1674,109 @@ mod tests {
|
||||
assert!(third.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::B, .. })));
|
||||
}
|
||||
|
||||
/// Input an agent queues in the window (`ui.text`, `ui.key`, `ui.click`) is handled frames later,
|
||||
/// so the agent folders stay in force until that input has gone through a UI pass; input from
|
||||
/// `--control` (no roots) leaves nothing in force.
|
||||
#[test]
|
||||
fn agent_input_keeps_the_agent_folders_until_it_is_handled() {
|
||||
let mut a = app();
|
||||
let ctx = egui::Context::default();
|
||||
crate::framework::install_headless(&ctx);
|
||||
let (req, _reply) = control::ControlRequest::new("ui.text", json!({"text": "x"}));
|
||||
a.answer_control(&ctx, &req, None);
|
||||
assert!(a.agent_input_roots.is_none(), "--control input is not confined");
|
||||
a.synthetic.clear();
|
||||
let roots = cadcraft_engine::file_access::AutomationRoots::none();
|
||||
let (req, _reply) = control::ControlRequest::new("ui.text", json!({"text": "x"}));
|
||||
a.answer_control(&ctx, &req, Some(&roots));
|
||||
assert!(a.agent_input_roots.is_some(), "in force while the text waits");
|
||||
let mut raw = egui::RawInput::default();
|
||||
a.raw_input_hook(&ctx, &mut raw);
|
||||
let mut out = ctx.run_ui(raw, |ui| {
|
||||
a.guarded_logic(ui.ctx());
|
||||
a.guarded_ui(ui);
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
assert!(a.agent_input_roots.is_none(), "the text went through a UI pass");
|
||||
|
||||
// A `--control` request in a frame that holds an agent's roots is not held to them.
|
||||
let outside = std::env::temp_dir().join(format!("cadcraft-control-unconfined-{}.png", std::process::id()));
|
||||
let (req, reply) = control::ControlRequest::new("ui.render", json!({"path": outside.to_string_lossy()}));
|
||||
a.session.new_drawing(false);
|
||||
cadcraft_engine::file_access::confine(Some(&roots), || a.answer_control(&ctx, &req, None));
|
||||
assert_eq!(reply.wait(std::time::Duration::from_secs(5))["ok"], true);
|
||||
assert!(outside.is_file());
|
||||
let _ = std::fs::remove_file(outside);
|
||||
}
|
||||
|
||||
/// A routine an agent starts through the agent link, in a frame whose `logic` began with no
|
||||
/// agent folders in force, writes nothing outside them in any later slice, the first one of the
|
||||
/// same `logic` call included.
|
||||
#[test]
|
||||
fn an_agents_routine_is_confined_from_the_same_frame_on() {
|
||||
use craft_automation::agents::{AgentLink, AgentSwitch, TOKEN_FILE};
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-lisp-same-frame-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let folder = dir.join("agents");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let outside = dir.join("outside.txt");
|
||||
let mut a = app();
|
||||
a.session.new_drawing(false);
|
||||
let link = AgentLink::new(Some(dir.clone()), "CADCraft test");
|
||||
a.agents = agents::Agents::new(link, AgentSwitch::fixed(true, true), Some(dir.clone())).with_default_folder(Some(folder));
|
||||
let ctx = egui::Context::default();
|
||||
a.logic(&ctx);
|
||||
let port = a.agents.status().port.unwrap();
|
||||
let token = std::fs::read_to_string(dir.join(TOKEN_FILE)).unwrap().trim().to_string();
|
||||
let path = outside.to_string_lossy().replace('\\', "/");
|
||||
let text = format!("(progn (repeat 300000 (setq x 1)) (setq f (open \"{path}\" \"w\")) (if f (close f)) (prompt \"agent-routine-done\"))");
|
||||
let agent = std::thread::spawn(move || {
|
||||
craft_automation::client::ControlClient::connect(([127, 0, 0, 1], port).into(), &token)
|
||||
.map_err(|e| format!("{e:?}"))?
|
||||
.call("cmdline.input", json!({"text": text}))
|
||||
});
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
|
||||
while !agent.is_finished() || a.session.lisp_running() {
|
||||
assert!(std::time::Instant::now() < deadline, "the routine never ended");
|
||||
// `logic` alone, as `guarded_logic` with no roots taken: only the stored agent roots confine.
|
||||
a.logic(&ctx);
|
||||
std::thread::sleep(std::time::Duration::from_millis(2));
|
||||
}
|
||||
let reply = agent.join().expect("the agent thread");
|
||||
assert!(reply.is_ok(), "the window took the request: {reply:?}");
|
||||
assert!(a.session.log.iter().any(|l| l.contains("agent-routine-done")), "the routine ran past its file attempt: {:?}", a.session.log);
|
||||
assert!(!outside.exists(), "the routine wrote outside the agent folders");
|
||||
drop(a);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
/// A LISP routine an agent starts that runs past its first slice goes on in later frames, still
|
||||
/// held to the agent folders until it ends.
|
||||
#[test]
|
||||
fn an_agents_long_lisp_routine_keeps_the_agent_folders() {
|
||||
let mut a = app();
|
||||
let ctx = egui::Context::default();
|
||||
crate::framework::install_headless(&ctx);
|
||||
a.session.new_drawing(false);
|
||||
let roots = cadcraft_engine::file_access::AutomationRoots::none();
|
||||
let (req, _reply) = control::ControlRequest::new("cmdline.input", json!({"text": "(repeat 300000 (setq x 1))"}));
|
||||
a.answer_control(&ctx, &req, Some(&roots));
|
||||
assert!(a.session.lisp_running(), "the routine outlives the request");
|
||||
assert!(a.agent_input_roots.is_some(), "and keeps the agent folders");
|
||||
for _ in 0..2000 {
|
||||
if !a.session.lisp_running() {
|
||||
break;
|
||||
}
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
|
||||
a.guarded_logic(ui.ctx());
|
||||
a.guarded_ui(ui);
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
}
|
||||
assert!(!a.session.lisp_running(), "the routine ended");
|
||||
assert!(a.agent_input_roots.is_none(), "then the folders are no longer in force");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn theme_choice_persists_and_drives_tokens() {
|
||||
let mut a = app();
|
||||
|
||||
@@ -12,13 +12,14 @@ use crate::animation::AnimationPref;
|
||||
use crate::theme::{ThemePref, Tokens};
|
||||
|
||||
/// The tabs: (id in the dialog name, label).
|
||||
pub(super) const TABS: [(&str, &str); 6] = [
|
||||
pub(super) const TABS: [(&str, &str); 7] = [
|
||||
("display", "Display"),
|
||||
("files", "Open and Save"),
|
||||
("drafting", "Drafting"),
|
||||
("selection", "Selection"),
|
||||
("preferences", "User Preferences"),
|
||||
("profiles", "Profiles"),
|
||||
("agents", "AI Agents"),
|
||||
];
|
||||
|
||||
const WIDTH: f32 = 580.0;
|
||||
@@ -57,6 +58,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, name: &str, open: &mut bool
|
||||
"selection" => selection(app, ui, &mut changes),
|
||||
"preferences" => preferences(app, ui, &mut changes),
|
||||
"profiles" => profiles(app, ui, &mut changes),
|
||||
"agents" => agents(app, ui),
|
||||
_ => display(app, ui, &mut changes),
|
||||
}
|
||||
// The same height on every tab, so switching tabs doesn't move the buttons.
|
||||
@@ -85,6 +87,54 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, name: &str, open: &mut bool
|
||||
}
|
||||
}
|
||||
|
||||
/// AI Agents tab: the shared Agents page (`craft_automation::ui::agents`) over the agent settings.
|
||||
/// Unlike the other tabs it doesn't go through OPTIONS: no command may change these settings, or an
|
||||
/// agent in the window could widen its own folders. They are saved at once for `cadcraft-cli mcp`
|
||||
/// too ([`crate::agents::Agents::set_settings`]).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn agents(app: &mut CadApp, ui: &mut egui::Ui) {
|
||||
use craft_ui::patterns::preferences::SettingsDraft;
|
||||
if !app.agents.mcp_flag() {
|
||||
// CADCraft had no agent consent of its own before the launcher's switch, so without the
|
||||
// flag there is nothing to set here.
|
||||
hint(
|
||||
ui,
|
||||
crate::tl!(
|
||||
"AI apps reach the open CADCraft window once ArtCraft Launcher › Settings › AI agents is available on this computer. Until then they work with CADCraft without a window."
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
app.agents.page_shown(ui.ctx().cumulative_frame_nr());
|
||||
let mut draft = SettingsDraft::default();
|
||||
if let Err(e) = draft.replace(&json!({ AGENTS_PAGE: app.agents.settings() })) {
|
||||
hint(ui, &e.to_string());
|
||||
return;
|
||||
}
|
||||
let status = app.agents.status();
|
||||
let out = craft_automation::ui::agents::AgentsPage::new(AGENTS_PAGE, &mut draft, &status).mcp_flag(true).show(ui);
|
||||
if !out.changed {
|
||||
return;
|
||||
}
|
||||
let settings = draft.to::<Value>().and_then(|v| serde_json::from_value(v[AGENTS_PAGE].clone()).ok());
|
||||
if let Some(settings) = settings
|
||||
&& let Err(e) = app.agents.set_settings(settings)
|
||||
{
|
||||
log::warn!("{e}");
|
||||
app.session.echo(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// The browser build has no connection for agents.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn agents(_: &mut CadApp, ui: &mut egui::Ui) {
|
||||
hint(ui, crate::tl!("AI apps work with the desktop app; the web version has no connection for them."));
|
||||
}
|
||||
|
||||
/// The section of the Agents page's draft that holds the agent settings.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
const AGENTS_PAGE: &str = "agents";
|
||||
|
||||
fn grid(ui: &mut egui::Ui, id: &str, add: impl FnOnce(&mut egui::Ui)) {
|
||||
egui::Grid::new(id).num_columns(2).spacing(vec2(14.0, 8.0)).show(ui, add);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
//! Agents in the open window: a request through the agent link runs in the app, held to the agent
|
||||
//! folders of Options › AI Agents.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use cadcraft_engine::Session;
|
||||
use cadcraft_ui_egui::agents::Agents;
|
||||
use cadcraft_ui_egui::{CadApp, Services};
|
||||
use craft_automation::agents::{AgentLink, AgentSwitch, TOKEN_FILE};
|
||||
use craft_automation::client::ControlClient;
|
||||
use serde_json::json;
|
||||
|
||||
/// A file an agent asks the window to write outside its folders is refused, one inside them is
|
||||
/// written: the agent link's requests run inside the agent folders, as headless ones do.
|
||||
#[test]
|
||||
fn a_window_request_is_held_to_the_agent_folders() {
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-agents-window-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let folder = dir.join("agents");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let mut app = CadApp::new(Session::new(), Services::default());
|
||||
let link = AgentLink::new(Some(dir.clone()), "CADCraft test");
|
||||
app.agents = Agents::new(link, AgentSwitch::fixed(true, true), Some(dir.clone())).with_default_folder(Some(folder.clone()));
|
||||
let ctx = egui::Context::default();
|
||||
app.logic(&ctx);
|
||||
let port = app.agents.status().port.expect("the window takes agents while the switch allows");
|
||||
let token = std::fs::read_to_string(dir.join(TOKEN_FILE)).unwrap().trim().to_string();
|
||||
|
||||
let (outside, inside): (PathBuf, PathBuf) = (dir.join("outside.png"), folder.join("inside.png"));
|
||||
let paths = (outside.to_string_lossy().into_owned(), inside.to_string_lossy().into_owned());
|
||||
let agent = std::thread::spawn(move || {
|
||||
let mut client = ControlClient::connect(([127, 0, 0, 1], port).into(), &token).map_err(|e| format!("{e:?}"))?;
|
||||
Ok::<_, String>((client.call("ui.render", json!({"path": paths.0})), client.call("ui.render", json!({"path": paths.1}))))
|
||||
});
|
||||
let deadline = Instant::now() + Duration::from_secs(30);
|
||||
while !agent.is_finished() {
|
||||
assert!(Instant::now() < deadline, "the window never answered");
|
||||
app.logic(&ctx);
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
let (refused, written) = agent.join().unwrap().unwrap();
|
||||
let refused = refused.unwrap_err();
|
||||
assert!(refused.contains("outside the write root"), "{refused}");
|
||||
assert!(!outside.exists());
|
||||
written.unwrap();
|
||||
assert!(inside.is_file());
|
||||
drop(app);
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
@@ -71,3 +71,29 @@ fn unknown_method_points_to_control_methods() {
|
||||
let e = r["error"].as_str().unwrap_or_default();
|
||||
assert!(e.starts_with("unknown method `help`") && e.contains("control.methods"), "{e}");
|
||||
}
|
||||
|
||||
/// An agent in the window (its requests run inside the agent folders) can't have `ui.render` or
|
||||
/// `ui.screenshot` write a file outside them; inside them `ui.render` writes, and without roots
|
||||
/// (`--control`) nothing is checked.
|
||||
#[test]
|
||||
fn files_written_for_agents_stay_in_their_folders() {
|
||||
use cadcraft_engine::file_access::{AutomationRoots, confine};
|
||||
let dir = std::env::temp_dir().join(format!("cadcraft-control-roots-{}", std::process::id()));
|
||||
let folder = dir.join("agents");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
let roots = AutomationRoots::new(None, Some(&folder)).unwrap();
|
||||
let mut app = app();
|
||||
let outside = dir.join("outside.png").to_string_lossy().into_owned();
|
||||
let inside = folder.join("inside.png").to_string_lossy().into_owned();
|
||||
confine(roots.as_ref(), || {
|
||||
for method in ["ui.render", "ui.screenshot"] {
|
||||
let v = call(&mut app, method, json!({"path": outside}));
|
||||
assert_eq!(v["ok"], false, "{method}: {v}");
|
||||
assert!(v["error"].as_str().unwrap_or_default().contains("outside the write root"), "{method}: {v}");
|
||||
}
|
||||
assert_eq!(call(&mut app, "ui.render", json!({"path": inside}))["ok"], true);
|
||||
});
|
||||
assert_eq!(call(&mut app, "ui.render", json!({"path": outside}))["ok"], true);
|
||||
assert!(std::path::Path::new(&outside).is_file() && std::path::Path::new(&inside).is_file());
|
||||
let _ = std::fs::remove_dir_all(dir);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
mod agents_window;
|
||||
mod animation_effects;
|
||||
mod attedit_dialog;
|
||||
mod block_description_palette;
|
||||
|
||||
@@ -313,3 +313,24 @@ fn reset_brings_back_hidden_menu_bar_toolbar_and_status_bar() {
|
||||
assert_eq!(a.ui.show_command_line, d.show_command_line);
|
||||
assert_eq!(a.ui.show_palettes, d.show_palettes);
|
||||
}
|
||||
|
||||
/// With the suite's `AI-MCP` flag the AI Agents tab is the shared Agents page (folders and the
|
||||
/// closed-app choice, no switch of its own); without it, one line pointing to the launcher.
|
||||
#[test]
|
||||
fn the_ai_agents_tab_shows_the_launchers_switch() {
|
||||
use cadcraft_ui_egui::agents::Agents;
|
||||
use craft_automation::agents::{AgentLink, AgentSwitch};
|
||||
let ctx = egui::Context::default();
|
||||
cadcraft_ui_egui::framework::install_headless(&ctx);
|
||||
let mut a = app();
|
||||
a.ui.dialog = Some("options:agents".into());
|
||||
a.agents = Agents::new(AgentLink::new(None, "CADCraft test"), AgentSwitch::fixed(false, true), None);
|
||||
let text = render(&mut a, &ctx);
|
||||
assert!(text.contains("ArtCraft Launcher") && !text.contains("Folder agents can save to"), "{text}");
|
||||
a.agents = Agents::new(AgentLink::new(None, "CADCraft test"), AgentSwitch::fixed(true, false), None);
|
||||
let text = render(&mut a, &ctx);
|
||||
for shown in ["Control Port", "Folder agents can open from", "Folder agents can save to", "is closed"] {
|
||||
assert!(text.contains(shown), "{shown}: {text}");
|
||||
}
|
||||
assert!(!text.contains("Allow Agent Control"), "the launcher's switch decides: {text}");
|
||||
}
|
||||
@@ -114,6 +114,26 @@ The existing response is unchanged: `count` is all matches, `returned` is the pa
|
||||
`entities` contains handles, layers and geometry. This query does not change selection, drawing
|
||||
contents or undo history. `entities` is a command, not a top-level protocol method.
|
||||
|
||||
## The agent server
|
||||
|
||||
While the ArtCraft Launcher's switch lets agents use CADCraft, the app runs a second server for them
|
||||
on `127.0.0.1` (Options › AI Agents › Control Port; 0 is any free port) and publishes it in
|
||||
`agent-connection.json` in the settings folder: `{"version", "pid", "port", "tokenFile", "app"}`.
|
||||
The token is in `agent-control.token` beside it, kept across launches. This server is the shared one
|
||||
of the Craft apps (`craft_automation::server`), so it differs from `--control`:
|
||||
|
||||
- A connection signs in first, within 10 s: `{"id": 0, "method": "auth.challenge", "params":
|
||||
{"clientNonce": "<hex>"}}` answers with `serverNonce` and `serverProof`, the app's proof that it
|
||||
holds the token; the client checks it and sends `{"id": 0, "method": "auth", "params": {"proof":
|
||||
"<hex>"}}`. Requests after that carry no `token`.
|
||||
- A request line is at most 1 MiB; a timeout reply says in its `error` whether the request can still
|
||||
have run (`timeout: not run` is safe to send again).
|
||||
- Every request runs inside the agent folders (`docs/mcp.md`): `app.open`, `app.save`, commands that
|
||||
read or write files, and the `path` of `ui.render` and `ui.screenshot` are refused outside them.
|
||||
|
||||
The methods and replies are the same as below. `ui.inspect` reports the agent link under `agents`:
|
||||
`port`, `launchFlags` (`--control` manages the connection), `error`, `mcpFlag` and `allowed`.
|
||||
|
||||
## Extended data (xdata)
|
||||
|
||||
Other applications' extended data travels with an entity (it is read from the file, kept on
|
||||
|
||||
+56
-20
@@ -4,33 +4,67 @@ CADCraft speaks the [Model Context Protocol](https://modelcontextprotocol.io) ov
|
||||
|
||||
## Start it
|
||||
|
||||
The ArtCraft Launcher adds CADCraft to your AI apps: turn on **ArtCraft Launcher › Settings › AI
|
||||
agents**. It writes the MCP client entries itself (one `ArtCraft` entry in Claude Desktop, Claude
|
||||
Code, Cursor and LM Studio); CADCraft writes no client configuration of its own.
|
||||
|
||||
```sh
|
||||
# Headless: an in-process drawing session, no window.
|
||||
# What the launcher's entry runs: the open CADCraft window while the launcher lets agents use it,
|
||||
# otherwise a headless drawing session.
|
||||
cadcraft-cli mcp
|
||||
|
||||
# Bridged to the running app (watch the agent draw):
|
||||
cadcraft --control 7979 &
|
||||
cadcraft-cli mcp --connect 127.0.0.1:7979
|
||||
# Never the window: an in-process drawing session.
|
||||
cadcraft-cli mcp --headless
|
||||
```
|
||||
|
||||
An MCP client usually starts its servers when it starts, often before the app is open. With
|
||||
`--lazy` the bridge starts anyway and reaches the app at the first tool call; until the app answers,
|
||||
each call fails with a message saying how to open it. `--launch` also opens CADCraft (macOS) with
|
||||
that control port at a call that finds nothing, and waits for it:
|
||||
### Agents in the open window
|
||||
|
||||
```json
|
||||
{ "mcpServers": { "cadcraft": { "command": "cadcraft-cli", "args": ["mcp", "--connect", "127.0.0.1:7979", "--launch"] } } }
|
||||
```
|
||||
While the launcher's switch names CADCraft (the suite's `AI-MCP` flag is on), the open app serves its
|
||||
control channel on `127.0.0.1` for agents and publishes where in `agent-connection.json` in its
|
||||
settings folder (`CADCRAFT_CONFIG_DIR`, a portable copy's `CADCraftData`, else `%APPDATA%\CADCraft`,
|
||||
`~/Library/Application Support/CADCraft` or `~/.config/cadcraft`), with its token in
|
||||
`agent-control.token` beside it (owner-only). When the switch turns off the server stops and the file
|
||||
goes, without a restart.
|
||||
|
||||
`--connect` needs the app's `HOST:PORT`. Without one (or with an unknown argument) `cadcraft-cli mcp`
|
||||
exits with an error instead of falling back to a headless session, so a client meant for the app
|
||||
never edits a separate drawing by mistake. If the app can't be reached, startup fails too.
|
||||
Plain `cadcraft-cli mcp` reads that file before every tool call, so the MCP client's configuration
|
||||
holds no port and no token, and CADCraft may open, quit or change port while the client stays
|
||||
connected:
|
||||
|
||||
Example client configuration (Claude Code / Claude Desktop):
|
||||
- **CADCraft open:** the call goes to its window. The client signs in with a challenge handshake:
|
||||
CADCraft first proves it holds the token, and the token itself never crosses the wire, so a
|
||||
program that took the port of a CADCraft that quit gets nothing.
|
||||
- **CADCraft closed, agents allowed:** Options › AI Agents › When CADCraft is closed decides, or
|
||||
`--when-closed launch|headless|error`: open CADCraft and wait for it (up to 45 s), work without a
|
||||
window, or an error saying to open it. A session that went headless stays headless, so the drawing
|
||||
doesn't move under the agent.
|
||||
- **Agents not allowed** (switch off, or no `AI-MCP` flag): a headless session, as `mcp` always was.
|
||||
|
||||
```json
|
||||
{ "mcpServers": { "cadcraft": { "command": "cadcraft-cli", "args": ["mcp"] } } }
|
||||
```
|
||||
Agent requests in the window are held to the folders of **Options › AI Agents**: files are opened
|
||||
only from the read folder (or the write folder) and saved only in the write folder, with the same
|
||||
checks as the headless roots below. An empty folder setting is the default agent folder,
|
||||
`Documents/ArtCraft/Agents/CADCraft` (made when first used). A folder that can't be used grants no
|
||||
access through it (with neither usable, every file is refused, never none); a usable write folder
|
||||
still allows reads inside it. What an agent's queued input (`ui.click`, `ui.key`, `ui.text`) or a
|
||||
LISP routine it started does in later frames is held to the same folders. A headless session made because CADCraft is closed uses the
|
||||
same folders unless `--automation-read-root` / `--automation-write-root` name others. The
|
||||
`agent_folders` tool tells the agent which folders it has (`read_folder`, `write_folder`) and whether
|
||||
files outside them are refused (`confined`).
|
||||
|
||||
Only you change these settings, in the Options dialog: the `options` command has no such keys, and
|
||||
the tab refuses changes while an agent's request or input is being handled, so an agent can't widen
|
||||
its own folders. The tab also shows whether agents can connect and on which port. With several CADCraft windows on
|
||||
the same settings folder, the first one takes the agents; another takes over when it closes.
|
||||
`cadcraft --control PORT` keeps its own server for the whole run; the tab then says the launch
|
||||
options manage the connection. A Nightly build takes no agents this way.
|
||||
|
||||
### `--connect` (deprecated)
|
||||
|
||||
`cadcraft-cli mcp --connect HOST:PORT` still bridges to an app started with `--control PORT` for
|
||||
one more release, and prints a deprecation line on stderr; plain `mcp` replaces it. `--lazy` reaches
|
||||
the app at the first tool call instead of at startup, and `--launch` also opens CADCraft (macOS)
|
||||
with that control port at a call that finds nothing. Without an address `cadcraft-cli mcp --connect`
|
||||
exits with an error instead of falling back to a headless session. The `--control` server is held
|
||||
to no folders (#1585).
|
||||
|
||||
## Confining file access
|
||||
|
||||
@@ -96,8 +130,9 @@ configuration works across the suite) keep the agent to the folders you give it:
|
||||
given once (`--flag <dir>` or `--flag=<dir>`).
|
||||
|
||||
The flags confine the headless server. `--connect` with them is an error, since the server would
|
||||
otherwise talk to an app that isn't confined; the app's control channel does not take them yet
|
||||
(#1585). Without `--connect` the server writes the files itself, so every check happens here.
|
||||
otherwise talk to an app that isn't confined; the app's `--control` channel does not take them yet
|
||||
(#1585). The open window holds agents to its own folders instead (Options › AI Agents, above).
|
||||
Headless, the server writes the files itself, so every check happens here.
|
||||
|
||||
A path is checked, then opened: another program on the computer that swaps in a link between the two
|
||||
can still win that race, and a hard link can't be told from a file. Use the operating system's
|
||||
@@ -121,6 +156,7 @@ sandbox as well if other programs can change these folders.
|
||||
| `render {width?, height?, fit?, window?, background?, plot_style?}` | A PNG image of the drawing, or of just the area `window` `[[x0,y0],[x1,y1]]` (one sheet or room of a large drawing; 1600 px wide with the window's shape unless sized). `background`: `"dark"` (the canvas; the default without a plot style), `"white"` (the default with one, as a plot prints on paper), `"paper"` or `"#rrggbb"`; colour 7 is drawn white on a dark background and black on a light one, as on a plot. `plot_style`: a plot style table, e.g. `monochrome.ctb` (every colour black) or `grayscale.ctb`; `"none"` (or `""`) draws every object with its own properties, also in a layout that shows its own plot styles (without `plot_style` such a layout draws with its table, as on screen). An unknown value is refused. The result is an image content block (`content[0].type` is `"image"`), not text. |
|
||||
| `find_text {contains?, query?, layer?, window?, limit?, offset?}` | The readable texts — TEXT, MTEXT without formatting codes, block attributes, multileaders — with text, insertion point, height, rotation, style, layer and handle; filtered by content (`contains`, or `query` as an alias; any case), layer and a window around the insertion points. Read-only (the `texts` command). |
|
||||
| `new_drawing {metric?}`, `open {path}`, `save {path?}`, `cancel` | Files and Escape. `save` to a `.svg`, `.png` or `.pdf` path exports: the drawing keeps its name and unsaved changes. |
|
||||
| `agent_folders` | The folders this session may open from (`read_folder`) and save to (`write_folder`), and whether files outside them are refused (`confined`). |
|
||||
| `screenshot`, `ui_inspect`, `ui_click {x, y}` | Only when connected to the app. |
|
||||
|
||||
Resources: `cadcraft://drawing` (inspect JSON) and `cadcraft://commands` (catalog).
|
||||
|
||||
Reference in new issue
Block a user