Merge main into fix/open-dwg-files

This commit is contained in:
dotCooCoo committed 2026-12-04 06:36:17 -08:00
commit 2e030ec46d
34 files changed
+3799 -243

No files matched your search

Generated
+27
View File
@@ -1262,6 +1262,7 @@ dependencies = [
"craft-browse",
"craft-cms",
"craft-color-ui",
"craft-control",
"craft-dialogs",
"craft-draw",
"craft-font-catalog",
@@ -1304,6 +1305,16 @@ dependencies = [
"ruzstd",
]
[[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"
@@ -1441,8 +1452,13 @@ name = "craft-control"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
dependencies = [
"craft-ai-agents",
"craft-atomic",
"craft-control-protocol",
"craft-flags",
"craft-platform",
"dirs",
"log",
"serde",
"serde_json",
]
@@ -1570,6 +1586,16 @@ name = "craft-eps"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
[[package]]
name = "craft-flags"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=77ade517ecb2a6ad86feb2f9983a098ad5738fc6#77ade517ecb2a6ad86feb2f9983a098ad5738fc6"
dependencies = [
"craft-atomic",
"dirs",
"toml_edit",
]
[[package]]
name = "craft-font-catalog"
version = "0.1.0"
@@ -8699,6 +8725,7 @@ dependencies = [
name = "vectorcraft-cli"
version = "0.25.1"
dependencies = [
"craft",
"craft-dwg",
"log",
"objc2-core-foundation",
+3
View File
@@ -25,6 +25,8 @@ vectorcraft-render = { workspace = true }
vectorcraft-text = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
# The agent settings and the desktop app to start for plain `mcp` (the shared `src/agent_settings.rs`).
craft = { workspace = true, features = ["automation-agents"] }
# `perf` on Windows (src/perf.rs) reads how busy the processors are (GetSystemTimes) and this
# process's working set (GetProcessMemoryInfo) through winsafe's safe wrappers over Win32 (MIT),
@@ -54,6 +56,7 @@ serde_json = { workspace = true }
# The files of other crates that this crate compiles or its tests read, for CI's test selection.
[package.metadata.craft]
reads = [
"apps/vectorcraft/src/agent_settings.rs",
"apps/vectorcraft/src/mac_fonts.rs",
"apps/vectorcraft/src/prefs_dir.rs",
"apps/vectorcraft/src/profile.rs",
+64 -12
View File
@@ -2,7 +2,7 @@
//!
//! ```text
//! vectorcraft-cli --safe-mode SUBCOMMAND ...
//! vectorcraft-cli mcp [--connect 127.0.0.1:7979 | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]...
//! vectorcraft-cli mcp [--headless] [--when-closed launch|headless|error] [--automation-read-root DIR]... [--automation-write-root DIR]...
//! vectorcraft-cli run [--in FILE] [--cmd id [--params '{json}'] | --commands FILE|-]... [--export out.svg]... [--scale 2] [--ppi 300] [--width 1920] [--height 1080] [--background transparent]
//! vectorcraft-cli commands
//! vectorcraft-cli convert IN OUT [--scale 2] [--ppi 300] [--width 1920] [--height 1080] [--background transparent] [--artboard 0 | --range 1-3,5] [--outline-text] [--decimals N] [--replace-lossy] [--editing-data] [--legacy-name-encoding ENC] [--preserve-editing] [--ai-version 7|pdf] [--hidden-objects layer|omit|visible] [--transparent-images flatten|omit]
@@ -39,6 +39,10 @@ macro_rules! out {
}};
}
/// The desktop app's agent settings (Preferences › AI Integrations), shared: plain `mcp` reads the
/// closed-app choice and the agent folders the app saved.
#[path = "../../vectorcraft/src/agent_settings.rs"]
mod agent_settings;
/// The desktop app's CoreText font lister, shared: exports and MCP find the same fonts.
#[cfg(target_os = "macos")]
#[path = "../../vectorcraft/src/mac_fonts.rs"]
@@ -56,9 +60,11 @@ mod system_fonts;
#[path = "../../vectorcraft/src/windows_cores.rs"]
mod windows_cores;
use craft::automation::agents::WhenAppClosed;
use serde_json::{Value, json};
use vectorcraft_engine::file_access::{self, AutomationRoots};
use vectorcraft_mcp::{Backend, DEFAULT_ADDR, Headless, Remote, Server};
use vectorcraft_mcp::agents::{LiveBackend, LiveConfig};
use vectorcraft_mcp::{Backend, Headless, Remote, Server};
/// stdout went away. A reader that stopped early (a closed pipe) ends the program quietly, as
/// ripgrep does; any other write error is reported.
@@ -79,9 +85,18 @@ USAGE:
Safe Mode is on. Plug-ins stay installed. `--safe-mode mcp` serves a headless session and
does not take --connect.
vectorcraft-cli mcp [--connect ADDR | --headless] [--automation-read-root DIR]... [--automation-write-root DIR]... [--allow-plugin-grants]
Run the MCP server on stdio. Default: connect to a running app at 127.0.0.1:7979
(vectorcraft --control 7979), falling back to a headless in-process session.
vectorcraft-cli mcp [--headless] [--when-closed launch|headless|error] [--automation-read-root DIR]... [--automation-write-root DIR]... [--allow-plugin-grants]
Run the MCP server on stdio. Every tool call goes to the open VectorCraft window while AI
agents may use it (ArtCraft Launcher › Settings › AI agents), found through the connection
file the window publishes in the settings folder: no port or token to configure, and an app
opened after the session started is found too. Otherwise the call runs in a session without
a window. While agents may use VectorCraft but it is closed, the choice in Preferences › AI
Integrations applies (open VectorCraft, a session without a window in the agent folders, or
an error); --when-closed overrides it. Files of the open window's agent requests stay in the
agent folders set there (Documents/ArtCraft/Agents/VectorCraft when none is set); the
agent_folders tool names them. --headless always runs without a window.
--connect ADDR (deprecated, removed in a later release) drives an app started with
vectorcraft --control PORT and its VECTORCRAFT_CONTROL_TOKEN.
--automation-read-root / --automation-write-root confine the files the agent's commands read
(open, place, relink, library loads…) and write (save, export, package, library saves…) to
DIR, links followed; each may be given more than once, a path inside any of its folders being
@@ -286,6 +301,20 @@ fn with_stores(mut h: Headless) -> Headless {
h
}
/// Plain `mcp`'s window lookup: the agent settings in `dir`, the closed-app choice (`--when-closed`
/// overrides the saved one), the desktop app beside this CLI to start, and headless sessions with
/// the user's stores, or confined to the agent folders without them.
fn live_config(dir: std::path::PathBuf, when_closed: Option<WhenAppClosed>) -> LiveConfig {
let mut cfg = LiveConfig::new(dir, agent_settings::read_settings);
cfg.when_closed = when_closed;
cfg.launch = std::env::current_exe().ok().and_then(|cli| craft::automation::agents::launcher(&cli, vectorcraft_mcp::agents::APP_EXE));
cfg.headless = Box::new(|roots| match roots {
Some(roots) => Headless::with_document().with_automation_roots(Some(roots)),
None => with_stores(Headless::with_document()),
});
cfg
}
/// Makes `h`'s `plugin.install` accept `grant` and `allowHeavy` when `allow` (`--allow-plugin-grants`).
fn accepting_grants(mut h: Headless, allow: bool) -> Headless {
if allow {
@@ -294,26 +323,34 @@ fn accepting_grants(mut h: Headless, allow: bool) -> Headless {
h
}
/// `mcp`. With `--safe-mode` (`safe_mode`) it serves a headless session: a running app loads its own
/// plug-ins, so `--connect` is refused and the default does not connect.
/// The stderr line `mcp --connect` prints: the flag works for one more release.
const CONNECT_DEPRECATED: &str = "vectorcraft-cli: --connect is deprecated and will be removed in a later release; plain `vectorcraft-cli mcp` finds the open VectorCraft window while AI agents are on in ArtCraft Launcher › Settings › AI agents";
/// `mcp`: the open VectorCraft window while the person lets agents use it (the ArtCraft Launcher's
/// switch), found through its connection file on every tool call, otherwise a headless session
/// (`vectorcraft_mcp::agents`). `--headless`, the automation roots, `--allow-plugin-grants` and
/// `--safe-mode` (`safe_mode`: a running app loads its own plug-ins) always run headless.
/// `--connect ADDR` drives an app started with `vectorcraft --control PORT` (deprecated).
fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
if help_requested(args, &["--connect", "--automation-read-root", "--automation-write-root"]) {
if help_requested(args, &["--connect", "--when-closed", "--automation-read-root", "--automation-write-root"]) {
return help();
}
let mut connect: Option<String> = None;
let mut headless = false;
let mut when_closed: Option<String> = None;
let mut allow_grants = false;
let (mut read_roots, mut write_roots): (Vec<String>, Vec<String>) = (vec![], vec![]);
let mut it = args.iter();
while let Some(a) = it.next() {
// The roots also come as `--flag=DIR`, as the other Craft apps take them.
let (flag, inline) = match a.split_once('=') {
Some((f, v)) if f.starts_with("--automation-") => (f, Some(v.to_string())),
Some((f, v)) if f.starts_with("--automation-") || f == "--when-closed" => (f, Some(v.to_string())),
_ => (a.as_str(), None),
};
match flag {
"--connect" => connect = Some(it.next().cloned().ok_or("--connect needs an address")?),
"--headless" => headless = true,
"--when-closed" => when_closed = Some(inline.or_else(|| it.next().cloned()).ok_or("--when-closed needs launch, headless or error")?),
"--allow-plugin-grants" => allow_grants = true,
"--automation-read-root" | "--automation-write-root" => {
let dir = inline.or_else(|| it.next().cloned()).ok_or_else(|| format!("{flag} needs a folder"))?;
@@ -334,6 +371,16 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
if safe_mode && connect.is_some() {
return Err("--safe-mode runs a headless session without plug-ins; a running app loads its own: start it with `vectorcraft --safe-mode --control <port>`".into());
}
let when_closed = match when_closed.as_deref() {
None => None,
Some(choice) => {
let parsed = WhenAppClosed::parse(choice).ok_or_else(|| format!("--when-closed must be launch, headless or error, not `{choice}`"))?;
if connect.is_some() || headless || safe_mode || allow_grants || !(read_roots.is_empty() && write_roots.is_empty()) {
return Err("--when-closed is for the open window of plain `mcp`; --connect, --headless, --safe-mode, --allow-plugin-grants and the automation roots never use it".into());
}
Some(parsed)
}
};
let read: Vec<&Path> = read_roots.iter().map(Path::new).collect();
let write: Vec<&Path> = write_roots.iter().map(Path::new).collect();
let roots = AutomationRoots::new(&read, &write)?;
@@ -349,13 +396,18 @@ fn mcp(args: &[String], safe_mode: bool) -> Result<(), String> {
} else if headless || safe_mode || allow_grants {
Box::new(accepting_grants(with_stores(Headless::with_document()), allow_grants))
} else if let Some(addr) = connect {
eprintln!("{CONNECT_DEPRECATED}");
// Explicit address: fail loudly if the app isn't there.
let token = vectorcraft_mcp::control_token()?;
Box::new(Remote::connect(&addr, &token).map_err(|e| format!("cannot connect to {addr}: {e}"))?)
} else {
// No token or no app listening: the headless session answers instead.
match vectorcraft_mcp::control_token().ok().and_then(|token| Remote::connect(DEFAULT_ADDR, &token).ok()) {
Some(r) => Box::new(r),
match prefs_dir::prefs_dir() {
Some(dir) => Box::new(LiveBackend::new(live_config(dir, when_closed))),
// No settings folder (no home folder): no window can be found either, so `--when-closed error`
// refuses rather than answering from a session the agent didn't ask for.
None if when_closed == Some(WhenAppClosed::Error) => {
return Err("VectorCraft's settings folder can't be found (no home folder), so its window can't be either: open VectorCraft, or run `mcp` without `--when-closed error`".into());
}
None => Box::new(with_stores(Headless::with_document())),
}
};
+17
View File
@@ -836,3 +836,20 @@ fn runs_without_preferences_remember_nothing() {
let r = run_in(&config, &[("pdf.preset.list", json!({}))]);
assert!(r[0]["presets"].as_array().unwrap().iter().all(|p| p["builtIn"] == true));
}
/// Plain `mcp` takes `--when-closed` for the open window only, and `--connect` still works for one
/// release but says it is deprecated before it connects.
#[test]
fn mcp_when_closed_and_the_deprecated_connect() {
let fails = |args: &[&str], why: &str| {
let out = Command::new(crate::bin()).args(args).env("VECTORCRAFT_NO_PREFS", "1").stdin(Stdio::null()).output().unwrap();
let err = String::from_utf8_lossy(&out.stderr);
assert!(!out.status.success() && err.contains(why), "{args:?}: {err}");
err.into_owned()
};
fails(&["mcp", "--when-closed", "later"], "--when-closed must be launch, headless or error");
fails(&["mcp", "--when-closed", "launch", "--headless"], "--when-closed is for the open window");
fails(&["mcp", "--when-closed=error", "--connect", "127.0.0.1:1"], "--when-closed is for the open window");
let err = fails(&["mcp", "--connect", "127.0.0.1:1"], "--connect is deprecated");
assert!(err.contains("cannot connect") || err.contains("no control token"), "{err}");
}
+77
View File
@@ -0,0 +1,77 @@
//! The agent settings of Preferences › AI Integrations, in `agents.json` in the settings folder
//! (`prefs_dir.rs`). The desktop app writes them when they change (`prefs.agents`); `vectorcraft-cli`
//! (which shares this file) reads them on every tool call of plain `mcp`, for the closed-app choice
//! and the agent folders.
use std::io::Read as _;
use std::path::Path;
use craft::automation::agents::AgentSettings;
use serde_json::Value;
/// The file in the settings folder: `{"controlPort", "readRoot", "writeRoot", "whenAppClosed",
/// "allowAgentControl"}`, the framework's `AgentSettings`.
pub const SETTINGS_FILE: &str = "agents.json";
/// The largest settings file read; the settings are a few short strings.
const MAX_SETTINGS_FILE: u64 = 64 * 1024;
/// The agent settings saved in `dir`; the defaults when nothing is saved or the file can't be read,
/// so neither the app nor the CLI fails over them. One bad value resets only itself.
pub fn read_settings(dir: &Path) -> AgentSettings {
let Ok(file) = std::fs::File::open(dir.join(SETTINGS_FILE)) else { return AgentSettings::default() };
let mut text = String::new();
if file.take(MAX_SETTINGS_FILE + 1).read_to_string(&mut text).is_err() || text.len() as u64 > MAX_SETTINGS_FILE {
return AgentSettings::default();
}
let Ok(Value::Object(saved)) = serde_json::from_str::<Value>(&text) else { return AgentSettings::default() };
let mut settings = AgentSettings::default();
for (key, value) in saved {
let Ok(Value::Object(mut one)) = serde_json::to_value(&settings) else { continue };
if one.contains_key(&key) {
one.insert(key, value);
if let Ok(next) = serde_json::from_value(Value::Object(one)) {
settings = next;
}
}
}
settings
}
/// Saves `settings` in `dir` (created when missing), replacing the file in one step, so a
/// `vectorcraft-cli mcp` reading it at the same time sees the old or the new settings, never half.
// The desktop writes the settings; `vectorcraft-cli` includes this file and only reads them.
#[allow(dead_code)]
pub fn write_settings(dir: &Path, settings: &AgentSettings) -> std::io::Result<()> {
std::fs::create_dir_all(dir)?;
let text = serde_json::to_vec_pretty(settings).map_err(std::io::Error::other)?;
let partial = dir.join(format!("{SETTINGS_FILE}.{}.tmp", std::process::id()));
std::fs::write(&partial, text)?;
std::fs::rename(&partial, dir.join(SETTINGS_FILE)).inspect_err(|_| {
let _ = std::fs::remove_file(&partial);
})
}
#[cfg(test)]
mod tests {
use super::*;
use craft::automation::agents::WhenAppClosed;
// Settings saved by the app read back in the CLI, and a damaged file or value never fails it.
#[test]
fn saved_settings_read_back_and_bad_values_reset_alone() {
let dir = tempfile::tempdir().unwrap();
assert_eq!(read_settings(dir.path()), AgentSettings::default());
let mut settings = AgentSettings::default();
settings.read_root = "/in".into();
settings.when_app_closed = WhenAppClosed::Headless;
write_settings(dir.path(), &settings).unwrap();
assert_eq!(read_settings(dir.path()), settings);
std::fs::write(dir.path().join(SETTINGS_FILE), "not json").unwrap();
assert_eq!(read_settings(dir.path()), AgentSettings::default());
std::fs::write(dir.path().join(SETTINGS_FILE), r#"{"whenAppClosed": "error", "readRoot": 5, "unknown": true}"#).unwrap();
let read = read_settings(dir.path());
assert_eq!(read.when_app_closed, WhenAppClosed::Error);
assert_eq!(read.read_root, "");
}
}
+31
View File
@@ -27,6 +27,7 @@
//! how the window's frames reach the display (`presentation`).
#![cfg_attr(all(target_os = "windows", not(debug_assertions)), windows_subsystem = "windows")]
mod agent_settings;
mod automation_args;
#[cfg(test)]
mod build_channel;
@@ -516,6 +517,30 @@ fn launch_arguments(nightly: bool, arguments: &[std::ffi::OsString]) -> Vec<Stri
if nightly { arguments.iter().map(|a| a.to_string_lossy().into_owned()).collect() } else { std::env::args().skip(1).collect() }
}
/// Agents in the open window (`vectorcraft_ui_egui::agents`): while the ArtCraft Launcher's switch
/// names VectorCraft, the window serves agents on loopback and publishes the connection in its
/// settings folder, where `vectorcraft-cli mcp` finds it. A connection file a crashed run left is
/// removed first. With `--control` (`control_port`, served by `launched`) that channel serves the
/// whole run and the link stays off. A nightly and a run without preferences have no link.
fn agents_link(ctx: &egui::Context, control_port: Option<u16>, launched: Option<&Listening>) -> Option<vectorcraft_ui_egui::agents::Agents> {
use craft::automation::agents::{AgentSwitch, remove_stale_connection};
use vectorcraft_ui_egui::agents::{Agents, LAUNCHER_APP_ID, SaveFn};
let dir = prefs_dir::prefs_dir()?;
remove_stale_connection(&dir);
let switch = AgentSwitch::watch(LAUNCHER_APP_ID, {
let ctx = ctx.clone();
move || ctx.request_repaint()
});
let save_dir = dir.clone();
let save: SaveFn = Box::new(move |settings| {
agent_settings::write_settings(&save_dir, settings).map_err(|e| format!("couldn't save the agent settings in {}: {e}", save_dir.display()))
});
let version = format!("VectorCraft {}", env!("VECTORCRAFT_BUILT_VERSION"));
let agents = Agents::new(Some(dir.clone()), version, switch, agent_settings::read_settings(&dir), save);
// The port it listens on (the one the system picked for `--control 0`), none when it couldn't.
Some(if control_port.is_some() { agents.launched_with_control(launched.map(|l| l.addr.port())) } else { agents })
}
/// The control channel's port, and the token's notice with the token itself.
type ControlChannel = (Option<u16>, Option<(String, String)>);
@@ -1056,6 +1081,12 @@ fn main() -> std::process::ExitCode {
}
}
}
if !nightly
&& prefs_enabled()
&& let Some(agents) = agents_link(&cc.egui_ctx, control_port, control_server.as_ref())
{
app = app.with_agents(agents);
}
#[cfg(target_os = "macos")]
{
open_documents::set_ui(&cc.egui_ctx);
+6 -1
View File
@@ -93,7 +93,7 @@ impl AutomationRoots {
/// Roots that grant no access of either kind: inside [`confine`] with them, every path a
/// command reads or writes is refused.
pub(crate) fn none() -> Arc<Self> {
pub fn none() -> Arc<Self> {
Arc::new(Self { read: Vec::new(), write: Vec::new() })
}
@@ -124,6 +124,11 @@ impl AutomationRoots {
if roots.iter().any(|r| inside(real, &r.resolved)) { Ok(()) } else { Err(refused(roots, &real.display().to_string(), access)) }
}
/// The folders of the kind `access`, as people read them.
pub fn folders(&self, access: Access) -> impl Iterator<Item = &Path> {
self.of(access).iter().map(|r| r.shown.as_path())
}
/// The roots of the kind `access`.
fn of(&self, access: Access) -> &[Root] {
match access {
+3 -1
View File
@@ -22,7 +22,9 @@ vectorcraft-format = { workspace = true }
vectorcraft-tools = { workspace = true }
vectorcraft-geom = { workspace = true }
vectorcraft-doc = { workspace = true }
craft = { workspace = true, features = ["automation"] }
# `automation-agents` and `control-agents`: plain `mcp` finds the open window through the ArtCraft
# Launcher's switch and the connection file, with the shared live client and the agent folders.
craft = { workspace = true, features = ["automation", "automation-agents", "control-agents"] }
serde_json = { workspace = true }
log = { workspace = true }
+336
View File
@@ -0,0 +1,336 @@
//! Agents in the open window: the CLI's side of the ArtCraft Launcher's switch.
//!
//! While the launcher's *Settings › AI agents* switch names VectorCraft (behind the suite's `AI-MCP`
//! flag), the desktop app serves its control channel on loopback and publishes where in its
//! settings folder (`craft::automation::agents::AgentLink`, `vectorcraft_ui_egui::agents`). Plain
//! `vectorcraft-cli mcp` reads that file on every tool call ([`LiveBackend`], over the shared
//! `craft::automation::agents::Live`), so an MCP client's configuration holds no port and no token,
//! and the app may start, quit or move to another port while the client stays connected. Adding
//! VectorCraft to MCP clients is the launcher's job (one entry for every Craft app); VectorCraft
//! writes no client configuration.
//!
//! What is VectorCraft's here: its launcher id, its window client ([`Window`], which makes the app
//! prove it holds the token before it proves it holds it too) and its headless session
//! ([`Headless`] with the agent folders as automation roots).
use std::cell::RefCell;
use std::io::{BufRead, BufReader, ErrorKind, Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant};
use craft::automation::agents::{self as shared, AgentSettings, Consent, HeadlessFolders, Route, WhenAppClosed};
use craft::automation::client::{CALL_TIMEOUT, CONNECT_TIMEOUT, MAX_REPLY_BYTES};
use craft::automation::security::{self, ProofRole};
use craft::control::agents::{AgentFolders, folders_answer};
use serde_json::{Value, json};
use vectorcraft_engine::file_access::{Access, AutomationRoots};
use crate::backend::Backend;
use crate::headless::Headless;
/// The id the ArtCraft Launcher's app list names VectorCraft by (its catalog id).
pub const LAUNCHER_APP_ID: &str = "vectorcraft";
/// The app's name in messages and its default agent folder (`Documents/ArtCraft/Agents/VectorCraft`).
pub const APP_NAME: &str = "VectorCraft";
/// The desktop app's file name beside the CLI (without `.exe`).
pub const APP_EXE: &str = "vectorcraft";
/// The method the `agent_folders` tool calls: the folders this session's file commands may use.
pub const FOLDERS_METHOD: &str = "agent.folders";
/// What a tool that needs the window says in a session without one.
pub const NEEDS_WINDOW: &str = "needs the open VectorCraft window: open VectorCraft with AI agents on (ArtCraft Launcher › Settings › AI agents) and run `vectorcraft-cli mcp` without --headless";
/// Whether the person lets agents use VectorCraft now: with the suite's `AI-MCP` flag, the
/// launcher's switch. VectorCraft had no agent consent of its own before the switch, so without
/// the flag agents get a session without a window.
pub fn allowed_now() -> bool {
shared::agents_allowed(shared::mcp_flag(), shared::launcher_allows(LAUNCHER_APP_ID), false)
}
/// The automation roots for `folders`: what a session with these folders may open and save. A kind
/// without a folder is refused, and so is everything when there is no folder at all.
pub fn roots_for(folders: &AgentFolders) -> Result<Arc<AutomationRoots>, String> {
let read: Vec<&Path> = folders.read.as_deref().into_iter().collect();
let write: Vec<&Path> = folders.write.as_deref().into_iter().collect();
Ok(AutomationRoots::new(&read, &write)?.unwrap_or_else(AutomationRoots::none))
}
/// The `agent_folders` answer of a headless session confined to `roots` (`None`: not confined).
/// With more than one folder of a kind (`--automation-read-root` given twice), `read_folders` /
/// `write_folders` list them all.
pub(crate) fn headless_folders(roots: Option<&AutomationRoots>) -> Value {
let Some(roots) = roots else {
// A session started without automation roots (`--headless` without them, or with the
// agents switch off) isn't confined: say so rather than claim it has no folders.
return json!({
"read_folder": null,
"write_folder": null,
"unrestricted": true,
"note": "This session was started without automation roots: its file commands open and save wherever the user can.",
});
};
let (read, write): (Vec<&Path>, Vec<&Path>) = (roots.folders(Access::Read).collect(), roots.folders(Access::Write).collect());
let mut folders = AgentFolders::default();
folders.read = read.first().map(|p| p.to_path_buf());
folders.write = write.first().map(|p| p.to_path_buf());
let mut answer = folders_answer(&folders);
for (key, all) in [("read_folders", &read), ("write_folders", &write)] {
if all.len() > 1
&& let Some(o) = answer.as_object_mut()
{
o.insert(key.into(), json!(all.iter().map(|p| p.to_string_lossy()).collect::<Vec<_>>()));
}
}
answer
}
// ---- The open window ---------------------------------------------------------------------------
/// How often a call waiting for its reply looks whether it was cancelled.
const CANCEL_POLL: Duration = Duration::from_millis(100);
/// One authenticated connection to the open window. The app proves it holds the token first
/// (`auth.challenge`), then the client answers with its own proof: the token never crosses the
/// wire, and a program that took a stale port learns nothing derived from it.
pub struct Window {
addr: SocketAddr,
token: String,
conn: Option<(BufReader<TcpStream>, TcpStream)>,
next_id: u64,
}
impl Window {
/// A client for the window on `127.0.0.1:port` with `token`; connects on the first call.
pub fn new(port: u16, token: String) -> Self {
Self { addr: SocketAddr::from(([127, 0, 0, 1], port)), token, conn: None, next_id: 1 }
}
/// Connects and runs the challenge handshake.
pub fn connect(&mut self) -> Result<(), String> {
self.conn = None;
let stream = TcpStream::connect_timeout(&self.addr, CONNECT_TIMEOUT).map_err(|e| e.to_string())?;
stream.set_nodelay(true).ok();
stream.set_write_timeout(Some(CALL_TIMEOUT)).map_err(|e| e.to_string())?;
let mut conn = (BufReader::new(stream.try_clone().map_err(|e| e.to_string())?), stream);
let client_nonce = security::generate_nonce().map_err(|e| e.to_string())?;
let challenge = round_trip(&mut conn, 0, security::CHALLENGE_METHOD, json!({"clientNonce": client_nonce}), false)?
.map_err(|e| format!("{} refused challenge authentication ({e}); the agent token was not used", self.addr))?;
let field = |key: &str| challenge.get(key).and_then(Value::as_str).filter(|v| security::is_hex256(v)).map(str::to_owned);
let (Some(server_nonce), Some(server_proof)) = (field("serverNonce"), field("serverProof")) else {
return Err(format!("{} answered the challenge without a proof; the agent token was not used", self.addr));
};
if !security::proof_matches(&self.token, ProofRole::Server, &client_nonce, &server_nonce, &server_proof) {
return Err(format!("{} could not prove it holds VectorCraft's agent token; nothing was sent to it", self.addr));
}
let proof = security::handshake_proof(&self.token, ProofRole::Client, &client_nonce, &server_nonce).map_err(|e| e.to_string())?;
round_trip(&mut conn, 0, security::AUTH_METHOD, json!({"proof": proof}), false)?
.map_err(|e| format!("VectorCraft refused the agent token: {e}"))?;
self.conn = Some(conn);
Ok(())
}
}
/// Sends one request and reads the reply with its `id` (lines for other ids are skipped): `Err`
/// when the connection failed or the call was cancelled while it waited, `Ok(Err)` when the app
/// answered with an error. With `cancellable`, a cancelled MCP call stops waiting.
fn round_trip(
conn: &mut (BufReader<TcpStream>, TcpStream),
id: u64,
method: &str,
params: Value,
cancellable: bool,
) -> Result<Result<Value, String>, String> {
let (reader, writer) = conn;
let line = json!({"id": id, "method": method, "params": params}).to_string();
writer.write_all(line.as_bytes()).and_then(|()| writer.write_all(b"\n")).and_then(|()| writer.flush()).map_err(|e| e.to_string())?;
let deadline = Instant::now() + CALL_TIMEOUT;
loop {
let reply = read_line(reader, deadline, cancellable)?;
let v: Value = serde_json::from_slice(&reply).map_err(|e| format!("bad reply from the window: {e}"))?;
if v.get("id").and_then(Value::as_u64) != Some(id) {
continue;
}
return Ok(if v.get("ok").and_then(Value::as_bool) == Some(true) {
Ok(v.get("result").cloned().unwrap_or(Value::Null))
} else {
Err(v.get("error").and_then(Value::as_str).unwrap_or("unknown error").to_owned())
});
}
}
/// One reply line, at most [`MAX_REPLY_BYTES`], read by `deadline`.
fn read_line(reader: &mut BufReader<TcpStream>, deadline: Instant, cancellable: bool) -> Result<Vec<u8>, String> {
let mut line = Vec::new();
loop {
let left = deadline.saturating_duration_since(Instant::now());
if left.is_zero() {
return Err("the window did not answer in time".into());
}
reader.get_ref().set_read_timeout(Some(left.min(CANCEL_POLL))).map_err(|e| e.to_string())?;
let room = (MAX_REPLY_BYTES + 1).saturating_sub(line.len() as u64);
// `read_until` keeps what it read before a timeout, so the line goes on where it stopped.
match reader.by_ref().take(room).read_until(b'\n', &mut line) {
Ok(0) => return Err("the window closed the connection".into()),
Ok(_) if line.ends_with(b"\n") => return Ok(line),
Ok(_) if line.len() as u64 > MAX_REPLY_BYTES => return Err("the window's reply is too long".into()),
Ok(_) => return Err("the window closed the connection".into()),
Err(e) if matches!(e.kind(), ErrorKind::WouldBlock | ErrorKind::TimedOut) => {
if cancellable && vectorcraft_engine::cancel::is_cancelled() {
return Err("cancelled".into());
}
}
Err(e) if e.kind() == ErrorKind::Interrupted => {}
Err(e) => return Err(e.to_string()),
}
}
}
impl Backend for Window {
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
if self.conn.is_none() {
self.connect().map_err(|e| format!("the VectorCraft window is not reachable: {e}; `{method}`: nothing was sent"))?;
}
let id = self.next_id;
self.next_id = self.next_id.wrapping_add(1).max(1);
let Some(conn) = self.conn.as_mut() else { return Err("not connected".into()) };
let cancellable = vectorcraft_engine::cancel::is_cancellable();
match round_trip(conn, id, method, params, cancellable) {
Ok(answer) => answer,
// Never sent again: the request may have run. The next call reconnects.
Err(e) => {
self.conn = None;
if e == "cancelled" {
return Err(format!(
"the VectorCraft window: `{method}` cancelled; the app may still finish what it was asked, which can't be stopped from here"
));
}
Err(format!("lost the connection to the VectorCraft window ({e}); `{method}` may or may not have run: inspect state before retrying"))
}
}
}
fn has_ui(&self) -> bool {
true
}
fn describe(&self) -> String {
format!("the open VectorCraft window ({})", self.addr)
}
}
// ---- The live backend --------------------------------------------------------------------------
type SharedWindow = Arc<Mutex<Window>>;
/// The headless session stays on the server's thread, as the backend does.
type SharedHeadless = Rc<RefCell<Headless>>;
/// Makes each new headless session (the CLI attaches the user's stores) from its automation roots.
pub type HeadlessMaker = Box<dyn Fn(Option<Arc<AutomationRoots>>) -> Headless + Send + Sync>;
/// What plain `vectorcraft-cli mcp` needs to find the window.
pub struct LiveConfig {
/// The app's settings folder: connection file, token file and agent settings.
pub config_dir: PathBuf,
/// Reads the agent settings saved in a settings folder (`agents.json`).
pub read_settings: fn(&Path) -> AgentSettings,
/// Overrides the app's closed-app choice (`--when-closed`).
pub when_closed: Option<WhenAppClosed>,
/// The command's folders (`--automation-read-root`, `--automation-write-root`).
pub read_roots: Vec<PathBuf>,
pub write_root: Option<PathBuf>,
/// Starts the app; `None` when this install can't.
pub launch: Option<shared::LaunchFn>,
pub launch_timeout: Duration,
/// Whether agents may use the app now ([`allowed_now`]); tests replace it.
pub allowed: fn() -> bool,
/// The default agent folder for an empty folder setting; tests replace it.
pub default_folder: Option<PathBuf>,
/// Makes each new headless session.
pub headless: HeadlessMaker,
}
impl LiveConfig {
/// The settings in `config_dir` as `read_settings` reads them, the launcher's switch, the
/// default agent folder, and a plain headless session with a document.
pub fn new(config_dir: PathBuf, read_settings: fn(&Path) -> AgentSettings) -> Self {
Self {
config_dir,
read_settings,
when_closed: None,
read_roots: Vec::new(),
write_root: None,
launch: None,
launch_timeout: shared::LAUNCH_TIMEOUT,
allowed: allowed_now,
default_folder: craft::control::agents::default_folder(APP_NAME),
headless: Box::new(|roots| Headless::with_document().with_automation_roots(roots)),
}
}
}
/// Plain `vectorcraft-cli mcp`: every call goes to the open window while the person lets agents
/// use it, otherwise to a headless session; a closed app follows the closed-app choice. The lookup
/// is the shared `craft::automation::agents::Live`; a session that went headless stays headless.
pub struct LiveBackend {
live: shared::Live<SharedWindow, SharedHeadless>,
config_dir: PathBuf,
read_settings: fn(&Path) -> AgentSettings,
default_folder: Option<PathBuf>,
}
impl LiveBackend {
pub fn new(cfg: LiveConfig) -> Self {
let LiveConfig { config_dir, read_settings, when_closed, read_roots, write_root, launch, launch_timeout, allowed, default_folder, headless } =
cfg;
let consent = move |dir: &Path| Consent::new(allowed(), read_settings(dir));
let connect = |w: &shared::Window| -> Result<SharedWindow, String> {
let mut window = Window::new(w.port, w.token.clone());
window.connect()?;
Ok(Arc::new(Mutex::new(window)))
};
let make_headless = move |wanted: &HeadlessFolders| -> Result<SharedHeadless, String> {
let roots = if wanted.read.is_empty() && wanted.write.is_none() {
None
} else {
let read: Vec<&Path> = wanted.read.iter().map(PathBuf::as_path).collect();
let write: Vec<&Path> = wanted.write.as_deref().into_iter().collect();
Some(AutomationRoots::new(&read, &write)?.unwrap_or_else(AutomationRoots::none))
};
Ok(Rc::new(RefCell::new(headless(roots))))
};
let mut shared_cfg = shared::LiveConfig::new(APP_NAME, config_dir.clone(), consent, connect, make_headless);
shared_cfg.when_closed = when_closed;
shared_cfg.read_roots = read_roots;
shared_cfg.write_root = write_root;
shared_cfg.launch = launch;
shared_cfg.launch_timeout = launch_timeout;
shared_cfg.default_folder = default_folder.clone();
Self { live: shared::Live::new(shared_cfg), config_dir, read_settings, default_folder }
}
/// The folders the open window lets agents use, as the window opens them.
fn window_folders(&self) -> Value {
folders_answer(&(self.read_settings)(&self.config_dir).folders_with(self.default_folder.as_deref()))
}
}
impl Backend for LiveBackend {
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
match self.live.resolve()? {
Route::Window(_) if method == FOLDERS_METHOD => Ok(self.window_folders()),
Route::Window(w) => w.lock().unwrap_or_else(PoisonError::into_inner).call(method, params),
Route::Headless(h) => h.borrow_mut().call(method, params),
}
}
fn has_ui(&self) -> bool {
matches!(self.live.resolve(), Ok(Route::Window(_)))
}
fn describe(&self) -> String {
"the open VectorCraft window while AI agents may use it (ArtCraft Launcher › Settings › AI agents), otherwise a session without a window"
.into()
}
}
+6
View File
@@ -86,6 +86,12 @@ impl Remote {
impl Backend for Remote {
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
if method == crate::agents::FOLDERS_METHOD {
return Err(format!(
"the app at {} was started with --control, so agent folders don't apply: its own --automation-read-root and --automation-write-root, if given, confine it",
self.addr
));
}
let addr = self.addr.clone();
let client = self.open_client(method)?;
// The app can't stop what it runs, but a cancelled call stops waiting for it.
+4 -7
View File
@@ -163,13 +163,11 @@ impl Headless {
}
None if KEYBOARD_ONLY.contains(&id) => {
return Err(format!(
"`{id}` opens another app: only the person at the keyboard can run it in the desktop app; control and MCP requests are refused, `--connect` included"
"`{id}` opens another app: only the person at the keyboard can run it in the desktop app; control and MCP requests are refused, in the open window too"
));
}
None if crate::ui_catalog::UI_COMMANDS.iter().any(|(cid, ..)| *cid == id) => {
return Err(format!(
"`{id}` is a desktop UI command (`ui: true`); start `vectorcraft --control 7979` and use `vectorcraft-cli mcp --connect`"
));
return Err(format!("`{id}` is a desktop UI command (`ui: true`): it {}", crate::agents::NEEDS_WINDOW));
}
None => self.session.check_params(id, params).map_err(|e| e.to_string())?,
}
@@ -451,9 +449,8 @@ impl Headless {
"app.save" => self.save(p),
"app.export" => self.export(p),
"app.quit" => Ok(Value::Null),
m if m.starts_with("ui.") => {
Err(format!("`{m}` needs the desktop app (start `vectorcraft --control 7979` and use `vectorcraft-cli mcp --connect`)"))
}
crate::agents::FOLDERS_METHOD => Ok(crate::agents::headless_folders(self.roots.as_deref())),
m if m.starts_with("ui.") => Err(format!("`{m}` {}", crate::agents::NEEDS_WINDOW)),
other => Err(format!("unknown method `{other}`")),
}
}
+9 -2
View File
@@ -4,9 +4,15 @@
//! JSON-RPC 2.0, hand-written (no async runtime). The server exposes VectorCraft as a set of MCP
//! tools and resources and forwards everything to a [`Backend`]:
//!
//! - [`agents::LiveBackend`] (plain `vectorcraft-cli mcp`) sends each call to the open window
//! while the ArtCraft Launcher's switch lets agents use VectorCraft, through the connection file
//! the window publishes ([`agents::Window`]). While agents may not use it, calls go to a
//! [`Headless`] session; while they may but VectorCraft is closed, the closed-app choice of
//! Preferences › AI Integrations (or `--when-closed`) starts the app, uses a headless session in
//! the agent folders, or answers with an error.
//! - [`Remote`] talks to a running desktop app through its loopback JSON-lines control channel
//! (`vectorcraft --control 7979`): one `{"id","method","params"}` line in, one
//! `{"id","ok","result"|"error"}` line out.
//! (`vectorcraft --control 7979`, `vectorcraft-cli mcp --connect`, deprecated): one
//! `{"id","method","params"}` line in, one `{"id","ok","result"|"error"}` line out.
//! - [`Headless`] hosts an in-process [`vectorcraft_engine::Session`] and implements the same
//! control-channel method names itself (rendering screenshots with `vectorcraft-render`), so agents
//! can draw and look at the result without a window.
@@ -15,6 +21,7 @@
#![forbid(unsafe_code)]
#![doc(test(attr(forbid(unsafe_code))))]
pub mod agents;
mod backend;
mod headless;
mod intake;
+1 -1
View File
@@ -405,7 +405,7 @@ Method:
removeWord / dictionary; for this document only, text.spelling.ignoreAll.
4. Prefer those commands over inventing replacements. screenshot if the layout may reflow.
Desktop-only Auto Spell Check is edit.autoSpellCheck (ui: true); use --connect for the underlines.",
Desktop-only Auto Spell Check is edit.autoSpellCheck (ui: true); the underlines need the open window.",
},
PromptDef {
name: "variables-bind",
+5 -3
View File
@@ -4,6 +4,7 @@ use serde_json::{Value, json};
use crate::{Backend, Headless, PROTOCOL_VERSION, Remote, Server, tool_definitions};
mod agents;
mod batchdraw;
mod concurrency;
mod conventions;
@@ -279,10 +280,11 @@ fn tool_schemas_are_valid() {
"transform",
"create_graph",
"text_wrap",
"agent_folders",
] {
assert!(names.contains(want), "missing tool {want}");
}
assert_eq!(tools.len(), 33, "parity docs and #6460 expect 33 MCP tools");
assert_eq!(tools.len(), 34, "parity docs and #6460 expect 34 MCP tools (agent_folders: #10621)");
}
/// Headless `command_list` must expose engine commands that a stale release CLI used to omit (#6460).
@@ -335,7 +337,7 @@ fn headless_command_list_includes_ui_commands() {
}
let r = call(&mut s, 40, "command_run", json!({"id": "view.fitArtboard", "params": {}}));
assert_eq!(r["isError"], true, "{r}");
assert!(text_of(&r).contains("--connect"), "{r}");
assert!(text_of(&r).contains("needs the open VectorCraft window"), "{r}");
}
/// Desktop commands that the app refuses for every automated request are not offered through
@@ -1102,7 +1104,7 @@ fn answer_dialog_needs_the_desktop_app() {
let mut s = server();
let r = call(&mut s, 1, "answer_dialog", json!({"action": "confirm"}));
assert_eq!(r["isError"], true, "{r}");
assert!(text_of(&r).contains("needs the desktop app"), "{r}");
assert!(text_of(&r).contains("needs the open VectorCraft window"), "{r}");
}
/// How long a fake app waits for [`Remote`] to connect or to send, and how long a test waits for
+158
View File
@@ -0,0 +1,158 @@
//! Plain `mcp` in front of the open window (`crate::agents`): the window gets the calls only while
//! agents are allowed and it proves it holds the token; otherwise the closed-app choice applies.
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use craft::automation::agents::{AgentSettings, Connection, TOKEN_FILE, WhenAppClosed, write_connection};
use craft::automation::security::{AuthStep, ServerHandshake};
use serde_json::{Value, json};
use super::TempFolder;
use crate::Backend;
use crate::agents::{FOLDERS_METHOD, LiveBackend, LiveConfig};
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
/// A stand-in for the window's control server holding `token`: it authenticates as the shared
/// server does and answers every request with `{"window": true, "method"}`. The count is of the
/// requests it got after authentication.
fn fake_window(token: &'static str) -> (u16, Arc<AtomicUsize>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let served = Arc::new(AtomicUsize::new(0));
let count = served.clone();
std::thread::spawn(move || {
for stream in listener.incoming() {
let Ok(stream) = stream else { return };
let count = count.clone();
std::thread::spawn(move || {
let mut writer = stream.try_clone().unwrap();
let mut handshake = ServerHandshake::new();
let mut signed_in = false;
for line in BufReader::new(stream).lines() {
let Ok(line) = line else { return };
let reply = if signed_in {
count.fetch_add(1, Ordering::SeqCst);
let req: Value = serde_json::from_str(&line).unwrap();
json!({"id": req["id"], "ok": true, "result": {"window": true, "method": req["method"]}})
} else {
let (reply, step) = handshake.reply(&line, token);
signed_in = matches!(step, AuthStep::Authenticated);
reply
};
if writeln!(writer, "{reply}").is_err() {
return;
}
}
});
}
});
(port, served)
}
/// Publishes a window on `port` in the settings folder `dir`, as the app's agents link does, with
/// [`TOKEN`] in its token file.
fn publish(dir: &Path, port: u16) {
let token_file = dir.join(TOKEN_FILE);
std::fs::write(&token_file, TOKEN).unwrap();
// The client reads only a token its owner alone can read, as the app writes it.
#[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, "VectorCraft test")).unwrap();
}
/// A port nothing listens on.
fn closed_port() -> u16 {
TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
}
fn settings_headless(_: &Path) -> AgentSettings {
let mut s = AgentSettings::default();
s.when_app_closed = WhenAppClosed::Headless;
s
}
fn settings_error(_: &Path) -> AgentSettings {
let mut s = AgentSettings::default();
s.when_app_closed = WhenAppClosed::Error;
s
}
fn live(dir: &Path, allowed: fn() -> bool, read_settings: fn(&Path) -> AgentSettings, default_folder: PathBuf) -> LiveBackend {
let mut cfg = LiveConfig::new(dir.to_path_buf(), read_settings);
cfg.allowed = allowed;
cfg.default_folder = Some(default_folder);
LiveBackend::new(cfg)
}
#[test]
fn plain_mcp_reaches_the_window_while_agents_are_allowed() {
let dir = TempFolder::new("agents-window");
let (port, served) = fake_window(TOKEN);
publish(&dir, port);
let mut b = live(&dir, || true, settings_headless, dir.file("Agents"));
assert!(b.has_ui());
let r = b.call("document.inspect", json!({})).unwrap();
assert_eq!(r["window"], true, "{r}");
assert!(served.load(Ordering::SeqCst) >= 1);
// The window's folders are the agent folders as the window opens them: the default one here.
let folders = b.call(FOLDERS_METHOD, json!({})).unwrap();
assert_eq!(folders["read_folder"], json!(dir.file("Agents").to_string_lossy()));
assert_eq!(folders["write_folder"], folders["read_folder"]);
}
// With agents off the app doesn't listen (its link is the gate), and plain `mcp` runs headless with
// only the command's folders: the closed-app choice (an error here) is for agents the person let in.
#[test]
fn with_agents_off_plain_mcp_runs_headless() {
let dir = TempFolder::new("agents-off");
let mut b = live(&dir, || false, settings_error, dir.file("Agents"));
assert!(!b.has_ui());
let r = b.call("document.inspect", json!({}));
assert!(r.as_ref().is_ok_and(|r| r["window"] != true), "{r:?}");
assert_eq!(b.call(FOLDERS_METHOD, json!({})).unwrap()["unrestricted"], true);
assert!(!dir.file("Agents").exists(), "the agent folder is made only for agents the person let in");
}
#[test]
fn a_window_that_cannot_prove_the_token_gets_nothing() {
let dir = TempFolder::new("agents-bad-token");
let (port, served) = fake_window("fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210");
publish(&dir, port);
let mut b = live(&dir, || true, settings_headless, dir.file("Agents"));
let e = b.call("document.inspect", json!({})).unwrap_err();
assert!(e.contains("could not prove"), "{e}");
assert_eq!(served.load(Ordering::SeqCst), 0);
}
#[test]
fn a_connection_file_with_nothing_listening_follows_the_closed_app_choice() {
let dir = TempFolder::new("agents-stale");
publish(&dir, closed_port());
let mut b = live(&dir, || true, settings_error, dir.file("Agents"));
let e = b.call("document.inspect", json!({})).unwrap_err();
assert!(e.contains("isn't running"), "{e}");
// Headless: a session without a window, confined to the agent folders.
let mut b = live(&dir, || true, settings_headless, dir.file("Agents"));
assert!(!b.has_ui());
let folders = b.call(FOLDERS_METHOD, json!({})).unwrap();
assert_eq!(folders["read_folder"], json!(std::fs::canonicalize(dir.file("Agents")).map(shown).unwrap()));
let outside = dir.file("outside.svg");
std::fs::write(&outside, r#"<svg xmlns="http://www.w3.org/2000/svg" width="4" height="3"/>"#).unwrap();
let e = b.call("app.open", json!({"path": outside.to_string_lossy()})).unwrap_err();
assert!(e.contains("outside the read root"), "{e}");
}
/// A canonical path as the automation roots show it: without Windows' `\\?\` prefix.
fn shown(p: PathBuf) -> String {
let s = p.to_string_lossy().into_owned();
s.strip_prefix(r"\\?\").map_or(s.clone(), str::to_owned)
}
+3 -2
View File
@@ -103,7 +103,7 @@ pub fn tool_definitions() -> Vec<Value> {
tool(
"command_list",
"List commands",
"Discover command ids, labels, parameter descriptions and enabled state. Lists engine and plug-in commands, and desktop UI menu commands (ui: true; running a UI-only id headless needs --connect). A command with a parameter schema also lists it as schema (JSON Schema 2020-12) and as inputSchema (the same schema with an object root, the form of a tool's inputSchema). Returns an array. The whole catalogue is large: narrow it with filter (or query), menu, and brief. list_commands lists the same commands; it takes enabledOnly instead of enabled_only and returns {count, commands}. Effect ids (effect.list) are not command ids.",
"Discover command ids, labels, parameter descriptions and enabled state. Lists engine and plug-in commands, and desktop UI menu commands (ui: true; running a UI-only id needs the open window). A command with a parameter schema also lists it as schema (JSON Schema 2020-12) and as inputSchema (the same schema with an object root, the form of a tool's inputSchema). Returns an array. The whole catalogue is large: narrow it with filter (or query), menu, and brief. list_commands lists the same commands; it takes enabledOnly instead of enabled_only and returns {count, commands}. Effect ids (effect.list) are not command ids.",
obj(
json!({"filter": string("Case-insensitive id, label or menu substring"), "query": string("Same as filter"), "menu": string(MENU_FILTER), "enabled_only": {"type":"boolean"}, "brief": {"type":"boolean", "description": BRIEF}}),
&[],
@@ -161,7 +161,7 @@ pub fn tool_definitions() -> Vec<Value> {
tool(
"list_commands",
"List commands",
"List VectorCraft commands (id, label, menu path, shortcut, parameter description, enabled state, and schema and inputSchema for a command with a parameter schema). Includes engine commands and desktop UI menu commands (ui: true; a UI-only id run headless needs --connect). Every editing action is a command; run any of them with run_command (or invoke_menu for a menu path). Coordinates are points in document space, y down, origin at the first artboard's top-left. command_list lists the same commands as a bare array and takes enabled_only. Effect ids (effect.list) are not command ids.",
"List VectorCraft commands (id, label, menu path, shortcut, parameter description, enabled state, and schema and inputSchema for a command with a parameter schema). Includes engine commands and desktop UI menu commands (ui: true; a UI-only id needs the open window). Every editing action is a command; run any of them with run_command (or invoke_menu for a menu path). Coordinates are points in document space, y down, origin at the first artboard's top-left. command_list lists the same commands as a bare array and takes enabled_only. Effect ids (effect.list) are not command ids.",
obj(
json!({"filter": string("Case-insensitive substring matched against id, label and menu path (e.g. \"align\", \"Object\")"), "query": string("Same as filter"), "menu": string(MENU_FILTER), "enabledOnly": {"type": "boolean", "description": "Only commands that can run right now"}, "brief": {"type": "boolean", "description": BRIEF}}),
&[],
@@ -528,5 +528,6 @@ pub fn tool_definitions() -> Vec<Value> {
),
tool("undo", "Undo", "Undo the last change (Edit → Undo). redo reapplies it.", empty(), false),
tool("redo", "Redo", "Redo the last undone change (Edit → Redo): the change the last undo took back.", empty(), false),
tool(craft::control::agents::FOLDERS_TOOL, "Agent folders", craft::control::agents::FOLDERS_TOOL_DESCRIPTION, empty(), true),
]
}
+1
View File
@@ -219,6 +219,7 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result<ToolResult, Str
j(b.call("ui.set", json!({"panel": req_str(a, "panel")?}))?)
}
"screenshot" => screenshot(b, a),
craft::control::agents::FOLDERS_TOOL => j(b.call(crate::agents::FOLDERS_METHOD, json!({}))?),
"open_file" => {
let path = absolute_path(b, req_str(a, "path")?)?;
let mut p = json!({"path": path});
+2 -8
View File
@@ -11,7 +11,7 @@ pub(super) fn req_str<'a>(a: &'a Args, k: &str) -> Result<&'a str, String> {
}
/// A file tool's path made absolute against this process's working directory when it goes to the app
/// (`--connect`). Headless, and for an empty path, it is returned as given.
/// (the open window). Headless, and for an empty path, it is returned as given.
pub(super) fn absolute_path(b: &dyn Backend, p: &str) -> Result<String, String> {
if p.is_empty() || !b.has_ui() {
return Ok(p.to_owned());
@@ -25,13 +25,7 @@ pub(super) fn exec(b: &mut dyn Backend, cmd: &str, params: Value) -> Result<Valu
}
pub(super) fn need_ui(b: &dyn Backend, tool: &str) -> Result<(), String> {
if b.has_ui() {
Ok(())
} else {
Err(format!(
"`{tool}` needs the desktop app: run `vectorcraft --control 7979` and start the server with `vectorcraft-cli mcp --connect 127.0.0.1:7979`"
))
}
if b.has_ui() { Ok(()) } else { Err(format!("`{tool}` {}", crate::agents::NEEDS_WINDOW)) }
}
/// Paint argument → `paint.setFill` / `paint.setStroke` params.
+6
View File
@@ -171,6 +171,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
),
("app.home", "Home", "", "{} shows the Home screen (new file presets, Open) over the open documents; choosing a document tab returns to it"),
("edit.preferences", "Preferences…", "Cmd+K", "{category?} open Preferences (engine: prefs.get / prefs.set / prefs.list)"),
(
"prefs.agents",
"AI Integrations",
"",
"{controlPort?: 0–65535, readRoot?: string, writeRoot?: string, whenAppClosed?: launch|headless|error} the agent settings of Preferences › AI Integrations (agents in the open window through the ArtCraft Launcher's switch); given keys are saved where vectorcraft-cli mcp reads them, refused from an agent's request → {settings, status: {port, launchFlags, error}, allowed, mcpFlag}; an error in the web build and in a run without preferences",
),
("edit.keyboardShortcuts", "Keyboard Shortcuts…", "Cmd+Alt+Shift+K", "{}"),
(
"view.refreshMonitorProfile",
+3 -1
View File
@@ -78,7 +78,9 @@ log = { workspace = true }
# Floating panels open in OS windows of their own on the desktop; on the web they stay in the page.
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
# The folder picker and the updater are native only (`craft/Cargo.toml`: rfd and getrandom have no wasm build).
craft = { workspace = true, features = ["dialogs", "update"] }
# Agents in the open window (`src/agents.rs`): the ArtCraft Launcher's switch, the link host with its control
# server and the Agents page of Preferences (`automation-agents`), and the default agent folder (`control-agents`).
craft = { workspace = true, features = ["dialogs", "update", "automation-agents", "control-agents"] }
# The local date and time the status bar's Date and Time readout shows (`chrono::Local`). Already in
# Cargo.lock with the time-zone crates `clock` uses.
chrono = { workspace = true, features = ["clock"] }
+188
View File
@@ -0,0 +1,188 @@
//! Agents in the open window: while the ArtCraft Launcher's *Settings › AI agents* switch names
//! VectorCraft, the window serves its control channel to agents on loopback.
//!
//! The switch, the control server, its token and the connection file `vectorcraft-cli mcp` finds
//! the window by are the framework's (`craft::automation::agents::AgentSwitch` and `AgentLink`).
//! VectorCraft supplies its agent settings (saved by `prefs.agents`), answers the requests with its
//! own control methods ([`crate::control`]) and confines every file they open or save to the agent
//! folders: those set in Preferences › AI Integrations, or `Documents/ArtCraft/Agents/VectorCraft`
//! for an empty one. Without a folder of a kind, that kind of access is refused.
use std::path::PathBuf;
use std::sync::Arc;
use craft::automation::ControlChannel;
use craft::automation::agents::{AgentLink, AgentLinkStatus, AgentSettings, AgentSwitch, LinkProblem};
use craft::ui::runtime::windows::WindowHost;
use serde_json::{Value, json};
use vectorcraft_engine::file_access::{self, AutomationRoots};
use crate::VectorcraftApp;
/// The id the ArtCraft Launcher's app list names VectorCraft by (its catalog id).
pub const LAUNCHER_APP_ID: &str = "vectorcraft";
/// The app's name in messages and its default agent folder (`Documents/ArtCraft/Agents/VectorCraft`).
pub const APP_NAME: &str = "VectorCraft";
/// The Preferences page of the agent settings, and the key they sit under in its draft.
pub const PAGE: &str = "integrations";
/// The page's title in Preferences, as PhotoCraft names it.
pub const PAGE_TITLE: &str = "AI Integrations";
/// Saves the agent settings where `vectorcraft-cli mcp` reads them; `Err` says why it couldn't.
pub type SaveFn = Box<dyn Fn(&AgentSettings) -> Result<(), String>>;
/// The agents link of the open window.
pub struct Agents {
/// The link; `None` while the launch options (`--control`) manage the control channel.
link: Option<AgentLink>,
/// The status shown while the launch options manage the control channel.
launch: AgentLinkStatus,
switch: AgentSwitch,
settings: AgentSettings,
save: SaveFn,
default_folder: Option<PathBuf>,
}
impl Agents {
/// The link for the window, keeping its token and connection file in `settings_dir` and naming
/// `app` (the version string) in the connection file, following `switch` with the saved
/// `settings`; `save` stores the settings when `prefs.agents` changes them.
pub fn new(settings_dir: Option<PathBuf>, app: String, switch: AgentSwitch, settings: AgentSettings, save: SaveFn) -> Self {
Self {
link: Some(AgentLink::new(settings_dir, app)),
launch: AgentLinkStatus::default(),
switch,
settings,
save,
default_folder: craft::control::agents::default_folder(APP_NAME),
}
}
/// The window was started with `--control`, listening on `port` (none when it couldn't): that
/// channel serves the whole run, the link stays off and Preferences says the launch options
/// manage it.
pub fn launched_with_control(mut self, port: Option<u16>) -> Self {
self.link = None;
self.launch.port = port;
self.launch.launch_flags = true;
self
}
/// `default` replaces the default agent folder (tests).
pub fn with_default_folder(mut self, default: Option<PathBuf>) -> Self {
self.default_folder = default;
self
}
/// The saved agent settings.
pub fn settings(&self) -> &AgentSettings {
&self.settings
}
/// Where the link stands, for Preferences and `ui.inspect`.
pub fn status(&self) -> &AgentLinkStatus {
self.link.as_ref().map_or(&self.launch, AgentLink::status)
}
/// The suite's `AI-MCP` flag: the launcher's switch decides, and Preferences shows its state.
pub fn mcp_flag(&self) -> bool {
self.switch.mcp_flag()
}
/// Whether the launcher's switch lets agents use VectorCraft now.
pub fn allowed(&self) -> bool {
// VectorCraft had no agent consent of its own before the switch.
self.switch.allows(false)
}
/// Saves `settings`; the link applies them on the next pass.
fn set(&mut self, settings: AgentSettings) -> Result<(), String> {
(self.save)(&settings)?;
self.settings = settings;
Ok(())
}
}
/// What agent requests may open and save with `settings`: the agent folders (`default` for an empty
/// setting), or nothing. `Err` says why a folder can't be used.
fn roots_for(settings: &AgentSettings, default: Option<&std::path::Path>) -> Result<Arc<AutomationRoots>, String> {
let folders = settings.folders_with(default);
let read: Vec<&std::path::Path> = folders.read.as_deref().into_iter().collect();
let write: Vec<&std::path::Path> = folders.write.as_deref().into_iter().collect();
Ok(AutomationRoots::new(&read, &write)?.unwrap_or_else(AutomationRoots::none))
}
/// Once per pass: brings the link in line with the launcher's switch and the saved settings. The
/// control server starts, moves or stops; while it runs, its requests are the app's control channel
/// and run inside the agent folders ([`VectorcraftApp::run_control`]).
pub(crate) fn sync(app: &mut VectorcraftApp, ctx: &egui::Context) {
let Some(agents) = app.agents.as_mut() else { return };
let allowed = agents.allowed();
let Some(link) = agents.link.as_mut() else { return };
let update = link.sync(allowed.then_some(&agents.settings), &WindowHost::of(ctx));
if update.stopped {
app.channel = None;
app.deferred_control = None;
}
if let Some(requests) = update.requests {
app.channel = Some(ControlChannel::new(requests));
}
if !update.changed {
return;
}
app.automation_roots = Some(if link.status().port.is_none() {
AutomationRoots::none()
} else {
// Opened only when something changed: the default folder is created on the way.
roots_for(&agents.settings, agents.default_folder.as_deref()).unwrap_or_else(|e| {
link.note(LinkProblem::App(format!("Agents can't open or save files: {e}")));
AutomationRoots::none()
})
});
}
/// The keys `prefs.agents` takes.
const KEYS: [&str; 4] = ["controlPort", "readRoot", "writeRoot", "whenAppClosed"];
/// `prefs.agents`: the agent settings of Preferences › AI Integrations, the link's status and the
/// launcher's switch. `{controlPort?, readRoot?, writeRoot?, whenAppClosed?}` changes and saves those
/// settings first. Agents can't change them: their requests run confined to the agent folders, and
/// widening those is the person's choice.
pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let Some(agents) = app.agents.as_mut() else {
return Err("agents can't use this window: it keeps no preferences (VECTORCRAFT_NO_PREFS), or it is a nightly".into());
};
let given = p.as_object().filter(|o| !o.is_empty());
if let Some(given) = given {
if let Some(unknown) = given.keys().find(|k| !KEYS.contains(&k.as_str())) {
return Err(format!("unknown agent setting `{unknown}` ({})", KEYS.join(", ")));
}
if file_access::current().is_some() {
return Err("agents can't change the agent settings: the person sets them in Preferences › AI Integrations".into());
}
let mut next = serde_json::to_value(agents.settings()).map_err(|e| e.to_string())?;
if let Some(next) = next.as_object_mut() {
next.extend(given.clone());
}
let next: AgentSettings = serde_json::from_value(next).map_err(|e| format!("bad agent setting: {e}"))?;
if next.control_port > u32::from(u16::MAX) {
return Err(format!("controlPort must be 0 to {}, not {}", u16::MAX, next.control_port));
}
agents.set(next)?;
}
Ok(json!({"settings": agents.settings(), "status": agents.status(), "allowed": agents.allowed(), "mcpFlag": agents.mcp_flag()}))
}
/// The agent settings as Preferences shows them: under [`PAGE`] in its draft.
pub(crate) fn draft_value(app: &VectorcraftApp) -> Option<Value> {
serde_json::to_value(app.agents.as_ref()?.settings()).ok()
}
/// What Preferences' Agents page needs each pass: the link's status and the suite's `AI-MCP` flag.
pub(crate) fn page_state(app: &VectorcraftApp) -> Option<(AgentLinkStatus, bool)> {
let agents = app.agents.as_ref()?;
Some((agents.status().clone(), agents.mcp_flag()))
}
#[cfg(test)]
mod tests;
+135
View File
@@ -0,0 +1,135 @@
//! Agents in the open window: the link follows the launcher's switch, agent requests stay inside
//! the agent folders, and agents can't change the agent settings.
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use craft::automation::agents::{AgentSettings, AgentSwitch, CONNECTION_FILE, read_connection};
use craft::automation::client::ControlClient;
use serde_json::{Value, json};
use vectorcraft_engine::Session;
use vectorcraft_engine::file_access::{self, AutomationRoots};
use super::Agents;
use crate::{Services, VectorcraftApp};
/// A test's folder with `settings` (the app's settings folder), `in` (the read folder, with
/// `a.svg`), `out` (the write folder) and `outside` (with `b.svg`).
fn folders(tag: &str) -> PathBuf {
let base = std::env::temp_dir().join(format!("vc-ui-agents-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
for d in ["settings", "in", "out", "outside"] {
std::fs::create_dir_all(base.join(d)).unwrap();
}
let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="30"><rect width="20" height="10"/></svg>"#;
std::fs::write(base.join("in/a.svg"), svg).unwrap();
std::fs::write(base.join("outside/b.svg"), svg).unwrap();
base
}
fn s(p: PathBuf) -> String {
p.to_string_lossy().into_owned()
}
/// An app with the desktop's file services whose agents link follows `switch`, with `in` and `out`
/// as the agent folders; the settings it saves land in the returned list.
fn app_with_agents(base: &Path, switch: AgentSwitch) -> (VectorcraftApp, Arc<Mutex<Vec<AgentSettings>>>) {
let services = Services {
read: Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))),
write: Some(Box::new(|p: &str, b: &[u8]| vectorcraft_format::write_atomic(Path::new(p), b).map_err(|e| e.to_string()))),
..Default::default()
};
let mut settings = AgentSettings::default();
settings.read_root = s(base.join("in"));
settings.write_root = s(base.join("out"));
let saved = Arc::new(Mutex::new(Vec::new()));
let into = saved.clone();
let save: super::SaveFn = Box::new(move |settings| {
into.lock().unwrap().push(settings.clone());
Ok(())
});
let agents = Agents::new(Some(base.join("settings")), "VectorCraft test".into(), switch, settings, save).with_default_folder(None);
let app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services).with_agents(agents));
(app, saved)
}
/// One request from an agent's client through the link's server, answered by the app's frames: the client
/// thread hands its reply back over a channel, and the app runs a pass while it waits.
fn agent_request(app: &mut VectorcraftApp, client: &mut Option<ControlClient>, method: &str, params: Value) -> Result<Value, String> {
let ctx = app.ui_ctx.clone().unwrap_or_default();
let mut c = client.take().expect("a connected client");
let sent = method.to_owned();
let (done, reply) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let r = c.call(&sent, params);
let _ = done.send((c, r));
});
for _ in 0..2000 {
app.run_control(&ctx);
app.poll_input(&ctx);
if let Ok((c, r)) = reply.recv_timeout(std::time::Duration::from_millis(5)) {
*client = Some(c);
return r;
}
}
panic!("the app did not answer {method:?}")
}
// With the launcher's switch naming VectorCraft, the window serves agents on loopback and publishes
// where; their requests open and save only inside the agent folders, while the person is not confined.
#[test]
fn agents_reach_the_window_only_inside_the_agent_folders() {
let base = folders("on");
let (mut app, _) = app_with_agents(&base, AgentSwitch::fixed(true, true));
let ctx = app.ui_ctx.clone().unwrap_or_default();
super::sync(&mut app, &ctx);
let port = app.agents.as_ref().and_then(|a| a.status().port).expect("the link listens while the switch allows it");
let connection = read_connection(&base.join("settings")).unwrap().expect("the connection file is published");
assert_eq!(connection.port, port);
let token = std::fs::read_to_string(&connection.token_file).unwrap();
let mut client = Some(ControlClient::connect(([127, 0, 0, 1], port).into(), token.trim()).unwrap());
let inside = agent_request(&mut app, &mut client, "app.open", json!({"path": s(base.join("in/a.svg"))}));
assert!(inside.is_ok(), "{inside:?}");
let outside = agent_request(&mut app, &mut client, "app.open", json!({"path": s(base.join("outside/b.svg"))}));
assert!(outside.as_ref().is_err_and(|e| e.contains("outside the read root")), "{outside:?}");
let saved = agent_request(&mut app, &mut client, "app.export", json!({"path": s(base.join("outside/a.png")), "format": "png"}));
assert!(saved.as_ref().is_err_and(|e| e.contains("outside the write root")), "{saved:?}");
assert!(!base.join("outside/a.png").exists());
// The person at the keyboard opens what they like.
assert!(app.run("file.open", json!({"path": s(base.join("outside/b.svg"))})).is_ok());
let _ = std::fs::remove_dir_all(&base);
}
// With the switch off, nothing listens and no connection file is published.
#[test]
fn with_the_switch_off_nothing_listens() {
let base = folders("off");
let (mut app, _) = app_with_agents(&base, AgentSwitch::fixed(true, false));
let ctx = app.ui_ctx.clone().unwrap_or_default();
super::sync(&mut app, &ctx);
assert!(app.channel.is_none());
assert_eq!(app.agents.as_ref().and_then(|a| a.status().port), None);
assert!(!base.join("settings").join(CONNECTION_FILE).exists());
let _ = std::fs::remove_dir_all(&base);
}
// `prefs.agents` saves the person's settings, refuses unknown keys, and refuses every change from a
// confined request: agents can't widen their own folders.
#[test]
fn prefs_agents_saves_and_agents_cannot_change_it() {
let base = folders("prefs");
let (mut app, saved) = app_with_agents(&base, AgentSwitch::fixed(true, false));
let r = app.run("prefs.agents", json!({"whenAppClosed": "headless"})).unwrap();
assert_eq!(r["settings"]["whenAppClosed"], "headless");
assert_eq!(saved.lock().unwrap().len(), 1);
assert!(app.run("prefs.agents", json!({"port": 7})).is_err());
assert!(app.run("prefs.agents", json!({"controlPort": 70000})).is_err());
let roots = AutomationRoots::new(&[&base.join("in")], &[&base.join("out")]).unwrap().unwrap();
let widened = file_access::confine(Some(&roots), || app.run("prefs.agents", json!({"readRoot": s(base.clone())})));
assert!(widened.is_err_and(|e| e.contains("can't change the agent settings")));
assert_eq!(saved.lock().unwrap().len(), 1, "nothing more was saved");
// Reading them is fine.
assert!(file_access::confine(Some(&roots), || app.run("prefs.agents", json!({}))).is_ok());
let _ = std::fs::remove_dir_all(&base);
}
+20 -1
View File
@@ -286,6 +286,8 @@ impl VectorcraftApp {
prefs_changed: false,
touch_screen: false,
automation_roots: None,
#[cfg(not(target_arch = "wasm32"))]
agents: None,
pending_plugin_install: None,
pending_profile_open: None,
queued_profile_opens: Default::default(),
@@ -315,6 +317,22 @@ impl VectorcraftApp {
pub fn with_automation_roots(mut self, roots: Option<Arc<AutomationRoots>>) -> Self {
let Some(roots) = roots else { return self };
self.automation_roots = Some(roots);
self.check_file_services();
self
}
/// Lets agents into this window while the ArtCraft Launcher's switch names VectorCraft
/// ([`crate::agents`]): their requests, the input they inject and the saves they start read and
/// write only inside the agent folders, as with [`Self::with_automation_roots`].
#[cfg(not(target_arch = "wasm32"))]
pub fn with_agents(mut self, agents: crate::agents::Agents) -> Self {
self.agents = Some(Box::new(agents));
self.check_file_services();
self
}
/// Has the host's file services check every path against the roots in force ([`file_access`]).
fn check_file_services(&mut self) {
let s = &mut self.services;
if let Some(read) = s.read.take() {
s.read = Some(Box::new(move |p: &str| file_access::check_read(p).and_then(|()| read(p))));
@@ -339,7 +357,6 @@ impl VectorcraftApp {
*service = Some(Box::new(move |p: &str| file_access::check_read(p).and_then(|()| open(p))));
}
}
self
}
/// The folders this pass may read and write: the automation roots while the pass carries
@@ -632,6 +649,8 @@ impl VectorcraftApp {
}
crate::keymap::note_os(ctx);
prefs_dialog::apply_runtime(self, ctx);
#[cfg(not(target_arch = "wasm32"))]
crate::agents::sync(self, ctx);
self.run_control(ctx);
// Plug-ins loading on other threads since launch install as their loads finish; until then
// the host keeps coming back to look again, and once more when the last one installs, for
+6
View File
@@ -24,6 +24,9 @@ macro_rules! tl {
}
pub mod addons;
/// Agents in the open window through the ArtCraft Launcher's switch (desktop).
#[cfg(not(target_arch = "wasm32"))]
pub mod agents;
pub mod background;
mod brand;
pub mod canvas;
@@ -343,6 +346,9 @@ pub struct VectorcraftApp {
/// (`--automation-read-root`, `--automation-write-root`); `None`: anywhere. See
/// [`Self::with_automation_roots`].
automation_roots: Option<Arc<AutomationRoots>>,
/// The agents link while the ArtCraft Launcher's switch may let agents in ([`Self::with_agents`]).
#[cfg(not(target_arch = "wasm32"))]
pub(crate) agents: Option<Box<agents::Agents>>,
/// The plug-in install the approval dialog asks about, kept out of the dialog's fields, which
/// `ui.dialog.set` writes.
pub(crate) pending_plugin_install: Option<dialogs::plugin::PendingInstall>,
+4
View File
@@ -299,6 +299,10 @@ fn run_ui_part2(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result<
crate::prefs_dialog::open(app, s("category").as_deref());
Ok(Value::Null)
}
#[cfg(not(target_arch = "wasm32"))]
"prefs.agents" => crate::agents::command(app, p),
#[cfg(target_arch = "wasm32")]
"prefs.agents" => Err("agents in the open window need the desktop app".into()),
// Edit → Color Settings… / Assign Profile… (no params): show the colour-management panel
// wherever it is, as Window › Separations Preview does (it isn't in an icon column, so a
// flyout for it never opened: #4542), scrolled to its Color Settings section, which a short
+6
View File
@@ -172,6 +172,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
),
("app.home", "Home", "", "{} shows the Home screen (new file presets, Open) over the open documents; choosing a document tab returns to it"),
("edit.preferences", "Preferences…", "Cmd+K", "{category?} open Preferences (engine: prefs.get / prefs.set / prefs.list)"),
(
"prefs.agents",
"AI Integrations",
"",
"{controlPort?: 0–65535, readRoot?: string, writeRoot?: string, whenAppClosed?: launch|headless|error} the agent settings of Preferences › AI Integrations (agents in the open window through the ArtCraft Launcher's switch); given keys are saved where vectorcraft-cli mcp reads them, refused from an agent's request → {settings, status: {port, launchFlags, error}, allowed, mcpFlag}; an error in the web build and in a run without preferences",
),
("edit.keyboardShortcuts", "Keyboard Shortcuts…", "Cmd+Alt+Shift+K", "{}"),
(
"view.refreshMonitorProfile",
+31 -3
View File
@@ -173,6 +173,30 @@ impl PrefsWindow {
}
}
/// The English names of the window's pages: the preference categories, then AI Integrations where agents may use the
/// window (the desktop app with preferences).
fn categories(app: &VectorcraftApp) -> impl Iterator<Item = &'static str> {
#[cfg(not(target_arch = "wasm32"))]
let agents = app.agents.is_some().then_some(crate::agents::PAGE_TITLE);
#[cfg(target_arch = "wasm32")]
let agents = {
let _ = app;
None
};
PREF_CATEGORIES.iter().copied().chain(agents)
}
/// The agent settings as the AI Integrations page edits them; `None` where the window has no such page.
fn agent_settings(app: &VectorcraftApp) -> Option<Value> {
#[cfg(not(target_arch = "wasm32"))]
return crate::agents::draft_value(app);
#[cfg(target_arch = "wasm32")]
{
let _ = app;
None
}
}
/// Whether `key` is a row of the window: a UI-only field, a preference or a preference group.
fn is_known(key: &str) -> bool {
UI_FIELDS.iter().any(|f| f.0 == key) || spec(key).is_some() || PREF_GROUPS.contains(&key)
@@ -203,7 +227,10 @@ pub fn open(app: &mut VectorcraftApp, category: Option<&str>) {
draft.set("__smartGuides", &app.ui.view.smart_guides);
draft.set("__snapToGrid", &app.ui.view.snap_to_grid);
draft.set("__taskBar", &app.ui.task_bar);
let selected = category.and_then(|c| PREF_CATEGORIES.iter().find(|x| x.eq_ignore_ascii_case(c))).copied().unwrap_or(PREF_CATEGORIES[0]);
if let Some(agents) = agent_settings(app) {
draft.set(model::AGENTS_KEY, &agents);
}
let selected = category.and_then(|c| categories(app).find(|x| x.eq_ignore_ascii_case(c))).unwrap_or(PREF_CATEGORIES[0]);
// The saved delay, so OK writes the delay in use in its place.
let mut source = draft.clone();
if let Some(saved) = &saved_delay {
@@ -298,11 +325,12 @@ pub(crate) fn fields(app: &VectorcraftApp) -> Option<Map<String, Value>> {
/// Sets one field as the user editing it would (`ui.dialog.set`). `Err` while the window is closed, for an unknown
/// key or a value of the wrong kind.
pub(crate) fn set_field(app: &mut VectorcraftApp, key: &str, value: Value) -> Result<(), String> {
let category = (key == "__category").then(|| value.as_str().map(|name| (name, categories(app).find(|c| c.eq_ignore_ascii_case(name)))));
let w = app.prefs.as_mut().ok_or("no dialog open")?;
match key {
"__category" => {
let name = value.as_str().ok_or("`__category` takes text")?;
let category = PREF_CATEGORIES.iter().find(|c| c.eq_ignore_ascii_case(name)).ok_or_else(|| format!("no category `{name}`"))?;
let (name, category) = category.flatten().ok_or("`__category` takes text")?;
let category = category.ok_or_else(|| format!("no category `{name}`"))?;
w.state.selected = category.to_string();
Ok(())
}
+64 -5
View File
@@ -33,6 +33,28 @@ pub(super) const WARNING_DIALOGS: &[&str] = &["showExternalScriptWarning"];
/// The row key of the Reset All Warning Dialogs button.
const RESET_WARNINGS_KEY: &str = "resetWarningDialogs";
/// The draft key of the agent settings of Preferences › AI Integrations (`prefs.agents`).
pub(super) const AGENTS_KEY: &str = "integrations";
/// Preferences › AI Integrations: with the suite's `AI-MCP` flag, the framework's Agents page over the agent settings
/// in the draft (the ArtCraft Launcher's switch decides; the page has none of its own); without it, a line that says
/// so, as VectorCraft had no agent settings before the switch. Returns whether the draft changed.
#[cfg(not(target_arch = "wasm32"))]
fn agents_page(live: &mut Live<'_>, ui: &mut egui::Ui) -> bool {
use craft::ui::contract::Show as _;
use craft::ui::display::{Shade, Text};
let Some((status, mcp_flag)) = crate::agents::page_state(live.app) else { return false };
if !mcp_flag {
Text::new(tl!(
"Agents use VectorCraft without a window. The ArtCraft Launcher's Settings › AI agents switch lets them into the open window once the suite's AI-MCP flag is on."
))
.shade(Shade::Muted)
.show(ui);
return false;
}
craft::automation::ui::agents::AgentsPage::new(AGENTS_KEY, &mut live.w.draft, &status).mcp_flag(true).show(ui).changed
}
/// Turns the warning preferences `keys` back on in the draft, as Reset All Warning Dialogs does; OK or Apply writes
/// them.
pub(super) fn reset_warning_dialogs(w: &mut PrefsWindow, keys: &[&str]) {
@@ -358,7 +380,15 @@ impl Live<'_> {
impl PreferencesModel for Live<'_> {
fn pages(&self) -> Vec<PageSpec<'_>> {
PREF_CATEGORIES.iter().map(|&cat| self.page(cat)).collect()
let pages = PREF_CATEGORIES.iter().map(|&cat| self.page(cat));
// The agent settings, drawn whole by the framework's Agents page, on the desktop.
#[cfg(not(target_arch = "wasm32"))]
let pages = pages.chain(self.app.agents.is_some().then(|| {
use crate::agents::PAGE_TITLE;
let keywords = "agents AI MCP ArtCraft Launcher control port folders";
PageSpec::custom(PAGE_TITLE, tl!(PAGE_TITLE)).keywords(keywords).resettable(false)
}));
pages.collect()
}
fn set(&mut self, key: &str, value: PrefValue) {
@@ -429,7 +459,12 @@ impl PreferencesModel for Live<'_> {
}
}
fn custom_page(&mut self, _ui: &mut egui::Ui, _page: &str) -> bool {
fn custom_page(&mut self, ui: &mut egui::Ui, page: &str) -> bool {
#[cfg(not(target_arch = "wasm32"))]
if page == crate::agents::PAGE_TITLE {
return agents_page(self, ui);
}
let _ = (ui, page);
false
}
@@ -478,12 +513,33 @@ impl PreferencesDraft for Live<'_> {
|| current.get(k).and_then(Value::as_f64) == self.w.source.get::<Value>(k).as_ref().and_then(Value::as_f64))
})
.collect();
let values: Map<String, Value> = edited.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect();
let values: Map<String, Value> =
edited.iter().filter(|(k, _)| !k.starts_with("__") && *k != AGENTS_KEY).map(|(k, v)| (k.clone(), v.clone())).collect();
let touch_ws = values.get("touchWorkspace").and_then(Value::as_bool);
let document_units = self.w.reset_units.as_deref().is_none_or(|u| values.get("unitsGeneral").and_then(Value::as_str) != Some(u));
// The agent settings are saved where `vectorcraft-cli mcp` reads them, not with the preferences: only the
// fields changed in the window, so one `prefs.agents` changed while it is open keeps its new value. First,
// so a refused agent setting leaves the preferences unapplied too.
if let Some(agents) = edited.get(AGENTS_KEY).and_then(Value::as_object) {
let read = self.w.source.get::<Map<String, Value>>(AGENTS_KEY).unwrap_or_default();
let given: Map<String, Value> =
agents.iter().filter(|(k, v)| *k != "allowAgentControl" && read.get(*k) != Some(*v)).map(|(k, v)| (k.clone(), v.clone())).collect();
if !given.is_empty() {
self.app.run("prefs.agents", Value::Object(given))?;
}
}
// A refused folder, typed or picked, comes back here as the engine's message.
if !values.is_empty() {
self.app.run("prefs.set", json!({ "values": values, "documentUnits": document_units }))?;
if !values.is_empty()
&& let Err(e) = self.app.run("prefs.set", json!({ "values": values, "documentUnits": document_units }))
{
// The agent settings were saved: the window shows them as saved (its own edits among them, a change made
// outside it kept), and Apply doesn't send them again.
if let Some(agents) = super::agent_settings(self.app) {
self.w.draft.set(AGENTS_KEY, &agents);
self.w.source.set(AGENTS_KEY, &agents);
self.w.opened.set(AGENTS_KEY, &agents);
}
return Err(e);
}
let row = |key: &str| edited.get(key).and_then(Value::as_bool);
// When OK enters the Touch workspace, the task bar is set before the switch, so it goes to the workspace being
@@ -524,6 +580,9 @@ impl PreferencesDraft for Live<'_> {
self.w.draft.set("__smartGuides", &self.app.ui.view.smart_guides);
self.w.draft.set("__snapToGrid", &self.app.ui.view.snap_to_grid);
self.w.draft.set("__taskBar", &self.app.ui.task_bar);
if let Some(agents) = super::agent_settings(self.app) {
self.w.draft.set(AGENTS_KEY, &agents);
}
self.w.opened = self.w.draft.clone();
self.w.source = self.w.draft.clone();
self.w.touched.clear();
+51
View File
@@ -1589,3 +1589,54 @@ fn reset_all_warning_dialogs_turns_a_dismissed_warning_back_on() {
click_reset_warnings(&mut a);
assert!(!a.prefs.as_ref().unwrap().touched.contains("showExternalScriptWarning"), "a dimmed button changes nothing");
}
/// Preferences › AI Integrations (desktop): the page is there while the window has an agents link, it opens by
/// name, and OK saves an edited agent setting through `prefs.agents` instead of `prefs.set`.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn ai_integrations_page_saves_the_agent_settings_on_ok() {
use craft::automation::agents::{AgentSettings, AgentSwitch};
use std::sync::{Arc, Mutex};
let saved: Arc<Mutex<Vec<AgentSettings>>> = Arc::default();
let into = saved.clone();
let save: crate::agents::SaveFn = Box::new(move |s| {
into.lock().unwrap().push(s.clone());
Ok(())
});
let agents = crate::agents::Agents::new(None, "VectorCraft test".into(), AgentSwitch::fixed(true, false), AgentSettings::default(), save)
.with_default_folder(None);
let mut a = app().with_agents(agents);
open(&mut a, Some("ai integrations"));
assert_eq!(page(&a), Some(crate::agents::PAGE_TITLE));
assert!(with_pages(&mut a, |pages| pages.iter().any(|p| p.id == crate::agents::PAGE_TITLE && p.custom)));
a.prefs.as_mut().unwrap().draft.set("integrations.whenAppClosed", &"error");
confirm(&mut a).unwrap();
let saved = saved.lock().unwrap();
assert_eq!(saved.len(), 1);
assert_eq!(saved[0].when_app_closed, craft::automation::agents::WhenAppClosed::Error);
}
/// OK sends only the agent settings changed in the window: one changed through `prefs.agents` while Preferences is
/// open keeps its new value.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn ok_keeps_an_agent_setting_changed_while_preferences_is_open() {
use craft::automation::agents::{AgentSettings, AgentSwitch};
use std::sync::{Arc, Mutex};
let saved: Arc<Mutex<Vec<AgentSettings>>> = Arc::default();
let into = saved.clone();
let save: crate::agents::SaveFn = Box::new(move |s| {
into.lock().unwrap().push(s.clone());
Ok(())
});
let agents = crate::agents::Agents::new(None, "VectorCraft test".into(), AgentSwitch::fixed(true, false), AgentSettings::default(), save)
.with_default_folder(None);
let mut a = app().with_agents(agents);
open(&mut a, Some(crate::agents::PAGE_TITLE));
a.run("prefs.agents", json!({"readRoot": "/elsewhere"})).unwrap();
a.prefs.as_mut().unwrap().draft.set("integrations.whenAppClosed", &"error");
confirm(&mut a).unwrap();
let last = saved.lock().unwrap().last().cloned().unwrap();
assert_eq!(last.read_root, "/elsewhere", "the window did not send back the folder it opened with");
assert_eq!(last.when_app_closed, craft::automation::agents::WhenAppClosed::Error);
}
+13 -1
View File
@@ -1,6 +1,6 @@
# Control protocol
> **Last updated:** 2026-11-19 · **Change:** #5804 native-picked raster editor merged with main; scores and estimates unchanged; previously: completed the `ui.resize` and `ui.focus` entries and removed a duplicate `ui.render` row; previously: text style commands take a feature with a value (`"features": ["salt=2"]`), the font's alternate number, and shape runs that differ only in features as one piece of text; previously: Confining file access refuses a `:` in a name after the drive on Windows, an NTFS alternate data stream such as `x.svg:evil` (#3604); previously: Object → Expand… dimmed while the selection has an appearance Expand Appearance expands (`object.expand.info`'s `appearance`, #3089); previously: brush library panels (`window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary`); previously: Transform Each opens on the values it was last confirmed with; its Copy button confirms with `copy: true` (#1732); previously: panel docking on craft-ui's layout: `ui.docking`, the parameters of `window.panel.float` and `window.panel.dock`; previously: `ui.screenshot`'s 64 MiB inline-PNG cap and its path-plus-data downgrade; symbol library panels (`window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary`); synthetic input budgets (#1709); bounded transport waits (#1726).
> **Last updated:** 2026-12-03 · **Change:** the window serves agents while the ArtCraft Launcher's AI agents switch names VectorCraft ([Agents in the open window](#agents-in-the-open-window)); previously: #5804 native-picked raster editor merged with main; scores and estimates unchanged; previously: completed the `ui.resize` and `ui.focus` entries and removed a duplicate `ui.render` row; previously: text style commands take a feature with a value (`"features": ["salt=2"]`), the font's alternate number, and shape runs that differ only in features as one piece of text; previously: Confining file access refuses a `:` in a name after the drive on Windows, an NTFS alternate data stream such as `x.svg:evil` (#3604); previously: Object → Expand… dimmed while the selection has an appearance Expand Appearance expands (`object.expand.info`'s `appearance`, #3089); previously: brush library panels (`window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary`); previously: Transform Each opens on the values it was last confirmed with; its Copy button confirms with `copy: true` (#1732); previously: panel docking on craft-ui's layout: `ui.docking`, the parameters of `window.panel.float` and `window.panel.dock`; previously: `ui.screenshot`'s 64 MiB inline-PNG cap and its path-plus-data downgrade; symbol library panels (`window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary`); synthetic input budgets (#1709); bounded transport waits (#1726).
`vectorcraft --control <port>` listens on `127.0.0.1:<port>` (loopback only). The port must be a number
from 1 to 65535 (`--control=<port>` works too), given once; otherwise the app prints an error and exits
@@ -33,6 +33,18 @@ persistent clients can send further requests within these bounds, or reconnect a
These transport budgets are separate from the existing 60-second command-processing wait.
Transport: `apps/vectorcraft/src/control_server.rs`.
## Agents in the open window
While the ArtCraft Launcher's *Settings › AI agents* switch names VectorCraft, the window serves this protocol
without `--control`, on a loopback port of its own (*Edit › Preferences › AI Integrations › Control Port*; 0
picks a free one), and publishes the port, its process id and the token file in `agent-connection.json` in
the settings folder. It stops and removes the file when the switch turns off. Each connection must
authenticate before anything else is answered, with the token in `agent-control.token` there (readable by
the user only): `auth.challenge {clientNonce}` and then `auth {proof}`, which `vectorcraft-cli mcp` uses so the
token never crosses the wire, or `auth {token}`. Every request on it runs inside the agent folders of
Preferences › AI Integrations, as with `--automation-read-root` and `--automation-write-root`, and
`prefs.agents` refuses to change them from there. See [Agents in the open window](mcp.md#agents-in-the-open-window).
## Synthetic input budgets
`ui.drag` accepts at most **256** `steps`; `ui.click` and `ui.drag` accept at most **16** `count`.
+53 -30
View File
@@ -1,6 +1,6 @@
# VectorCraft MCP server
> **Last updated:** 2026-11-27 · **Change:** Anchor Inspector: canceled Corner and Shared Edge option edits restore their opening values; previously: Production Preflight command and report coverage; previously: `text.setFormat {composer}` and paragraph styles also take `standardSingleLine` and `standardEveryLine` (#4935); existing values and responses unchanged. Previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; no response-shape change. Previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; no response-shape change. Previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; no response-shape change. Previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter (#7097); existing response shapes retained.
> **Last updated:** 2026-12-03 · **Change:** plain `vectorcraft-cli mcp` finds the open window through the ArtCraft Launcher's AI agents switch (no port or token to configure), `--when-closed`, the `agent_folders` tool, Preferences › AI Integrations and `prefs.agents`; `--connect` is deprecated. Previously: Anchor Inspector: canceled Corner and Shared Edge option edits restore their opening values; previously: Production Preflight command and report coverage; previously: `text.setFormat {composer}` and paragraph styles also take `standardSingleLine` and `standardEveryLine` (#4935); existing values and responses unchanged. Previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; no response-shape change. Previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; no response-shape change. Previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; no response-shape change. Previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter (#7097); existing response shapes retained.
>
> Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5).
@@ -8,21 +8,53 @@
(newline-delimited JSON-RPC 2.0; see [Protocol](#protocol) for version negotiation). Agents use it to
draw, inspect and look at VectorCraft documents.
It has two backends:
It has three ways to run:
| Mode | How | What works |
|---|---|---|
| **Remote** | `vectorcraft-cli mcp --connect 127.0.0.1:7979` (the app must run with `vectorcraft --control 7979`) | Everything. Tool calls are forwarded over the [control protocol](control-protocol.md), so you watch the app change live. |
| **Headless** | `vectorcraft-cli mcp --headless` | An in-process engine session with a CPU renderer. Everything except the UI-only tools (`inspect_ui` or `ui_inspect`, `type_text`, `answer_dialog`, `open_panel`, `screenshot {window:true}` or `ui_screenshot`). |
| **Open window** | `vectorcraft-cli mcp` while the ArtCraft Launcher's *Settings › AI agents* switch lets agents use VectorCraft (see [Agents in the open window](#agents-in-the-open-window)); `--automation-read-root` or `--automation-write-root` make it headless instead | Everything. Each tool call goes to the open VectorCraft window, so you watch the app change live. |
| **Headless** | `vectorcraft-cli mcp --headless` or with automation roots, or plain `mcp` while agents may not use the open window | An in-process engine session with a CPU renderer. Everything except the UI-only tools (`inspect_ui` or `ui_inspect`, `type_text`, `answer_dialog`, `open_panel`, `screenshot {window:true}` or `ui_screenshot`). |
| **Remote** (deprecated) | `vectorcraft-cli mcp --connect 127.0.0.1:7979` (the app must run with `vectorcraft --control 7979` and `VECTORCRAFT_CONTROL_TOKEN`) | Everything, over the [control protocol](control-protocol.md). `--connect` prints a deprecation line and goes away in a later release. |
With no flag, the server tries `127.0.0.1:7979` and falls back to headless. Logs go to stderr; stdout carries
only protocol messages.
Logs go to stderr; stdout carries only protocol messages.
## Agents in the open window
One switch serves every Craft app: the ArtCraft Launcher's *Settings › AI agents › Let AI agents use Craft
apps* (behind the suite's `AI-MCP` flag). The launcher also adds one `ArtCraft` entry to the MCP clients it
knows; VectorCraft writes no client configuration of its own.
While the switch names VectorCraft, the open window serves its control channel on loopback and publishes
`agent-connection.json` (port, process id, token file) in its settings folder; the token stays in
`agent-control.token` there, readable by the user only. Plain `vectorcraft-cli mcp` reads that file before every tool
call and authenticates with the challenge handshake (the window proves it holds the token first; the token
itself never crosses the wire). So no port or token goes into a client's configuration, the app may be
opened after the MCP session started, and it may quit or restart while the session goes on. When the switch
turns off, the window stops listening and removes the file.
Every file an agent's request opens or saves in the window stays inside the agent folders: those set in
*Edit › Preferences › AI Integrations*, or `Documents/ArtCraft/Agents/VectorCraft` when none is set (made when
first used). A request outside them is refused, as with `--automation-read-root`. The person at the keyboard
is not confined. The `agent_folders` tool tells the agent which folders it may use.
While agents may use VectorCraft but it is closed, Preferences › AI Integrations chooses what plain `mcp`
does: open VectorCraft and wait for it (the default), run the call in a session without a window confined to
the agent folders, or answer with an error that asks to open VectorCraft. `--when-closed
launch|headless|error` overrides the choice for one server. A session that went headless stays headless, so
documents don't move under the agent. While agents may not use VectorCraft, plain `mcp` runs headless with
only the folders given on its command line, as before.
Preferences › AI Integrations shows the switch's state, the port agents connect on, Control Port (0: any free
port), the two folders and the closed-app choice. Without the `AI-MCP` flag it only says that agents use
VectorCraft without a window. The same settings are the UI command `prefs.agents {controlPort?, readRoot?,
writeRoot?, whenAppClosed?}`, which agents' own requests can read but not change. Started with `--control`,
the window serves that channel for the whole run instead, and the page says so.
### Command catalogue (headless vs remote)
`command_list` / `list_commands` / `vectorcraft://commands` return the live catalogue for the backend in use:
- **Headless:** engine and plug-in commands, plus the desktop menu catalogue (`UI_COMMANDS`) marked `"ui": true` so agents can discover ids such as `view.fitArtboard`, `file.newDialog` and `window.*`. Running a UI-only command that the headless host does not implement returns an error that points at `--connect`.
- **Headless:** engine and plug-in commands, plus the desktop menu catalogue (`UI_COMMANDS`) marked `"ui": true` so agents can discover ids such as `view.fitArtboard`, `file.newDialog` and `window.*`. Running a UI-only command that the headless host does not implement returns an error that asks for the open window.
The catalogue is mirrored in `crates/mcp/src/ui_catalog.rs` (mcp does not depend on ui-egui). Regenerate with `cargo xtask ui-commands`; `cargo xtask ci` runs `ui-commands --check` so the mirror cannot drift.
- **Remote:** the same lists, with each UI entry's `enabled` taken from the live app. Run UI commands with `command_run` / `run_command` or `invoke_menu`.
@@ -40,11 +72,13 @@ cargo install --path apps/vectorcraft-cli --locked
export PATH="${CARGO_HOME:-$HOME/.cargo}/bin:$PATH"
vectorcraft-cli --help
claude mcp add vectorcraft -- vectorcraft-cli mcp
# or pin a mode:
# or always without a window:
claude mcp add vectorcraft-headless -- vectorcraft-cli mcp --headless
claude mcp add vectorcraft-app -- vectorcraft-cli mcp --connect 127.0.0.1:7979
```
With the ArtCraft Launcher, its AI agents switch adds the `ArtCraft` entry for you, and these commands are only
needed for a build of your own.
Cargo installs a binary, not a symlink into `target/`, so it survives `cargo clean`.
Re-run the install command after updating the checkout.
By default the executable goes in `$CARGO_HOME/bin` (`~/.cargo/bin` when unset), or
@@ -66,7 +100,7 @@ installed binary path, not a literal `~` or `$HOME` expression. Avoid symlinks i
`target/release`: cleaning the build directory breaks them. A source build alone does
not put the CLI on `PATH`.
For a live session, start the app first: `cargo run --release -p vectorcraft -- --control 7979`.
For a live session, turn on the launcher's AI agents switch (for a build of your own, set the `AI-MCP` flag and name `vectorcraft` in the launcher's app list) and open the app: `cargo run --release -p vectorcraft`.
### From an installed release
@@ -76,33 +110,21 @@ The release packages ship `vectorcraft-cli` alongside the desktop app, so no bui
|---|---|
| Windows (MSI) | `%LOCALAPPDATA%\Programs\ArtCraft\VectorCraft\vectorcraft-cli.exe` by default (`C:\Program Files\ArtCraft\VectorCraft\vectorcraft-cli.exe` for an all-users install, under `Program Files (x86)` instead for the 32-bit build, or wherever you installed it otherwise), not on `PATH` |
| Linux (deb, rpm) | `/usr/bin/vectorcraft-cli` |
| macOS | the separate `vectorcraft-cli-<version>-macos-<arch>.zip` release asset (the `.app` holds only the desktop app) |
| macOS | `VectorCraft.app/Contents/MacOS/vectorcraft-cli`, beside the app, where the ArtCraft Launcher finds it (`/Applications/VectorCraft.app` by default), or the separate `vectorcraft-cli-<version>-macos-<arch>.zip` release asset |
```sh
# Windows (PowerShell), default install folder
claude mcp add vectorcraft -- "$env:LOCALAPPDATA\Programs\ArtCraft\VectorCraft\vectorcraft-cli.exe" mcp
# macOS, VectorCraft in /Applications (the default; put your own path to VectorCraft.app otherwise)
claude mcp add vectorcraft -- "/Applications/VectorCraft.app/Contents/MacOS/vectorcraft-cli" mcp
# Linux, or macOS with the CLI unzipped onto PATH
claude mcp add vectorcraft -- vectorcraft-cli mcp
```
For a live session, start the installed app with the control port before the MCP client starts the server:
```sh
# macOS: quit VectorCraft first, since `open -a` passes no arguments to an app that is already running
open -a VectorCraft --args --control 7979
# Windows (PowerShell), default install folder
& "$env:LOCALAPPDATA\Programs\ArtCraft\VectorCraft\vectorcraft.exe" --control 7979
# Linux (deb, rpm)
vectorcraft --control 7979
```
The Dock, Start menu and desktop launchers start the app without `--control`, so the app opens no control
port unless `VECTORCRAFT_CONTROL_PORT` is set. `vectorcraft-cli mcp` with no flag tries `127.0.0.1:7979`
once, when it starts: a server that started before the app stays headless until the MCP client restarts
it. `open -a` and PowerShell's `&` return before the app opens the port, so wait until the VectorCraft
window is open before you start the MCP client. With `--connect`, a server that finds no app stops and
prints `vectorcraft-cli: cannot connect to 127.0.0.1:7979: ` followed by the system's connection error, for
example `connection timed out`.
For a live session, turn on *Settings › AI agents* in the ArtCraft Launcher and open VectorCraft as usual (Dock,
Start menu, desktop launcher). The server finds the window whenever it opens, unless the session already went headless
(a call made while VectorCraft was closed, with the headless closed-app choice); such a session needs a new
MCP session to use the window. See [Agents in the open window](#agents-in-the-open-window).
## Confining file access
@@ -832,6 +854,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions
| `create_graph` | `{type?, x, y, width, height, csv? \| series?, categories?, rows?}` | The nine Illustrator graph types: column, stacked column, bar, stacked bar, line, area, scatter, pie and radar. An empty CSV cell or a `null` in `rows` is a blank value; a number in straight quotes is a label. Edit later with `graph.setData` / `graph.setType` via `run_command`. `graph.column {design, columnType: vertical\|uniform\|repeating\|sliding, each, fractions: chop\|scale}` draws the columns or bars of the series picked with Group Selection (or `seriesIndexes`, or all of them) with a graph design saved by `graph.design`; with no `design` it returns the series' current design and options. Type in the design that holds a `%` followed by two digits shows each column's value, with at least the first digit's places before the decimal point and the second digit's places after it. |
| `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. A type object in `ids` with another of them above it in its layer is the text to wrap, not a wrap object, so the objects and the type can be selected together. The reply has a `warning` when no area type lies below any of the wrap objects. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. |
| `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy`, `path.moveAnchors` by 0, `layer.setProps` with every row already as given and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. Any other command that changes the document during a tool's drag, from `run_command`, a panel or a menu, records its own undo step before the drag's. The command acts on the document without the drag's preview, and the drag then continues from the command's result: with Real-time Drawing on, the drag's preview is applied again at once, and with it off, the release applies it as before. The release records the drag's step after the command's, `undo` takes back the drag first and the command next, and Escape cancels only the drag. The drag acts on the objects it started with, so a selection the command makes (`select.all`, `edit.duplicate`) does not change what the drag moves, and the drag's release and Escape set the selection as they do without the command (with Real-time Drawing on, so does each move of the drag); a command that records no undo step, such as `select.none`, adds no step. When the command deletes or changes the art being dragged, the drag continues with the art the command left, and a drag left with nothing to change records no step. A warning or an error from the drag's preview applied again after the command is in the command's result as `previewWarning`. Typing in progress is kept as a step of its own before the command. Two cases run the command inside the drag, which then keeps the command's edit as part of its own step: a press of the Quick Pen (an edit to its path ends the path), and `object.transform` with `copy` during an Alt-drag, which copies the art as the drag's move left it. A command run while a dialog's or a panel's preview is open runs inside that preview. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. |
| `agent_folders` | `{}` | Where VectorCraft opens and saves files for this session: `{read_folder, write_folder}`, each a path or `null`. In the open window, the agent folders of Preferences › AI Integrations (`Documents/ArtCraft/Agents/VectorCraft` for an empty one); in a headless session started for agents, the folders it was confined to (`read_folders` / `write_folders` list them all when a kind has several); a session started without automation roots answers `unrestricted: true`. An app reached with the deprecated `--connect` answers an error: its own `--automation-*-root` flags, if any, confine it. |
For example, create editable Japanese area type with the engine's vertical writing mode:
@@ -10861,7 +10884,7 @@ The Selection & Anchor Display and General preferences apply to `pointer_gesture
{"name":"pointer_gesture","arguments":{"tool":"selection","mods":{"cmd":true},"events":[{"kind":"down","x":175,"y":125},{"kind":"up","x":175,"y":125}]}}
```
The preferences for the view need the desktop app (`vectorcraft-cli mcp --connect`): `zoomWithMouseWheel` (the
The preferences for the view need the open window (see [Agents in the open window](#agents-in-the-open-window)): `zoomWithMouseWheel` (the
wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; the control channel's
`ui.wheel` turns the wheel), `trackpadRotateView` (on by default: a two-finger rotation on a Mac trackpad, in the
macOS app or in Safari, turns the view about the pointer once it reaches 5°; with it off, the gesture does not turn
+1 -1
View File
@@ -1190,7 +1190,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`.
- Parameter key lookups: the engine reads the params description of each built-in command, with the descriptions its `…` entries name, once per process, and answers the key check and the `ids` and `id` questions of each later command from that reading. A plug-in command's description, and a description whose `…` entries name a plug-in command, are still read each time. The accepted keys, the answers and the error messages are the same. In a release build on a one-object document, `object.move` with `ids` and `dx` takes 48 µs of thread CPU time per command instead of 61 µs, and `select.set` with `ids` 2.3 µs instead of 3.2 µs (medians of 7 alternating runs of 20,000 commands in one process, measured while other builds were running; `tests::params_cache::bench_params_keys_once`). The time is saved per command, in scripts, batches and MCP or plug-in call loops, and does not grow with the size of the document. `crates/engine/src/tests/params_cache.rs` compares every built-in command's answers with those of a fresh parse.
- Effect parameter types: `effect.apply`, `appearance.addEffect` and `effect.setParams` refuse an effect parameter of another type than the effect reads, for keys only the params text names too (the earlier 3D `perspective`, `lightAzimuth` and `lightElevation`, Scribble's `variation`, Outline Stroke's `width`, Gaussian Blur's `linear`), a Crop Marks `style` other than `roman` or `japanese`, and an installed plug-in effect's parameter of another type than its manifest gives it, in a `command.batch` step too, with the document and undo history unchanged; a replayed action still plays. `effect.setParams` checks the parameters against a Warp's new style, and refuses a `visible` that is not true or false, in a replayed action too. `crates/engine/src/tests/params.rs` (`an_effect_parameter_without_a_default_is_held_to_its_type`, `effect_commands_refuse_an_undefaulted_parameter_of_the_wrong_type`), `crates/engine/src/tests/plugins.rs` (`live_effect_plugins_reshape_editable_art_and_expand`), `crates/engine/src/cmd/effectcmd/tests.rs` (`set_params_refuses_a_visible_that_is_not_true_or_false`, `set_params_checks_the_effect_it_leaves`).
- MCP server with 33 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, undo/redo, UI inspect/screenshot aliases, any command), attached to the running app or headless. Headless and remote `command_list` include desktop `UI_COMMANDS` (`ui: true`); a UI-only id still needs `--connect` to run. Eight prompts (poster, icon-set, recolor, trace-and-style, export-set, check-spelling, variables-bind, path-tools). Effect ids are not command ids. Prefer a CLI built from the checkout when a release binary lags (#6460). `vectorcraft://commands/reference` serves the API reference. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings. `--automation-read-root` / `--automation-write-root` (on `vectorcraft-cli mcp` and on `vectorcraft --control`) confine the files commands read and write to chosen folders, links followed, with the flags PhotoCraft takes (#832); each flag may be given more than once, a path inside any of its folders being allowed (#3546, `file_access::tests::several_roots_of_a_kind_each_grant_their_access`, `cli::mcp_automation_roots_take_several_folders`). A long export can be cancelled (`notifications/cancelled` stops it at the next page or group and writes nothing), reports page progress to a client that sent a progress token, and does not make other requests wait: engine-free ones answer at once, the rest are refused as busy after two seconds (#2165, #2171, #2172).
- MCP server with 34 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, undo/redo, UI inspect/screenshot aliases, any command, agent folders), attached to the open window through the ArtCraft Launcher's AI agents switch or headless (#10621). Headless and remote `command_list` include desktop `UI_COMMANDS` (`ui: true`); a UI-only id needs the open window to run. Eight prompts (poster, icon-set, recolor, trace-and-style, export-set, check-spelling, variables-bind, path-tools). Effect ids are not command ids. Prefer a CLI built from the checkout when a release binary lags (#6460). `vectorcraft://commands/reference` serves the API reference. Tool descriptions and replies agree with the engine: format lists come from its format table, `save_file` says it keeps the document's own format, `inspect_document` reports the paint type's characters show, and selection exports report the encoder's warnings. `--automation-read-root` / `--automation-write-root` (on `vectorcraft-cli mcp` and on `vectorcraft --control`) confine the files commands read and write to chosen folders, links followed, with the flags PhotoCraft takes (#832); each flag may be given more than once, a path inside any of its folders being allowed (#3546, `file_access::tests::several_roots_of_a_kind_each_grant_their_access`, `cli::mcp_automation_roots_take_several_folders`). A long export can be cancelled (headless, `notifications/cancelled` stops it at the next page or group and writes nothing; in the open window it only stops the call waiting, and the app may still finish and write the export), reports page progress to a client that sent a progress token, and does not make other requests wait: engine-free ones answer at once, the rest are refused as busy after two seconds (#2165, #2171, #2172).
- MCP window captures from an app that does not send the image back go through a file in a new folder inside the system's temporary folder, which only the user can open on Unix, instead of a fixed name in the shared folder; the folder is removed after the read, also when the capture or the read fails (`tests::conventions::an_old_app_captures_the_window_in_a_new_private_folder`).
- MCP protocol: five prompts (`prompts/list` / `prompts/get`: poster, icon set, recolour, trace-and-style, export set), `completion/complete` for prompt arguments and template variables read from the live catalogues (formats, effect ids, command ids, trace presets, swatch and object ids), four resource templates (`vectorcraft://object/{id}`, `//command/{id}`, `//effect/{id}`, `//swatch/{name}`) so an agent reads one thing instead of the whole document, and `logging/setLevel` with `notifications/message`. `window.panel` ids are case-insensitive (display labels work too), `vectorcraft://object/{id}` reads through `document.node {summary: true}` (the same reply bytes from one lookup instead of summarizing the whole document: a leaf read on a 2,000-object document drops from ~20 ms to ~0.06 ms), large containers slice with `document.node {depth?, childLimit?}` (truncated levels report `childCount`), `document.inspect` and the `inspect_document` tool slice the same way so a depth-0 read is the layer skeleton (~9.7 KB instead of ~2 MB on a 2,000-object document), `document.find` locates nodes by name/kind/text with ancestor paths, and the CLI sweeps the protocol surface over stdio against the compiled binary. `docs/mcp.md` has a Protocol section covering the capability table and what is deliberately absent (subscriptions, progress, cancellation, sampling, elicitation, Streamable HTTP — all of which need the transport to interleave reads).
- Headless CLI (`vectorcraft-cli run`, `convert`, `info`, `bench`, `perf`, `mcp`). A `run` step, like a `command_batch` step over MCP, can use an earlier step's result (`"$1.id"`, #785); `run --commands FILE` (or `-` for standard input) reads the steps from a JSON array or JSON Lines, past the Windows command-line limit (#3147, `apps/vectorcraft-cli/tests/it/cli.rs` `run_reads_*`, `run_refuses_malformed_commands_naming_the_step`).
+5 -1
View File
@@ -117,6 +117,9 @@ echo "==> assembling $APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
# Executable and icon carry the display name (CFBundleExecutable / CFBundleIconFile).
cp "$WORK/bin/vectorcraft" "$APP/Contents/MacOS/VectorCraft"
# The CLI too, beside the app: the ArtCraft Launcher finds `vectorcraft-cli` next to the app's
# executable and registers `vectorcraft-cli mcp` for agents.
cp "$WORK/bin/vectorcraft-cli" "$APP/Contents/MacOS/vectorcraft-cli"
cp "$ROOT/assets/app-icon/vectorcraft.icns" "$APP/Contents/Resources/VectorCraft.icns"
sed -e "s/@VERSION@/$VERSION/g" -e "s/@SHORT_VERSION@/$SHORT_VERSION/g" \
-e "s/@BUILD_SHA@/${VECTORCRAFT_BUILD_SHA:-unknown}/g" \
@@ -127,7 +130,8 @@ printf 'APPL????' >"$APP/Contents/PkgInfo"
copy_docs "$APP/Contents/Resources"
# Sign inside-out: nested code first, then the bundle itself (no --deep on the final signature).
# Today the only nested code is the main executable; frameworks/helpers would be signed here too.
# The bundled CLI is nested executable code; sign it before sealing the app bundle.
sign --options runtime --identifier ai.storyteller.vectorcraft-cli "$APP/Contents/MacOS/vectorcraft-cli"
sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP/Contents/MacOS/VectorCraft"
sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP"
codesign --verify --strict --deep --verbose=2 "$APP"
+2460 -163
View File
File diff suppressed because it is too large. Load diff