From b837aa22dc013fdbfe6342112763c99fd335a3a9 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 18 Nov 2026 02:35:46 +0100 Subject: [PATCH] craft-control: agents in the open window for apps on main (#2141) The ArtCraft Launcher's switch (AgentSwitch, mcp_flag, launcher_allows), the agent settings, the connection file (agent-connection.json) and the -cli mcp side that finds the open window (Live: window while the app accepts agents, otherwise headless or the closed-app choice; launcher starts the app beside the CLI), behind the new feature agents. No UI toolkit and no async runtime. Same formats as craft_automation::agents on next, which can re-export these once the branches meet. --- Cargo.lock | 15 + Cargo.toml | 2 + crates/control/Cargo.toml | 16 + crates/control/src/agents/connection.rs | 115 ++++++ crates/control/src/agents/live.rs | 480 ++++++++++++++++++++++++ crates/control/src/agents/mod.rs | 72 ++++ crates/control/src/agents/settings.rs | 124 ++++++ crates/control/src/agents/switch.rs | 93 +++++ crates/control/src/lib.rs | 4 +- crates/control/tests/agents.rs | 428 +++++++++++++++++++++ 10 files changed, 1348 insertions(+), 1 deletion(-) create mode 100644 crates/control/src/agents/connection.rs create mode 100644 crates/control/src/agents/live.rs create mode 100644 crates/control/src/agents/mod.rs create mode 100644 crates/control/src/agents/settings.rs create mode 100644 crates/control/src/agents/switch.rs create mode 100644 crates/control/tests/agents.rs diff --git a/Cargo.lock b/Cargo.lock index d7561e563..49cefd1ff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1557,6 +1557,16 @@ dependencies = [ "ureq", ] +[[package]] +name = "craft-ai-agents" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-ai-integrations?rev=35e0352666a117407d62230a6c6c2366f3e21a3b#35e0352666a117407d62230a6c6c2366f3e21a3b" +dependencies = [ + "dirs", + "serde", + "serde_json", +] + [[package]] name = "craft-ai-core" version = "0.1.0" @@ -1675,10 +1685,15 @@ dependencies = [ name = "craft-control" version = "0.1.0" dependencies = [ + "craft-ai-agents", + "craft-atomic", + "craft-flags", "getrandom 0.3.4", + "log", "proptest", "serde", "serde_json", + "tempfile", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 159c22ad4..26cb9f606 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -58,6 +58,8 @@ craft-gzip = { path = "crates/gzip" } craft-gridcraft-format = { path = "crates/gridcraft-format" } craft-aaf = { path = "crates/aaf" } craft-atomic = { path = "crates/atomic" } +# The ArtCraft Launcher's app list for AI agents (storytold/craft-ai-integrations, crates/ai-agents). +craft-ai-agents = { git = "https://github.com/storytold/craft-ai-integrations", rev = "35e0352666a117407d62230a6c6c2366f3e21a3b" } craft-xtask = { path = "crates/xtask" } craft-captions = { path = "crates/captions" } craft-cfb = { path = "crates/cfb" } diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index 0a18ccc99..5c4a90242 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -10,6 +10,12 @@ repository.workspace = true [lints] workspace = true +[features] +default = [] +# AI agents in the open window (desktop): the ArtCraft Launcher's switch, the connection file and +# the `-cli mcp` side that finds the open window. The agent settings build without it. +agents = ["dep:craft-ai-agents", "dep:craft-atomic", "dep:craft-flags", "dep:log"] + [dependencies] serde = { workspace = true } serde_json = { workspace = true } @@ -18,6 +24,16 @@ serde_json = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] # The per-launch control token: 32 random bytes from the operating system (MIT OR Apache-2.0). getrandom = "0.3" +# The launcher's app list, read in one place for the launcher, the gateway and every app (MIT OR Apache-2.0, ours). +craft-ai-agents = { workspace = true, optional = true } +craft-atomic = { workspace = true, optional = true } +craft-flags = { workspace = true, optional = true } +log = { workspace = true, optional = true } [dev-dependencies] proptest = { workspace = true } +tempfile = "3" + +[[test]] +name = "agents" +required-features = ["agents"] diff --git a/crates/control/src/agents/connection.rs b/crates/control/src/agents/connection.rs new file mode 100644 index 000000000..0c0bcebc7 --- /dev/null +++ b/crates/control/src/agents/connection.rs @@ -0,0 +1,115 @@ +//! The connection file: where an app's control server listens for agents. + +use std::net::{SocketAddr, TcpStream}; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; + +/// The connection file in the app's settings folder, present while the app accepts agents. +pub const CONNECTION_FILE: &str = "agent-connection.json"; +/// The token file the app keeps in its settings folder for agent connections. +pub const TOKEN_FILE: &str = "agent-control.token"; +/// How long [`probe`] waits for a connection to be accepted. +pub const PROBE_TIMEOUT: Duration = Duration::from_millis(500); +/// The version of the [`Connection`] file format. +const CONNECTION_VERSION: u32 = 1; +/// The largest connection file read; anything bigger is not one. +const MAX_CONNECTION_BYTES: u64 = 1 << 20; + +/// What an app publishes in [`CONNECTION_FILE`]: `{"version", "pid", "port", "tokenFile", "app"}`. +/// Holds no secret: the token stays in its own owner-only file. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Connection { + /// The file format's version (1). + pub version: u32, + /// The app's process id: only that process removes the file. + pub pid: u32, + /// The loopback port of the control server. + pub port: u16, + /// The file holding the token. + pub token_file: PathBuf, + /// The app's version, for diagnostics. + pub app: String, +} + +impl Connection { + /// This process's connection on `port`, naming `app` (the app's version string). + pub fn new(port: u16, token_file: PathBuf, app: impl Into) -> Self { + Self { version: CONNECTION_VERSION, pid: std::process::id(), port, token_file, app: app.into() } + } + + /// `127.0.0.1:`. + pub fn addr(&self) -> String { + format!("127.0.0.1:{}", self.port) + } +} + +fn io_error(path: &Path, e: impl std::fmt::Display) -> std::io::Error { + std::io::Error::other(format!("{}: {e}", path.display())) +} + +/// Publishes `c` in `dir` (made if missing), written atomically so a reader never sees half a +/// file. +pub fn write_connection(dir: &Path, c: &Connection) -> std::io::Result<()> { + std::fs::create_dir_all(dir).map_err(|e| io_error(dir, e))?; + let path = dir.join(CONNECTION_FILE); + let text = serde_json::to_string_pretty(c).map_err(|e| io_error(&path, e))?; + craft_atomic::atomic_write(&path, text.as_bytes()).map_err(|e| io_error(&path, e)) +} + +/// The connection published in `dir`, if any. A file of another version, with port 0, or one +/// that does not parse (invalid UTF-8 included) counts as none: the app rewrites it when it next +/// starts listening. Anything but a regular file (a FIFO would block the read) or a file over +/// 1 MiB is an error, and left alone. +pub fn read_connection(dir: &Path) -> std::io::Result> { + let path = dir.join(CONNECTION_FILE); + let meta = match std::fs::metadata(&path) { + Ok(m) => m, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(io_error(&path, e)), + }; + if !meta.is_file() { + return Err(io_error(&path, "not a regular file")); + } + if meta.len() > MAX_CONNECTION_BYTES { + return Err(io_error(&path, format!("larger than {MAX_CONNECTION_BYTES} bytes"))); + } + let bytes = match std::fs::read(&path) { + Ok(b) => b, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(io_error(&path, e)), + }; + Ok(serde_json::from_slice::(&bytes).ok().filter(|c| c.version == CONNECTION_VERSION && c.port != 0)) +} + +/// Removes the connection file in `dir` if process `pid` wrote it (another instance may have +/// published its own since). Errors are ignored: a stale file only fails [`probe`]. +pub fn remove_connection(dir: &Path, pid: u32) { + if let Ok(Some(c)) = read_connection(dir) + && c.pid == pid + { + let _ = std::fs::remove_file(dir.join(CONNECTION_FILE)); + } +} + +/// Removes the connection file in `dir` when nothing listens on its port any more (an app that +/// crashed or quit without removing it), or when it does not read as a connection. A live +/// instance's file is kept, and so is anything but a regular file. Errors are ignored. +pub fn remove_stale_connection(dir: &Path) { + let path = dir.join(CONNECTION_FILE); + let stale = match read_connection(dir) { + Ok(Some(c)) => !probe(c.port, PROBE_TIMEOUT), + Ok(None) => path.is_file(), + Err(_) => false, + }; + if stale { + let _ = std::fs::remove_file(path); + } +} + +/// Whether something accepts connections on loopback `port` within `timeout`; port 0 never does. +pub fn probe(port: u16, timeout: Duration) -> bool { + port != 0 && TcpStream::connect_timeout(&SocketAddr::from(([127, 0, 0, 1], port)), timeout).is_ok() +} diff --git a/crates/control/src/agents/live.rs b/crates/control/src/agents/live.rs new file mode 100644 index 000000000..d328c678f --- /dev/null +++ b/crates/control/src/agents/live.rs @@ -0,0 +1,480 @@ +//! The other end of the link: where an app's `-cli mcp` sends each tool call. +//! +//! [`Live::resolve`] runs before every tool call. It reads the connection file the app publishes +//! while it accepts agents ([`super::write_connection`]), so the app may start, quit or move to another port +//! while the MCP client stays connected, and the client's configuration holds no port and no +//! token: +//! +//! - An app that accepts agents: the call goes to its open window ([`Route::Window`]). The same +//! port, token and process id keep the window client the app made; any change makes a new one. +//! - No app accepts agents, and the person doesn't let agents use it: a session without a window +//! with only the folders given to the command ([`LiveConfig::read_roots`], [`LiveConfig::write_root`]), +//! as `mcp` always worked. The app's own folders are for agents the person let in. +//! - No app accepts agents, but agents are allowed: the closed-app choice decides +//! ([`LiveConfig::when_closed`], otherwise [`AgentSettings::when_app_closed`]): start the app and +//! wait until it accepts agents, a headless session with the app's agent folders (the command's +//! folders win), or an error that says what to do. +//! +//! Once headless, the session stays headless: documents don't move under the agent. Lookups are +//! serialised, so concurrent calls start the app once. +//! +//! The crate has no async runtime: `resolve` blocks (file reads, a loopback probe, and while an +//! app starts, polling), so an async MCP server calls it from its blocking pool. What a window +//! client and a headless session are stays the app's ([`LiveConfig::new`]'s `connect` and +//! `headless`), and so do the tools and the transport. Errors are the tool call's result: words +//! for the agent, and through it the person, naming the app. + +use std::ffi::{OsStr, OsString}; +use std::fmt; +use std::path::{Path, PathBuf}; +use std::sync::{Mutex, PoisonError}; +use std::time::{Duration, Instant}; + +use super::{AgentSettings, Connection, PROBE_TIMEOUT, WhenAppClosed, probe, read_connection}; + +/// Starts the desktop app; see [`launcher`]. +pub type LaunchFn = Box Result<(), String> + Send + Sync>; +/// What the person allows now, read from the app's settings folder before every call. +pub type ConsentFn = Box Consent + Send + Sync>; +/// Makes the app's client for its open window. +pub type ConnectFn = Box Result + Send + Sync>; +/// Makes the app's headless session with these folders. +pub type HeadlessFn = Box Result + Send + Sync>; + +/// How long a started app gets to accept agents. A first start can take a while (GPU shader +/// caches, a font scan), but MCP clients give a tool call about a minute. +pub const LAUNCH_TIMEOUT: Duration = Duration::from_secs(45); +/// How often a starting app's connection file is looked for. +pub const LAUNCH_POLL: Duration = Duration::from_millis(250); + +/// The open window a call goes to: from the connection file, with the token from its token file. +#[derive(Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Window { + /// The loopback port of the app's control server. + pub port: u16, + /// The app's process id. + pub pid: u32, + /// The control token (hex digits, lower case). + pub token: String, +} + +impl Window { + /// `127.0.0.1:`. + pub fn addr(&self) -> String { + format!("127.0.0.1:{}", self.port) + } +} + +impl fmt::Debug for Window { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // Never the token: Debug output ends up in logs. + f.debug_struct("Window").field("port", &self.port).field("pid", &self.pid).finish_non_exhaustive() + } +} + +/// Whether the person lets agents use the app now, and its agent settings. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct Consent { + /// Agents may use the app ([`super::agents_allowed`]: with the suite's `AI-MCP` flag, the + /// ArtCraft Launcher's switch). + pub allowed: bool, + /// The app's agent settings (closed-app choice, folders). + pub settings: AgentSettings, +} + +impl Consent { + /// `allowed` with these settings. + pub fn new(allowed: bool, settings: AgentSettings) -> Self { + Self { allowed, settings } + } +} + +/// The folders a headless session may open from and save to. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct HeadlessFolders { + /// Folders files may be opened from. + pub read: Vec, + /// The folder files may be saved to. + pub write: Option, +} + +/// Where a tool call goes: the app's window client or its headless session. +#[derive(Clone, Debug)] +pub enum Route { + /// The open window. + Window(W), + /// A session without a window. + Headless(H), +} + +/// What [`Live`] needs from the app. +#[non_exhaustive] +pub struct LiveConfig { + /// The app's name in messages (`"PhotoCraft"`). + pub app_name: String, + /// The app's settings folder: connection file, token file and settings. + pub config_dir: PathBuf, + /// Overrides the app's closed-app choice (the CLI's `--when-closed`). + pub when_closed: Option, + /// Folders a headless session may open from (the CLI's read roots); while agents are allowed + /// they replace the app's read folder. + pub read_roots: Vec, + /// The folder a headless session may save to (the CLI's write root); while agents are allowed + /// it replaces the app's write folder. + pub write_root: Option, + /// Starts the app; `None` when this install can't ([`launcher`] found nothing to start). + pub launch: Option, + /// How long a started app gets to accept agents ([`LAUNCH_TIMEOUT`]). + pub launch_timeout: Duration, + /// How often a starting app is looked for ([`LAUNCH_POLL`]). + pub poll: Duration, + consent: ConsentFn, + connect: ConnectFn, + headless: HeadlessFn, +} + +impl LiveConfig { + /// The app `app_name` with its settings in `config_dir`: `consent` reads whether agents may + /// use it, `connect` makes a client for its open window, `headless` a session without one. + pub fn new( + app_name: impl Into, + config_dir: PathBuf, + consent: impl Fn(&Path) -> Consent + Send + Sync + 'static, + connect: impl Fn(&Window) -> Result + Send + Sync + 'static, + headless: impl Fn(&HeadlessFolders) -> Result + Send + Sync + 'static, + ) -> Self { + Self { + app_name: app_name.into(), + config_dir, + when_closed: None, + read_roots: Vec::new(), + write_root: None, + launch: None, + launch_timeout: LAUNCH_TIMEOUT, + poll: LAUNCH_POLL, + consent: Box::new(consent), + connect: Box::new(connect), + headless: Box::new(headless), + } + } +} + +/// The port, token and process id a window client was made for: a restarted app may keep its +/// port and token, but its old socket is gone. +type WindowKey = (u16, String, u32); +/// The current route, and for a window the key it was made for. +type Current = Option<(Route, Option)>; + +/// Resolves each tool call of one MCP session; see the module docs. +pub struct Live { + cfg: LiveConfig, + /// Serialises lookups, so concurrent calls start the app once. + lookup: Mutex<()>, + current: Mutex>, +} + +impl Live { + /// A session that has not resolved anything yet. + pub fn new(cfg: LiveConfig) -> Self { + Self { cfg, lookup: Mutex::new(()), current: Mutex::new(None) } + } + + /// The route the last [`Self::resolve`] chose, if any. + pub fn current(&self) -> Option> { + self.current.lock().unwrap_or_else(PoisonError::into_inner).as_ref().map(|(r, _)| r.clone()) + } + + fn set(&self, route: Route, key: Option) -> Route { + *self.current.lock().unwrap_or_else(PoisonError::into_inner) = Some((route.clone(), key)); + route + } + + /// Where the next tool call goes. Blocks; see the module docs. The error is the tool call's + /// result. + pub fn resolve(&self) -> Result, String> { + let _one_at_a_time = self.lookup.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(route @ Route::Headless(_)) = self.current() { + return Ok(route); + } + let consent = (self.cfg.consent)(&self.cfg.config_dir); + if let Some(window) = self.find_app()? { + return self.use_window(window); + } + if !consent.allowed { + let folders = HeadlessFolders { read: self.cfg.read_roots.clone(), write: self.cfg.write_root.clone() }; + return self.headless(&folders, "the automation roots can't be used"); + } + let app = &self.cfg.app_name; + match self.cfg.when_closed.unwrap_or(consent.settings.when_app_closed) { + WhenAppClosed::Error => Err(format!("{app} isn't running: open it, then try again.")), + WhenAppClosed::Headless => { + let read = + if self.cfg.read_roots.is_empty() { consent.settings.read_folder().into_iter().collect() } else { self.cfg.read_roots.clone() }; + let write = self.cfg.write_root.clone().or_else(|| consent.settings.write_folder()); + self.headless(&HeadlessFolders { read, write }, &format!("{app} isn't running and its agent folders can't be used")) + } + WhenAppClosed::Launch => self.launch_and_wait(), + } + } + + fn headless(&self, folders: &HeadlessFolders, why: &str) -> Result, String> { + let session = (self.cfg.headless)(folders).map_err(|e| format!("{why}: {e}"))?; + Ok(self.set(Route::Headless(session), None)) + } + + fn launch_and_wait(&self) -> Result, String> { + let app = &self.cfg.app_name; + let Some(launch) = &self.cfg.launch else { + return Err(format!("{app} isn't running, and this install can't start it from here: open {app}, then try again.")); + }; + launch().map_err(|e| format!("couldn't start {app}: {e}"))?; + let deadline = Instant::now() + self.cfg.launch_timeout; + loop { + std::thread::sleep(self.cfg.poll); + if let Some(window) = self.find_app()? { + return self.use_window(window); + } + if Instant::now() >= deadline { + return Err(format!( + "{app} didn't accept agents within {} s of starting. If it's still opening, try again in a moment; otherwise check that AI agents are on in ArtCraft Launcher › Settings › AI agents.", + self.cfg.launch_timeout.as_secs() + )); + } + } + } + + fn use_window(&self, window: Window) -> Result, String> { + let key: WindowKey = (window.port, window.token.clone(), window.pid); + { + let current = self.current.lock().unwrap_or_else(PoisonError::into_inner); + if let Some((route, Some(k))) = current.as_ref() + && *k == key + { + return Ok(route.clone()); + } + } + let client = (self.cfg.connect)(&window)?; + Ok(self.set(Route::Window(client), Some(key))) + } + + /// The app accepting agents now: `None` when there is no connection file, or one left by an + /// app that crashed (nothing listens on its port). + fn find_app(&self) -> Result, String> { + find_window(&self.cfg.config_dir, &self.cfg.app_name) + } +} + +/// The window accepting agents with its settings in `dir`, with the token from its token file; +/// `None` when no app accepts agents there. `app_name` names the app in errors. +pub fn find_window(dir: &Path, app_name: &str) -> Result, String> { + let Some(c): Option = read_connection(dir).map_err(|e| e.to_string())? else { return Ok(None) }; + if !probe(c.port, PROBE_TIMEOUT) { + return Ok(None); + } + let token = read_token(&c.token_file).map_err(|e| format!("{app_name}'s agent token: {e}"))?; + Ok(Some(Window { port: c.port, pid: c.pid, token })) +} + +/// The largest token file read; a token is far shorter. +const MAX_TOKEN_FILE: u64 = 4096; + +/// The token in the token file at `path`, trimmed. The file must be a regular file of at most +/// [`MAX_TOKEN_FILE`] bytes holding a non-empty token of hex digits, and on Unix readable by its +/// owner only: a token others could read is refused rather than used. +fn read_token(path: &Path) -> Result { + use std::io::Read; + let shown = |e: &dyn fmt::Display| format!("{}: {e}", path.display()); + let file = std::fs::File::open(path).map_err(|e| shown(&e))?; + let meta = file.metadata().map_err(|e| shown(&e))?; + if !meta.is_file() { + return Err(shown(&"not a regular file")); + } + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if meta.mode() & 0o077 != 0 { + return Err(shown(&format!("readable by group or others (mode {:o}); restrict it to its owner", meta.mode() & 0o777))); + } + } + let mut text = String::new(); + file.take(MAX_TOKEN_FILE + 1).read_to_string(&mut text).map_err(|e| shown(&e))?; + if text.len() as u64 > MAX_TOKEN_FILE { + return Err(shown(&format!("larger than {MAX_TOKEN_FILE} bytes"))); + } + let token = text.trim(); + if token.is_empty() || !token.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err(shown(&"not a control token")); + } + Ok(token.to_ascii_lowercase()) +} + +/// How to start the desktop app `exe` (its file name without `.exe`) that ships beside the CLI at +/// `cli`: detached and with no standard streams, since the CLI's carry the MCP protocol and the +/// app must outlive the MCP client. `None` where this install can't start it: inside a Flatpak, +/// or with no app beside the CLI. +pub fn launcher(cli: &Path, exe: &str) -> Option { + use std::process::{Command, Stdio}; + let env = |name: &str| std::env::var_os(name).filter(|v| !v.is_empty()); + let (program, args) = + launch_command(cli, exe, Platform::current(), env("FLATPAK_ID").is_some(), env("APPIMAGE"), env("SystemRoot"), &|p| p.is_file())?; + let mut command = Command::new(program); + command.args(args); + let command = Mutex::new(command); + Some(Box::new(move || { + let mut c = command.lock().unwrap_or_else(PoisonError::into_inner); + c.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()); + detach(&mut c); + c.spawn().map(|_| ()).map_err(|e| e.to_string()) + })) +} + +/// The platform [`launch_command`] plans for. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Platform { + Windows, + MacOs, + Other, +} + +impl Platform { + fn current() -> Self { + if cfg!(windows) { + Self::Windows + } else if cfg!(target_os = "macos") { + Self::MacOs + } else { + Self::Other + } + } +} + +/// The program and arguments that start the app; see [`launcher`]. +fn launch_command( + cli: &Path, + exe: &str, + platform: Platform, + flatpak: bool, + appimage: Option, + system_root: Option, + is_file: &dyn Fn(&Path) -> bool, +) -> Option<(PathBuf, Vec)> { + if flatpak { + return None; + } + if let Some(image) = appimage { + // The AppImage's mount point goes away with the CLI; the image itself stays. + return Some((PathBuf::from(image), Vec::new())); + } + let dir = cli.parent()?; + if platform == Platform::MacOs + && dir.ends_with("Contents/MacOS") + && let Some(bundle) = dir.parent().and_then(Path::parent) + { + // A macOS app bundle: LaunchServices starts (or brings forward) the app. + return Some((PathBuf::from("/usr/bin/open"), vec![OsString::from("-a"), bundle.as_os_str().to_os_string()])); + } + let app = dir.join(if platform == Platform::Windows { format!("{exe}.exe") } else { exe.to_owned() }); + if !is_file(&app) { + return None; + } + Some(if platform == Platform::Windows { windows_launch(&app, system_root.as_deref()) } else { (app, Vec::new()) }) +} + +/// How Windows starts the app at `app`: through Explorer, as a double-click would. The app is then +/// no child of the CLI, so it outlives the MCP client ending the CLI's process tree (Claude Code +/// does on Windows), and it runs outside the container of a Microsoft Store client (Claude +/// Desktop): there, new files under `%APPDATA%` land in the client's package, where the app +/// started from the Start menu would never see them. Explorer reads a comma as a separator, so +/// such a path is started directly. (`%WINDIR%` can be empty under a Store client, hence +/// `%SystemRoot%`.) +fn windows_launch(app: &Path, system_root: Option<&OsStr>) -> (PathBuf, Vec) { + if app.to_string_lossy().contains(',') { + return (app.to_path_buf(), Vec::new()); + } + let root = system_root.filter(|r| !r.is_empty()).map_or_else(|| PathBuf::from(r"C:\Windows"), PathBuf::from); + (root.join("explorer.exe"), vec![app.as_os_str().to_os_string()]) +} + +/// Keeps the app running when the MCP client stops the CLI (and its process group). +fn detach(c: &mut std::process::Command) { + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + c.process_group(0); + } + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + const DETACHED_PROCESS: u32 = 0x0000_0008; + const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200; + c.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP); + } + #[cfg(not(any(unix, windows)))] + let _ = c; +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + use super::*; + + fn plan( + cli: &str, + platform: Platform, + flatpak: bool, + appimage: Option<&str>, + root: Option<&str>, + exists: bool, + ) -> Option<(PathBuf, Vec)> { + launch_command(Path::new(cli), "photocraft", platform, flatpak, appimage.map(OsString::from), root.map(OsString::from), &|_| exists) + } + + #[test] + fn windows_starts_the_app_through_explorer() { + let app = Path::new(r"C:\Program Files\PhotoCraft\photocraft.exe"); + let (program, args) = windows_launch(app, Some(OsStr::new(r"D:\Win"))); + assert_eq!(program, Path::new(r"D:\Win").join("explorer.exe")); + assert_eq!(args, [app.as_os_str()]); + // No usable %SystemRoot%: the default Windows folder. + let default = Path::new(r"C:\Windows").join("explorer.exe"); + assert_eq!(windows_launch(app, Some(OsStr::new(""))).0, default); + assert_eq!(windows_launch(app, None).0, default); + // Explorer would split this path at the comma. + let comma = Path::new(r"C:\Apps, tools\photocraft.exe"); + assert_eq!(windows_launch(comma, None), (comma.to_path_buf(), Vec::new())); + } + + #[test] + fn the_launch_command_fits_the_install() { + // Flatpak: the sandbox can't start the app. + assert_eq!(plan("/app/bin/photocraft-cli", Platform::Other, true, Some("/x.AppImage"), None, true), None); + // An AppImage starts its image, not the mount point the CLI runs from. + assert_eq!( + plan("/tmp/.mount/usr/bin/photocraft-cli", Platform::Other, false, Some("/home/a/P.AppImage"), None, false), + Some((PathBuf::from("/home/a/P.AppImage"), Vec::new())) + ); + // A macOS bundle opens through LaunchServices. + let (program, args) = plan("/Applications/PhotoCraft.app/Contents/MacOS/photocraft-cli", Platform::MacOs, false, None, None, false).unwrap(); + assert_eq!(program, Path::new("/usr/bin/open")); + assert_eq!(args, [OsString::from("-a"), OsString::from("/Applications/PhotoCraft.app")]); + // Beside the CLI, by the app's file name. + assert_eq!(plan("/opt/pc/photocraft-cli", Platform::Other, false, None, None, true), Some((PathBuf::from("/opt/pc/photocraft"), Vec::new()))); + let (program, args) = plan(r"C:\PC\photocraft-cli.exe", Platform::Windows, false, None, Some(r"C:\Win"), true).unwrap(); + assert_eq!(program, Path::new(r"C:\Win").join("explorer.exe")); + // The app beside the CLI (on a non-Windows host the backslashes are no separators). + assert_eq!(args, [Path::new(r"C:\PC\photocraft-cli.exe").parent().unwrap().join("photocraft.exe").into_os_string()]); + // No app beside the CLI: nothing to start. + assert_eq!(plan("/opt/pc/photocraft-cli", Platform::Other, false, None, None, false), None); + assert_eq!(plan("photocraft-cli", Platform::Other, false, None, None, true).map(|p| p.0), Some(PathBuf::from("photocraft"))); + } + + #[test] + fn a_window_never_shows_its_token() { + let w = Window { port: 7, pid: 9, token: "ab".repeat(32) }; + assert!(!format!("{w:?}").contains("abab")); + assert_eq!(w.addr(), "127.0.0.1:7"); + } +} diff --git a/crates/control/src/agents/mod.rs b/crates/control/src/agents/mod.rs new file mode 100644 index 000000000..77d45d25d --- /dev/null +++ b/crates/control/src/agents/mod.rs @@ -0,0 +1,72 @@ +//! AI agents in the open window, with no UI toolkit: whether the person lets agents use the app, +//! how the app tells its own `-cli mcp` where it listens, and where that CLI sends each tool +//! call. +//! +//! One switch serves every Craft app: the ArtCraft Launcher's *Settings › AI agents › Let AI agents +//! use Craft apps*, which writes the launcher's app list (`craft_ai_agents`). With the suite's +//! `AI-MCP` flag on, an app lets agents in when that list names it ([`AgentSwitch`]); without the +//! flag, the app's own earlier consent decides ([`agents_allowed`]). Apps have no agents switch of +//! their own. +//! +//! While agents may connect, the app serves its control channel on loopback with a token +//! ([`crate::server`], [`crate::auth`], or its own) and publishes where in its settings folder +//! ([`CONNECTION_FILE`]): the port, its process id and the token file. The app's `-cli mcp` +//! reads that file before every tool call ([`Live`]), so an MCP client's configuration never holds +//! a port or a token. The file holds no secret. A crashed app can leave it behind; nothing then +//! listens on its port ([`probe`]), and the app's next launch removes it +//! ([`remove_stale_connection`]). +//! +//! | Part | Names | Builds | +//! |---|---|---| +//! | Settings | [`AgentSettings`], [`WhenAppClosed`], [`agents_allowed`], [`folder`] | every target | +//! | The launcher's switch | [`AgentSwitch`], [`mcp_flag`], [`launcher_allows`], [`POLL`] | desktop, feature `agents` | +//! | The connection file | [`Connection`], [`write_connection`], [`read_connection`], [`remove_connection`], [`remove_stale_connection`], [`probe`] | desktop, feature `agents` | +//! | The CLI's side | [`Live`], [`LiveConfig`], [`Route`], [`Window`], [`Consent`], [`HeadlessFolders`], [`find_window`], [`launcher`] | desktop, feature `agents` | +//! +//! The same formats as `craft_automation::agents` on the shared UI library's branch (`next`), +//! which adds the egui link host and the Agents page of Preferences. +//! +//! # Adding an app +//! +//! The app (its id is the one in the ArtCraft Launcher's catalog, `"gridcraft"`): +//! +//! 1. At start, [`remove_stale_connection`] in its settings folder, then +//! `AgentSwitch::watch("gridcraft", wake)`, where `wake` asks the UI for a frame. +//! 2. On each change of [`AgentSwitch::allows`]: when it allows, listen on loopback with a token, +//! the token in an owner-only file ([`crate::auth::App::write_token_file`]), and +//! [`write_connection`] with [`Connection::new`]; when it stops allowing, stop listening and +//! [`remove_connection`] with the app's process id. No restart, no agents switch of its own. +//! +//! Its `gridcraft-cli mcp`: +//! +//! 1. A [`LiveConfig`] with the app's settings folder; `consent` reads its saved +//! [`AgentSettings`] and asks [`launcher_allows`]; `connect` makes the app's client for a +//! [`Window`] (its address and token); `headless` makes its session without a window for +//! [`HeadlessFolders`]. [`launcher`] starts the app beside the CLI. +//! 2. Before every tool call, [`Live::resolve`] (from a blocking thread in an async server), then +//! the call goes to the [`Route`] it returns. `--headless` skips [`Live`] altogether. + +// The links above name items of the `agents` feature; without it they have nothing to point at, +// and the docs of the settings alone still build. +#![cfg_attr(not(all(feature = "agents", not(target_arch = "wasm32"))), allow(rustdoc::broken_intra_doc_links))] + +mod settings; +pub use settings::{AgentSettings, WhenAppClosed, agents_allowed, folder}; + +#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] +mod connection; +#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] +mod live; +#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] +mod switch; +#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] +pub use connection::{ + CONNECTION_FILE, Connection, PROBE_TIMEOUT, TOKEN_FILE, probe, read_connection, remove_connection, remove_stale_connection, write_connection, +}; +#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] +pub use live::{ + ConnectFn, Consent, ConsentFn, HeadlessFn, HeadlessFolders, LAUNCH_POLL, LAUNCH_TIMEOUT, LaunchFn, Live, LiveConfig, Route, Window, find_window, + launcher, +}; +#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] +pub use switch::{AgentSwitch, POLL, launcher_allows, mcp_flag}; diff --git a/crates/control/src/agents/settings.rs b/crates/control/src/agents/settings.rs new file mode 100644 index 000000000..04ae933aa --- /dev/null +++ b/crates/control/src/agents/settings.rs @@ -0,0 +1,124 @@ +//! The agent settings an app saves in its preferences, and who decides that agents may connect. + +use std::path::PathBuf; + +use serde::{Deserialize, Serialize}; + +/// The agent settings of an app's Preferences (its `integrations` section in PhotoCraft). Saved in +/// camelCase: `allowAgentControl`, `controlPort`, `readRoot`, `writeRoot`, `whenAppClosed`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +#[non_exhaustive] +pub struct AgentSettings { + /// Off refuses every control server, `--control` included. + pub allow_agent_control: bool, + /// The loopback port agents connect to; 0 is any free port, published in the connection file. + pub control_port: u32, + /// The folder agents may open from; empty is none. Applied at once while agents are connected. + pub read_root: String, + /// The folder agents may save to; empty is none. Applied at once while agents are connected. + pub write_root: String, + /// What the app's `-cli mcp` does while agents may use the app but it is closed. + pub when_app_closed: WhenAppClosed, +} + +impl Default for AgentSettings { + fn default() -> Self { + Self { + allow_agent_control: true, + control_port: 0, + read_root: String::new(), + write_root: String::new(), + when_app_closed: WhenAppClosed::Launch, + } + } +} + +impl AgentSettings { + /// [`Self::read_root`] as a path ([`folder`]). + pub fn read_folder(&self) -> Option { + folder(&self.read_root) + } + + /// [`Self::write_root`] as a path ([`folder`]). + pub fn write_folder(&self) -> Option { + folder(&self.write_root) + } +} + +/// A folder setting as a path, trimmed; empty or blank is `None`. +pub fn folder(pref: &str) -> Option { + let pref = pref.trim(); + (!pref.is_empty()).then(|| PathBuf::from(pref)) +} + +/// What an app's `-cli mcp` does when an agent calls a tool while the app is closed. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum WhenAppClosed { + /// Open the app and wait for it. + #[default] + Launch, + /// Run the tool without a window. + Headless, + /// Answer with an error that asks to open the app. + Error, +} + +impl WhenAppClosed { + /// The saved names, in [`Self::ALL`] order. + pub const NAMES: &'static [&'static str] = &["launch", "headless", "error"]; + /// Every choice, in the order a menu lists them. + pub const ALL: [Self; 3] = [Self::Launch, Self::Headless, Self::Error]; + + /// The saved name. + pub fn name(self) -> &'static str { + match self { + Self::Launch => "launch", + Self::Headless => "headless", + Self::Error => "error", + } + } + + /// The choice a saved name means; `None` for any other text. + pub fn parse(name: &str) -> Option { + Self::ALL.into_iter().find(|c| c.name() == name) + } +} + +/// Whether agents may use the open window. With the suite's `AI-MCP` flag only the launcher's +/// switch decides: one switch for every Craft app, none in the app. Without the flag the app's own +/// earlier consent decides (`legacy`; PhotoCraft's is a Control Port saved before the switch). +/// Allow Agent Control off still refuses agents either way ([`AgentSettings::allow_agent_control`]). +pub fn agents_allowed(mcp_flag: bool, launcher: bool, legacy: bool) -> bool { + if mcp_flag { launcher } else { legacy } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + + // The saved names read back as the same choice, and nothing else reads as one. + #[test] + fn when_app_closed_names_round_trip() { + for choice in WhenAppClosed::ALL { + assert_eq!(WhenAppClosed::parse(choice.name()), Some(choice)); + assert_eq!(serde_json::to_value(choice).unwrap(), serde_json::json!(choice.name())); + } + assert_eq!(WhenAppClosed::NAMES, WhenAppClosed::ALL.map(WhenAppClosed::name)); + assert_eq!(WhenAppClosed::parse("Launch"), None); + let settings: AgentSettings = serde_json::from_str(r#"{"whenAppClosed": "headless", "controlPort": 7878}"#).unwrap(); + assert_eq!((settings.when_app_closed, settings.control_port, settings.allow_agent_control), (WhenAppClosed::Headless, 7878, true)); + } + + // A folder setting is trimmed; empty or blank means no folder. + #[test] + fn folder_preferences_are_trimmed() { + assert_eq!(folder(""), None); + assert_eq!(folder(" "), None); + assert_eq!(folder(" /work/project "), Some(PathBuf::from("/work/project"))); + let settings = AgentSettings { read_root: " /in ".into(), ..AgentSettings::default() }; + assert_eq!((settings.read_folder(), settings.write_folder()), (Some(PathBuf::from("/in")), None)); + } +} diff --git a/crates/control/src/agents/switch.rs b/crates/control/src/agents/switch.rs new file mode 100644 index 000000000..cf45f07a7 --- /dev/null +++ b/crates/control/src/agents/switch.rs @@ -0,0 +1,93 @@ +//! The ArtCraft Launcher's switch for one app, behind the suite's `AI-MCP` flag. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Weak}; +use std::time::Duration; + +use super::agents_allowed; + +/// How often [`AgentSwitch::watch`] reads the launcher's app list. +pub const POLL: Duration = Duration::from_secs(2); + +/// The suite's `AI-MCP` flag (`ArtCraft/flags.toml` or `CRAFT_FLAGS`). Reads the flags file; +/// what could not be read is logged. +pub fn mcp_flag() -> bool { + let flags = craft_flags::load(); + for problem in &flags.problems { + log::warn!("flags: {problem}"); + } + flags.enabled(&craft_flags::AI_MCP) +} + +/// The launcher's switch (Settings › AI agents › *Let AI agents use Craft apps*) lets agents use +/// the app `app_id`: the `AI-MCP` flag is on and the launcher's app list names the app. Reads two +/// small files; ask from a timer or a command, not every frame ([`AgentSwitch`] does that). +pub fn launcher_allows(app_id: &str) -> bool { + mcp_flag() && craft_ai_agents::allowed(app_id) +} + +/// The launcher's switch for one app, watched on a thread so a frame can ask without touching the +/// disk. The `AI-MCP` flag is read once, at [`Self::watch`]; the launcher's list every [`POLL`]. +/// Clones share one watch; the thread ends after the last clone is dropped. +#[derive(Clone, Debug)] +pub struct AgentSwitch { + mcp_flag: bool, + on: Arc, +} + +impl AgentSwitch { + /// Watches the launcher's list for `app_id`; a change logs `agents on/off` and calls `wake` (the + /// app asks for a frame there). + /// Without the `AI-MCP` flag nothing is watched: the launcher's list means nothing then. + pub fn watch(app_id: &'static str, wake: impl Fn() + Send + 'static) -> Self { + let flag = mcp_flag(); + if !flag { + return Self::fixed(false, false); + } + Self::watch_with(flag, move || craft_ai_agents::allowed(app_id), POLL, wake) + } + + /// A switch that never changes: tests, the web, an app without agents. + pub fn fixed(mcp_flag: bool, launcher: bool) -> Self { + Self { mcp_flag, on: Arc::new(AtomicBool::new(launcher)) } + } + + /// [`Self::watch`] with the flag given, `probe` asked once now and then every `poll`. + #[doc(hidden)] + pub fn watch_with(mcp_flag: bool, probe: impl Fn() -> bool + Send + 'static, poll: Duration, wake: impl Fn() + Send + 'static) -> Self { + let on = Arc::new(AtomicBool::new(probe())); + let seen: Weak = Arc::downgrade(&on); + let started = std::thread::Builder::new().name("launcher-agents".into()).spawn(move || { + loop { + std::thread::sleep(poll); + let now = probe(); + let Some(seen) = seen.upgrade() else { return }; + if seen.swap(now, Ordering::Relaxed) != now { + log::info!("ArtCraft Launcher: agents {}", if now { "on" } else { "off" }); + wake(); + } + } + }); + // Without a thread the answer stays what it was at launch. + if let Err(e) = started { + log::warn!("couldn't watch the ArtCraft Launcher's agents switch: {e}"); + } + Self { mcp_flag, on } + } + + /// The `AI-MCP` flag as it was when the watch started. + pub fn mcp_flag(&self) -> bool { + self.mcp_flag + } + + /// Whether the launcher's list named the app at the last poll. + pub fn launcher(&self) -> bool { + self.on.load(Ordering::Relaxed) + } + + /// Whether agents may use the open window ([`agents_allowed`]); `legacy` is the app's own + /// earlier consent, which counts only without the flag. + pub fn allows(&self, legacy: bool) -> bool { + agents_allowed(self.mcp_flag, self.launcher(), legacy) + } +} diff --git a/crates/control/src/lib.rs b/crates/control/src/lib.rs index 26727a97c..d2e4f3d95 100644 --- a/crates/control/src/lib.rs +++ b/crates/control/src/lib.rs @@ -2,12 +2,14 @@ //! files ([`auth`]), the loopback server that admits a connection by the token and hands each //! request to the window ([`server`]), the client that talks to it ([`client`]), the request the //! window answers ([`ControlRequest`]), the document watch subscribed connections wait on -//! ([`DocumentWatch`]), and what a request still running does when it finishes ([`Effect`]). It +//! ([`DocumentWatch`]), what a request still running does when it finishes ([`Effect`]), and AI +//! agents in the open window behind the ArtCraft Launcher's switch ([`agents`], feature `agents`). It //! needs no UI toolkit; the window's own requests over egui (`ui.screenshot`, `ui.resize`) are //! `craft-control-egui`. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] +pub mod agents; pub mod auth; mod cancel; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/control/tests/agents.rs b/crates/control/tests/agents.rs new file mode 100644 index 000000000..673522a0b --- /dev/null +++ b/crates/control/tests/agents.rs @@ -0,0 +1,428 @@ +//! AI agents in the open window: the launcher's switch, the connection file, and where an app's +//! `-cli mcp` sends each tool call. +// Unwrapping, expecting and panicking on failure is fine in tests, unlike in shipped code. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::net::TcpListener; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use craft_control::agents::{ + AgentSettings, AgentSwitch, CONNECTION_FILE, Connection, Consent, HeadlessFolders, Live, LiveConfig, Route, TOKEN_FILE, WhenAppClosed, Window, + agents_allowed, find_window, read_connection, remove_connection, remove_stale_connection, write_connection, +}; + +fn temp_dir(tag: &str) -> tempfile::TempDir { + tempfile::Builder::new().prefix(&format!("craft-agents-{tag}-")).tempdir().expect("a temp dir") +} + +/// Waits up to five seconds for `done`. +fn wait_for(mut done: impl FnMut() -> bool) -> bool { + let started = Instant::now(); + while !done() { + if started.elapsed() > Duration::from_secs(5) { + return false; + } + std::thread::sleep(Duration::from_millis(5)); + } + true +} + +const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + +/// Writes `text` as an owner-only token file, as an app's own token writer does. +fn write_token(path: &Path, text: &str) { + std::fs::write(path, text).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } +} + +/// An app accepting agents in `dir`: a listener on a free loopback port, its token file and its +/// connection file. Dropping the listener leaves the file behind, as a crashed app would. +fn publish(dir: &Path) -> (TcpListener, Connection) { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + write_token(&dir.join(TOKEN_FILE), &format!("{}\n", TOKEN.to_ascii_uppercase())); + let c = Connection::new(listener.local_addr().unwrap().port(), dir.join(TOKEN_FILE), "Test 1.0"); + write_connection(dir, &c).unwrap(); + (listener, c) +} + +// ---- The launcher's switch ---------------------------------------------------------------------- + +/// With the `AI-MCP` flag only the launcher's switch decides; without it the app's earlier consent. +#[test] +fn with_the_flag_only_the_launchers_switch_lets_agents_in() { + assert!(agents_allowed(false, false, true), "without the flag, the app's earlier consent"); + assert!(!agents_allowed(false, true, false), "the launcher's list means nothing without the flag"); + assert!(agents_allowed(true, true, false)); + assert!(!agents_allowed(true, false, true), "no second switch in the app"); + assert!(AgentSwitch::fixed(true, true).allows(false)); + assert!(!AgentSwitch::fixed(false, true).allows(false)); +} + +/// The switch follows the launcher's list within a poll, wakes the app once per change rather than +/// once per poll, and its thread ends once the last clone is dropped. +#[test] +fn the_switch_wakes_once_per_change() { + let launcher = Arc::new(AtomicBool::new(false)); + let probes = Arc::new(AtomicUsize::new(0)); + let wakes = Arc::new(AtomicUsize::new(0)); + let probe = { + let (launcher, probes) = (launcher.clone(), probes.clone()); + move || { + probes.fetch_add(1, Ordering::Relaxed); + launcher.load(Ordering::Relaxed) + } + }; + let wake = { + let wakes = wakes.clone(); + move || { + wakes.fetch_add(1, Ordering::Relaxed); + } + }; + let switch = AgentSwitch::watch_with(true, probe, Duration::from_millis(5), wake); + let clone = switch.clone(); + assert!(!switch.launcher()); + + launcher.store(true, Ordering::Relaxed); + assert!(wait_for(|| clone.launcher()), "the switch follows the launcher"); + assert!(switch.allows(false)); + let polled = probes.load(Ordering::Relaxed); + assert!(wait_for(|| probes.load(Ordering::Relaxed) > polled + 10)); + launcher.store(false, Ordering::Relaxed); + assert!(wait_for(|| !switch.launcher())); + assert!(wait_for(|| wakes.load(Ordering::Relaxed) == 2)); + assert_eq!(wakes.load(Ordering::Relaxed), 2, "one wake per change, not per poll"); + + drop(switch); + drop(clone); + std::thread::sleep(Duration::from_millis(50)); + let after_drop = probes.load(Ordering::Relaxed); + std::thread::sleep(Duration::from_millis(50)); + assert_eq!(probes.load(Ordering::Relaxed), after_drop, "the watch ended with the last switch"); +} + +// ---- The connection file ------------------------------------------------------------------------ + +/// A published connection reads back in its documented shape, and only the process that wrote it +/// removes it. +#[test] +fn a_published_connection_reads_back_and_only_its_writer_removes_it() { + let dir = temp_dir("conn"); + let dir = dir.path(); + assert_eq!(read_connection(dir).unwrap(), None, "no file"); + let c = Connection::new(7878, dir.join(TOKEN_FILE), "MyApp 1.2.3"); + write_connection(dir, &c).unwrap(); + assert_eq!(read_connection(dir).unwrap(), Some(c.clone())); + assert_eq!(c.addr(), "127.0.0.1:7878"); + let v: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(dir.join(CONNECTION_FILE)).unwrap()).unwrap(); + let mut keys: Vec<_> = v.as_object().unwrap().keys().cloned().collect(); + keys.sort(); + assert_eq!(keys, ["app", "pid", "port", "tokenFile", "version"]); + assert_eq!((v["version"].as_u64(), v["port"].as_u64(), v["app"].as_str()), (Some(1), Some(7878), Some("MyApp 1.2.3"))); + + remove_connection(dir, c.pid.wrapping_add(1)); + assert!(dir.join(CONNECTION_FILE).is_file(), "another process's file stays"); + remove_connection(dir, c.pid); + assert!(!dir.join(CONNECTION_FILE).exists()); +} + +/// A damaged, foreign or port-0 file reads as none; a directory in its place is an error and is +/// left alone; a file nobody listens on is removed as stale and a live one kept. +#[test] +fn a_damaged_foreign_or_stale_connection_file_counts_as_none() { + let dir = temp_dir("bad-conn"); + let dir = dir.path(); + for text in [ + &b""[..], + b"{not json", + b"[]", + br#"{"version":2,"pid":1,"port":7878,"tokenFile":"t","app":"x"}"#, + br#"{"version":1,"pid":1,"port":0,"tokenFile":"t","app":"x"}"#, + b"\xff\xfe not utf-8", + ] { + std::fs::write(dir.join(CONNECTION_FILE), text).unwrap(); + assert_eq!(read_connection(dir).unwrap(), None, "{}", String::from_utf8_lossy(text)); + remove_stale_connection(dir); + assert!(!dir.join(CONNECTION_FILE).exists(), "an unreadable file is not a connection"); + } + + std::fs::create_dir(dir.join(CONNECTION_FILE)).unwrap(); + assert!(read_connection(dir).is_err()); + remove_stale_connection(dir); + assert!(dir.join(CONNECTION_FILE).is_dir(), "anything but a regular file is left alone"); + std::fs::remove_dir(dir.join(CONNECTION_FILE)).unwrap(); + + let live = TcpListener::bind("127.0.0.1:0").unwrap(); + let live_port = live.local_addr().unwrap().port(); + write_connection(dir, &Connection { pid: 1, ..Connection::new(live_port, dir.join(TOKEN_FILE), "x") }).unwrap(); + remove_stale_connection(dir); + assert!(dir.join(CONNECTION_FILE).is_file(), "something listens on {live_port}"); + drop(live); + let closed = TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + write_connection(dir, &Connection { pid: 1, ..Connection::new(closed, dir.join(TOKEN_FILE), "x") }).unwrap(); + remove_stale_connection(dir); + assert!(!dir.join(CONNECTION_FILE).exists(), "nothing listens on {closed}"); +} + +// ---- The CLI's side ----------------------------------------------------------------------------- + +/// What the stand-in app made: a window client (its window) or a headless session (its folders), +/// with counts of each. +#[derive(Default)] +struct Made { + connects: AtomicUsize, + sessions: AtomicUsize, +} + +type TestLive = Live; + +fn config(dir: &Path, consent: Consent, made: &Arc) -> LiveConfig { + let (a, b) = (made.clone(), made.clone()); + let mut cfg = LiveConfig::new( + "Test", + dir.to_path_buf(), + move |_: &Path| consent.clone(), + move |w: &Window| { + a.connects.fetch_add(1, Ordering::Relaxed); + Ok(w.clone()) + }, + move |f: &HeadlessFolders| { + b.sessions.fetch_add(1, Ordering::Relaxed); + Ok(f.clone()) + }, + ); + cfg.poll = Duration::from_millis(5); + cfg +} + +fn settings(when: WhenAppClosed, read: &str, write: &str) -> AgentSettings { + let mut s = AgentSettings::default(); + s.when_app_closed = when; + s.read_root = read.into(); + s.write_root = write.into(); + s +} + +fn allowed(when: WhenAppClosed) -> Consent { + Consent::new(true, settings(when, "/app-in", "/app-out")) +} + +fn headless_folders(route: Result, String>) -> HeadlessFolders { + match route { + Ok(Route::Headless(f)) => f, + Ok(Route::Window(w)) => panic!("expected headless, got the window {w:?}"), + Err(e) => panic!("expected headless, got the error {e}"), + } +} + +fn window(route: Result, String>) -> Window { + match route { + Ok(Route::Window(w)) => w, + Ok(Route::Headless(f)) => panic!("expected the window, went headless with {f:?}"), + Err(e) => panic!("expected the window, got the error {e}"), + } +} + +fn paths(p: &[&str]) -> Vec { + p.iter().map(PathBuf::from).collect() +} + +/// An app accepting agents takes the call; the same port, token and process keep the client, a +/// restarted app (another process on the same port and token) gets a new one. +#[test] +fn an_open_app_takes_the_call_and_keeps_its_client_until_it_restarts() { + let dir = temp_dir("window"); + let (_listener, c) = publish(dir.path()); + let made = Arc::new(Made::default()); + // Even without consent: an app publishes its connection only while it accepts agents. + let live = TestLive::new(config(dir.path(), Consent::default(), &made)); + let w = window(live.resolve()); + assert_eq!((w.port, w.pid, w.token.as_str(), w.addr()), (c.port, c.pid, TOKEN, c.addr()), "the token is trimmed and lower-cased"); + window(live.resolve()); + assert_eq!(made.connects.load(Ordering::Relaxed), 1, "the same window keeps its client"); + assert!(matches!(live.current(), Some(Route::Window(_)))); + + write_connection(dir.path(), &Connection { pid: c.pid.wrapping_add(1), ..c.clone() }).unwrap(); + assert_eq!(window(live.resolve()).pid, c.pid.wrapping_add(1)); + assert_eq!(made.connects.load(Ordering::Relaxed), 2, "a restarted app gets a new client"); + assert_eq!(made.sessions.load(Ordering::Relaxed), 0); +} + +/// No app accepts agents and the person doesn't let them use it: headless with only the command's +/// folders, never the app's. +#[test] +fn without_consent_a_closed_app_runs_headless_with_the_commands_folders_only() { + let dir = temp_dir("no-consent"); + let made = Arc::new(Made::default()); + let consent = Consent::new(false, settings(WhenAppClosed::Launch, "/app-in", "/app-out")); + let live = TestLive::new(config(dir.path(), consent.clone(), &made)); + assert_eq!(headless_folders(live.resolve()), HeadlessFolders::default(), "no folders given, none used"); + + let mut cfg = config(dir.path(), consent, &made); + cfg.read_roots = paths(&["/cli-in"]); + cfg.write_root = Some(PathBuf::from("/cli-out")); + let f = headless_folders(TestLive::new(cfg).resolve()); + assert_eq!((f.read, f.write), (paths(&["/cli-in"]), Some(PathBuf::from("/cli-out")))); +} + +/// Agents allowed, app closed, "headless": the app's agent folders, each replaced by the command's. +#[test] +fn allowed_and_closed_runs_headless_with_the_apps_folders_unless_the_command_gives_its_own() { + let dir = temp_dir("headless"); + let made = Arc::new(Made::default()); + let f = headless_folders(TestLive::new(config(dir.path(), allowed(WhenAppClosed::Headless), &made)).resolve()); + assert_eq!((f.read, f.write), (paths(&["/app-in"]), Some(PathBuf::from("/app-out")))); + + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Headless), &made); + cfg.read_roots = paths(&["/cli-a", "/cli-b"]); + let f = headless_folders(TestLive::new(cfg).resolve()); + assert_eq!((f.read, f.write), (paths(&["/cli-a", "/cli-b"]), Some(PathBuf::from("/app-out")))); + + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Headless), &made); + cfg.write_root = Some(PathBuf::from("/cli-out")); + let f = headless_folders(TestLive::new(cfg).resolve()); + assert_eq!((f.read, f.write), (paths(&["/app-in"]), Some(PathBuf::from("/cli-out")))); +} + +/// Agents allowed, app closed, "error": the call fails with words that name the app; the command's +/// choice wins over the app's. +#[test] +fn the_closed_app_choice_decides_and_the_command_overrides_it() { + let dir = temp_dir("error"); + let made = Arc::new(Made::default()); + let err = TestLive::new(config(dir.path(), allowed(WhenAppClosed::Error), &made)).resolve().err().unwrap(); + assert_eq!(err, "Test isn't running: open it, then try again."); + + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Error), &made); + cfg.when_closed = Some(WhenAppClosed::Headless); + headless_folders(TestLive::new(cfg).resolve()); + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Headless), &made); + cfg.when_closed = Some(WhenAppClosed::Error); + assert!(TestLive::new(cfg).resolve().is_err()); +} + +/// Once headless, the session stays headless even when the app starts, so documents don't move +/// under the agent. +#[test] +fn a_headless_session_stays_headless() { + let dir = temp_dir("sticky"); + let made = Arc::new(Made::default()); + let live = TestLive::new(config(dir.path(), Consent::default(), &made)); + headless_folders(live.resolve()); + let _app = publish(dir.path()); + headless_folders(live.resolve()); + assert_eq!((made.sessions.load(Ordering::Relaxed), made.connects.load(Ordering::Relaxed)), (1, 0), "one session, no window"); +} + +/// A connection file left by an app that crashed counts as a closed app. +#[test] +fn a_crashed_apps_connection_file_counts_as_closed() { + let dir = temp_dir("crashed"); + drop(publish(dir.path()).0); + let made = Arc::new(Made::default()); + headless_folders(TestLive::new(config(dir.path(), Consent::default(), &made)).resolve()); + assert_eq!(find_window(dir.path(), "Test").unwrap(), None); +} + +/// A token file that isn't a token, is too big or is missing fails the call and names the app; +/// nothing is sent to the window. +#[test] +fn a_bad_token_file_fails_the_call() { + let dir = temp_dir("token"); + let (_listener, _c) = publish(dir.path()); + let made = Arc::new(Made::default()); + for bad in ["", " \n", "not a token", &"a".repeat(5000)] { + write_token(&dir.path().join(TOKEN_FILE), bad); + let err = TestLive::new(config(dir.path(), Consent::default(), &made)).resolve().err().unwrap(); + assert!(err.starts_with("Test's agent token: "), "{err}"); + } + std::fs::remove_file(dir.path().join(TOKEN_FILE)).unwrap(); + assert!(find_window(dir.path(), "Test").is_err()); + assert_eq!(made.connects.load(Ordering::Relaxed), 0); +} + +/// The app's own errors reach the agent with what was being done. +#[test] +fn the_apps_errors_reach_the_agent() { + let dir = temp_dir("app-errors"); + let consent = Consent::default(); + let cfg: LiveConfig = LiveConfig::new( + "Test", + dir.path().to_path_buf(), + move |_: &Path| consent.clone(), + |w: &Window| Ok(w.clone()), + |_: &HeadlessFolders| Err("no such folder".into()), + ); + assert_eq!(TestLive::new(cfg).resolve().err().unwrap(), "the automation roots can't be used: no such folder"); + + let (_listener, _c) = publish(dir.path()); + let cfg: LiveConfig = LiveConfig::new( + "Test", + dir.path().to_path_buf(), + |_: &Path| Consent::default(), + |_: &Window| Err("refused".into()), + |f: &HeadlessFolders| Ok(f.clone()), + ); + let live = TestLive::new(cfg); + assert_eq!(live.resolve().err().unwrap(), "refused"); + assert!(live.current().is_none(), "a failed connect leaves no route"); +} + +/// "Launch" without a way to start the app, a start that fails, and an app that never accepts +/// agents each end with words that say what to do. +#[test] +fn a_launch_that_cannot_happen_or_never_finishes_says_what_to_do() { + let dir = temp_dir("launch-fails"); + let made = Arc::new(Made::default()); + let err = TestLive::new(config(dir.path(), allowed(WhenAppClosed::Launch), &made)).resolve().err().unwrap(); + assert_eq!(err, "Test isn't running, and this install can't start it from here: open Test, then try again."); + + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); + cfg.launch = Some(Box::new(|| Err("boom".into()))); + assert_eq!(TestLive::new(cfg).resolve().err().unwrap(), "couldn't start Test: boom"); + + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); + cfg.launch = Some(Box::new(|| Ok(()))); + cfg.launch_timeout = Duration::from_millis(40); + let err = TestLive::new(cfg).resolve().err().unwrap(); + assert!(err.starts_with("Test didn't accept agents within 0 s of starting."), "{err}"); +} + +/// "Launch" starts the app once, also for calls that arrive together, and the calls go to its +/// window once it accepts agents. +#[test] +fn a_started_app_takes_the_call_and_concurrent_calls_start_it_once() { + let dir = temp_dir("launch"); + let made = Arc::new(Made::default()); + let launches = Arc::new(AtomicUsize::new(0)); + let app: Arc>> = Arc::new(Mutex::new(None)); + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); + let (d, n, slot) = (dir.path().to_path_buf(), launches.clone(), app.clone()); + cfg.launch = Some(Box::new(move || { + n.fetch_add(1, Ordering::Relaxed); + let (d, slot) = (d.clone(), slot.clone()); + // The app takes a moment before it accepts agents. + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(60)); + *slot.lock().unwrap() = Some(publish(&d).0); + }); + Ok(()) + })); + let live = Arc::new(TestLive::new(cfg)); + let calls: Vec<_> = (0..4) + .map(|_| { + let live = live.clone(); + std::thread::spawn(move || window(live.resolve())) + }) + .collect(); + let ports: Vec = calls.into_iter().map(|c| c.join().unwrap().port).collect(); + assert_eq!(launches.load(Ordering::Relaxed), 1, "one start for every call"); + assert!(ports.windows(2).all(|p| p[0] == p[1]), "{ports:?}"); + assert_eq!(made.connects.load(Ordering::Relaxed), 1); +}