mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-18 16:24:38 +00:00
Merge pull request #2142 from davidmann4/agents-live-client
MCP move shared code from PhotoCraft to craft-libs (#2141)
This commit is contained in:
10 files changed
+1621
-1
No files matched your search
Generated
+15
@@ -1568,6 +1568,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"
|
||||
@@ -1686,10 +1696,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]]
|
||||
|
||||
@@ -59,6 +59,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" }
|
||||
|
||||
@@ -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 `<id>-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"]
|
||||
@@ -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<String>) -> Self {
|
||||
Self { version: CONNECTION_VERSION, pid: std::process::id(), port, token_file, app: app.into() }
|
||||
}
|
||||
|
||||
/// `127.0.0.1:<port>`.
|
||||
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<Option<Connection>> {
|
||||
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::<Connection>(&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()
|
||||
}
|
||||
@@ -0,0 +1,601 @@
|
||||
//! The other end of the link: where an app's `<id>-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 ([`Consent::allowed`] off, or
|
||||
//! [`AgentSettings::allow_agent_control`] off, under which the app doesn't listen either): 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. Only a session
|
||||
//! made with the app's agent folders ends when the person stops letting agents in; the next call
|
||||
//! gets one with the command's folders. A window route is dropped as soon as no app accepts agents.
|
||||
//! Lookups are
|
||||
//! serialised, so concurrent calls start the app once: calls that queued while a start was under
|
||||
//! way and found no window get that start's error rather than starting the app again; a call made
|
||||
//! after it tries again.
|
||||
//!
|
||||
//! 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::atomic::{AtomicU64, Ordering};
|
||||
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<dyn Fn() -> Result<(), String> + Send + Sync>;
|
||||
/// What the person allows now, read from the app's settings folder before every call.
|
||||
pub type ConsentFn = Box<dyn Fn(&Path) -> Consent + Send + Sync>;
|
||||
/// Makes the app's client for its open window.
|
||||
pub type ConnectFn<W> = Box<dyn Fn(&Window) -> Result<W, String> + Send + Sync>;
|
||||
/// Makes the app's headless session with these folders.
|
||||
pub type HeadlessFn<H> = Box<dyn Fn(&HeadlessFolders) -> Result<H, String> + 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 longest [`LiveConfig::launch_timeout`] used; a longer one is cut to this.
|
||||
const MAX_LAUNCH_TIMEOUT: Duration = Duration::from_secs(600);
|
||||
/// The range [`LiveConfig::poll`] is kept in.
|
||||
const POLL_RANGE: (Duration, Duration) = (Duration::from_millis(1), Duration::from_secs(1));
|
||||
|
||||
/// 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, as its token file holds it (trimmed).
|
||||
pub token: String,
|
||||
}
|
||||
|
||||
impl Window {
|
||||
/// `127.0.0.1:<port>`.
|
||||
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: `agents_allowed(mcp_flag(), launcher_allows("<id>"), legacy)`
|
||||
/// ([`super::agents_allowed`]), with the suite's `AI-MCP` flag the ArtCraft Launcher's switch.
|
||||
/// [`Live`] also requires [`AgentSettings::allow_agent_control`].
|
||||
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<PathBuf>,
|
||||
/// The folder files may be saved to.
|
||||
pub write: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// Where a tool call goes: the app's window client or its headless session.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Route<W, H> {
|
||||
/// The open window.
|
||||
Window(W),
|
||||
/// A session without a window.
|
||||
Headless(H),
|
||||
}
|
||||
|
||||
/// What [`Live`] needs from the app.
|
||||
#[non_exhaustive]
|
||||
pub struct LiveConfig<W, H> {
|
||||
/// 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<WhenAppClosed>,
|
||||
/// 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<PathBuf>,
|
||||
/// 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<PathBuf>,
|
||||
/// Starts the app; `None` when this install can't ([`launcher`] found nothing to start).
|
||||
pub launch: Option<LaunchFn>,
|
||||
/// How long a started app gets to accept agents ([`LAUNCH_TIMEOUT`]; at most 10 minutes).
|
||||
pub launch_timeout: Duration,
|
||||
/// How often a starting app is looked for ([`LAUNCH_POLL`]; kept between 1 ms and 1 s).
|
||||
pub poll: Duration,
|
||||
consent: ConsentFn,
|
||||
connect: ConnectFn<W>,
|
||||
headless: HeadlessFn<H>,
|
||||
}
|
||||
|
||||
impl<W, H> LiveConfig<W, H> {
|
||||
/// 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<String>,
|
||||
config_dir: PathBuf,
|
||||
consent: impl Fn(&Path) -> Consent + Send + Sync + 'static,
|
||||
connect: impl Fn(&Window) -> Result<W, String> + Send + Sync + 'static,
|
||||
headless: impl Fn(&HeadlessFolders) -> Result<H, String> + 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 route the last call took.
|
||||
struct Current<W, H> {
|
||||
route: Route<W, H>,
|
||||
/// For a window, the key its client was made for.
|
||||
key: Option<WindowKey>,
|
||||
/// A headless session that holds folders of the app's agent settings: it lasts only while
|
||||
/// the person lets agents in.
|
||||
app_folders: bool,
|
||||
}
|
||||
|
||||
/// Resolves each tool call of one MCP session; see the module docs.
|
||||
pub struct Live<W, H> {
|
||||
cfg: LiveConfig<W, H>,
|
||||
/// Serialises lookups, so concurrent calls start the app once; holds the last start's error.
|
||||
lookup: Mutex<Option<String>>,
|
||||
/// How many starts have finished, read before a call queues for `lookup`.
|
||||
finished: AtomicU64,
|
||||
current: Mutex<Option<Current<W, H>>>,
|
||||
}
|
||||
|
||||
impl<W: Clone, H: Clone> Live<W, H> {
|
||||
/// A session that has not resolved anything yet.
|
||||
pub fn new(cfg: LiveConfig<W, H>) -> Self {
|
||||
Self { cfg, lookup: Mutex::new(None), finished: AtomicU64::new(0), current: Mutex::new(None) }
|
||||
}
|
||||
|
||||
/// The route the last [`Self::resolve`] chose, if any.
|
||||
pub fn current(&self) -> Option<Route<W, H>> {
|
||||
self.current.lock().unwrap_or_else(PoisonError::into_inner).as_ref().map(|c| c.route.clone())
|
||||
}
|
||||
|
||||
fn set(&self, route: Route<W, H>, key: Option<WindowKey>, app_folders: bool) -> Route<W, H> {
|
||||
*self.current.lock().unwrap_or_else(PoisonError::into_inner) = Some(Current { route: route.clone(), key, app_folders });
|
||||
route
|
||||
}
|
||||
|
||||
/// The headless session to keep using, if any: one made with the app's folders only while
|
||||
/// agents are still `allowed`. A route that may not be kept is dropped.
|
||||
fn sticky_headless(&self, allowed: bool) -> Option<Route<W, H>> {
|
||||
let mut current = self.current.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
match current.as_ref() {
|
||||
Some(c) if matches!(c.route, Route::Headless(_)) && (allowed || !c.app_folders) => Some(c.route.clone()),
|
||||
Some(c) if matches!(c.route, Route::Headless(_)) => {
|
||||
*current = None;
|
||||
None
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Forgets a window route: no app accepts agents any more, so its client is for a socket
|
||||
/// that is gone.
|
||||
fn drop_window(&self) {
|
||||
let mut current = self.current.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if current.as_ref().is_some_and(|c| matches!(c.route, Route::Window(_))) {
|
||||
*current = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the next tool call goes. Blocks; see the module docs. The error is the tool call's
|
||||
/// result.
|
||||
pub fn resolve(&self) -> Result<Route<W, H>, String> {
|
||||
let queued_at = self.finished.load(Ordering::Acquire);
|
||||
let mut last_failure = self.lookup.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let consent = (self.cfg.consent)(&self.cfg.config_dir);
|
||||
// Allow Agent Control off refuses agents, as the app does: it doesn't listen then.
|
||||
let allowed = consent.allowed && consent.settings.allow_agent_control;
|
||||
if let Some(route) = self.sticky_headless(allowed) {
|
||||
return Ok(route);
|
||||
}
|
||||
if let Some(window) = self.find_app()? {
|
||||
return self.use_window(window);
|
||||
}
|
||||
self.drop_window();
|
||||
let app = &self.cfg.app_name;
|
||||
if !allowed {
|
||||
let folders = HeadlessFolders { read: self.cfg.read_roots.clone(), write: self.cfg.write_root.clone() };
|
||||
return self.headless(&folders, false, &format!("{app} can't use the automation roots"));
|
||||
}
|
||||
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 app_read = self.cfg.read_roots.is_empty() && consent.settings.read_folder().is_some();
|
||||
let app_write = self.cfg.write_root.is_none() && consent.settings.write_folder().is_some();
|
||||
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());
|
||||
let why = format!("{app} isn't running and its agent folders can't be used");
|
||||
self.headless(&HeadlessFolders { read, write }, app_read || app_write, &why)
|
||||
}
|
||||
WhenAppClosed::Launch => {
|
||||
// A start finished while this call waited and the app still isn't there: its answer
|
||||
// is this call's too, rather than a second start of an app that may be opening.
|
||||
if self.finished.load(Ordering::Acquire) != queued_at
|
||||
&& let Some(failure) = last_failure.as_ref()
|
||||
{
|
||||
return Err(failure.clone());
|
||||
}
|
||||
let started = self.launch_and_wait();
|
||||
*last_failure = started.as_ref().err().cloned();
|
||||
self.finished.fetch_add(1, Ordering::AcqRel);
|
||||
started
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A headless session with `folders` from now on; `app_folders` when some of them are the
|
||||
/// app's agent folders. `why` leads its error.
|
||||
fn headless(&self, folders: &HeadlessFolders, app_folders: bool, why: &str) -> Result<Route<W, H>, String> {
|
||||
let session = (self.cfg.headless)(folders).map_err(|e| format!("{why}: {e}"))?;
|
||||
Ok(self.set(Route::Headless(session), None, app_folders))
|
||||
}
|
||||
|
||||
/// Starts the app and waits until it accepts agents, at most the launch timeout.
|
||||
fn launch_and_wait(&self) -> Result<Route<W, H>, 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 timeout = self.cfg.launch_timeout.min(MAX_LAUNCH_TIMEOUT);
|
||||
let started = Instant::now();
|
||||
let deadline = started.checked_add(timeout).unwrap_or(started);
|
||||
let poll = self.cfg.poll.clamp(POLL_RANGE.0, POLL_RANGE.1);
|
||||
loop {
|
||||
std::thread::sleep(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.",
|
||||
timeout.as_secs()
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The client for `window`: the one made for the same port, token and process, or a new one.
|
||||
fn use_window(&self, window: Window) -> Result<Route<W, H>, 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(c) = current.as_ref()
|
||||
&& c.key.as_ref() == Some(&key)
|
||||
{
|
||||
return Ok(c.route.clone());
|
||||
}
|
||||
}
|
||||
let client = (self.cfg.connect)(&window).map_err(|e| format!("couldn't reach {}'s window: {e}", self.cfg.app_name))?;
|
||||
Ok(self.set(Route::Window(client), Some(key), false))
|
||||
}
|
||||
|
||||
/// 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<Option<Window>, 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<Option<Window>, String> {
|
||||
let Some(c): Option<Connection> = 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 and otherwise as written: the app's server
|
||||
/// compares it exactly ([`crate::auth::tokens_match`]). The file must be a regular file of at most
|
||||
/// [`MAX_TOKEN_FILE`] bytes holding one token (no spaces or control characters in it), and on Unix
|
||||
/// readable by its owner only: a token others could read is refused rather than used.
|
||||
fn read_token(path: &Path) -> Result<String, String> {
|
||||
use std::io::Read;
|
||||
let shown = |e: &dyn fmt::Display| format!("{}: {e}", path.display());
|
||||
// Before opening: opening a FIFO for reading blocks until something writes to it.
|
||||
if !std::fs::metadata(path).map_err(|e| shown(&e))?.is_file() {
|
||||
return Err(shown(&"not a regular file"));
|
||||
}
|
||||
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.chars().any(|c| c.is_whitespace() || c.is_control()) {
|
||||
return Err(shown(&"not a control token"));
|
||||
}
|
||||
Ok(token.to_owned())
|
||||
}
|
||||
|
||||
/// 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<LaunchFn> {
|
||||
use std::process::{Command, Stdio};
|
||||
let env = |name: &str| std::env::var_os(name).filter(|v| !v.is_empty());
|
||||
// Both sides resolved, so a mount reached through a symlink (`$TMPDIR`) still matches.
|
||||
let resolved = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
|
||||
let install = Install {
|
||||
platform: Platform::current(),
|
||||
flatpak: env("FLATPAK_ID").is_some(),
|
||||
appimage: env("APPIMAGE"),
|
||||
appdir: env("APPDIR").map(|d| resolved(Path::new(&d)).into_os_string()),
|
||||
system_root: env("SystemRoot"),
|
||||
};
|
||||
let (program, args) = launch_command(&resolved(cli), exe, &install, &|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);
|
||||
let child = c.spawn().map_err(|e| e.to_string())?;
|
||||
reap(child);
|
||||
Ok(())
|
||||
}))
|
||||
}
|
||||
|
||||
/// Waits for `child` on a thread of its own, so a start helper that exits (`open`, Explorer) or an
|
||||
/// app that quits before the CLI does is reaped rather than left a zombie until the MCP client
|
||||
/// ends; the app keeps running on its own either way. Without a thread the child is dropped, as
|
||||
/// before.
|
||||
fn reap(mut child: std::process::Child) {
|
||||
let _ = std::thread::Builder::new().name("app-start-reaper".into()).spawn(move || {
|
||||
let _ = child.wait();
|
||||
});
|
||||
}
|
||||
|
||||
/// What [`launch_command`] needs to know about the install, from the environment.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct Install {
|
||||
platform: Platform,
|
||||
/// Inside a Flatpak (`FLATPAK_ID`).
|
||||
flatpak: bool,
|
||||
/// The AppImage the running image set (`APPIMAGE`).
|
||||
appimage: Option<OsString>,
|
||||
/// That image's mount point (`APPDIR`).
|
||||
appdir: Option<OsString>,
|
||||
/// `%SystemRoot%` (Windows).
|
||||
system_root: Option<OsString>,
|
||||
}
|
||||
|
||||
/// The platform [`launch_command`] plans for.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
enum Platform {
|
||||
Windows,
|
||||
MacOs,
|
||||
#[default]
|
||||
Other,
|
||||
}
|
||||
|
||||
impl Platform {
|
||||
/// The platform this build runs on.
|
||||
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, install: &Install, is_file: &dyn Fn(&Path) -> bool) -> Option<(PathBuf, Vec<OsString>)> {
|
||||
let platform = install.platform;
|
||||
if install.flatpak {
|
||||
return None;
|
||||
}
|
||||
// Only when this CLI runs from that image's mount: a process started from another AppImage
|
||||
// (an MCP client packaged as one) inherits its `APPIMAGE` too.
|
||||
if let (Some(image), Some(mount)) = (&install.appimage, &install.appdir)
|
||||
&& cli.starts_with(mount)
|
||||
{
|
||||
// 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, install.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<OsString>) {
|
||||
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<OsString>)> {
|
||||
// An AppImage's mount is where its CLI runs from.
|
||||
let appdir = appimage.map(|_| OsString::from("/tmp/.mount"));
|
||||
let install = Install { platform, flatpak, appimage: appimage.map(OsString::from), appdir, system_root: root.map(OsString::from) };
|
||||
launch_command(Path::new(cli), "photocraft", &install, &|_| 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()))
|
||||
);
|
||||
// Another AppImage's variables (an MCP client packaged as one): the app beside the CLI.
|
||||
let client = plan("/opt/pc/photocraft-cli", Platform::Other, false, Some("/home/a/Client.AppImage"), None, true);
|
||||
assert_eq!(client, Some((PathBuf::from("/opt/pc/photocraft"), Vec::new())));
|
||||
let no_mount = Install { appimage: Some("/home/a/P.AppImage".into()), ..Install::default() };
|
||||
assert_eq!(
|
||||
launch_command(Path::new("/tmp/.mount/usr/bin/photocraft-cli"), "photocraft", &no_mount, &|_| false),
|
||||
None,
|
||||
"APPIMAGE without APPDIR"
|
||||
);
|
||||
// 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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
//! AI agents in the open window, with no UI toolkit: whether the person lets agents use the app,
|
||||
//! how the app tells its own `<id>-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 `<id>-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`]). An app that quits removes its own ([`remove_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. Agents may connect while `settings.allow_agent_control && switch.allows(legacy)`
|
||||
//! ([`AgentSettings::allow_agent_control`], [`AgentSwitch::allows`]); check it again when the
|
||||
//! launcher's switch wakes the app and when the person changes the setting. When it turns true,
|
||||
//! 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 turns false, and when the app quits, stop listening and [`remove_connection`] with
|
||||
//! the app's process id. No restart, no agents switch of its own. There is one connection file
|
||||
//! per settings folder: an app that runs more than one process on one folder lets only one of
|
||||
//! them accept agents.
|
||||
//!
|
||||
//! Its `gridcraft-cli mcp`:
|
||||
//!
|
||||
//! 1. A [`LiveConfig`] with the app's settings folder; `consent` reads its saved
|
||||
//! [`AgentSettings`] and answers `agents_allowed(mcp_flag(), launcher_allows("gridcraft"), legacy)`
|
||||
//! ([`agents_allowed`], [`mcp_flag`], [`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};
|
||||
@@ -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 `<id>-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<PathBuf> {
|
||||
folder(&self.read_root)
|
||||
}
|
||||
|
||||
/// [`Self::write_root`] as a path ([`folder`]).
|
||||
pub fn write_folder(&self) -> Option<PathBuf> {
|
||||
folder(&self.write_root)
|
||||
}
|
||||
}
|
||||
|
||||
/// A folder setting as a path, trimmed; empty or blank is `None`.
|
||||
pub fn folder(pref: &str) -> Option<PathBuf> {
|
||||
let pref = pref.trim();
|
||||
(!pref.is_empty()).then(|| PathBuf::from(pref))
|
||||
}
|
||||
|
||||
/// What an app's `<id>-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> {
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
//! 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<AtomicBool>,
|
||||
}
|
||||
|
||||
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<AtomicBool> = 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 a later "off" in the launcher would never be seen: agents stay out.
|
||||
if let Err(e) = started {
|
||||
log::warn!("couldn't watch the ArtCraft Launcher's agents switch, so agents stay off: {e}");
|
||||
on.store(false, Ordering::Relaxed);
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,15 @@
|
||||
//! 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`]: its settings on
|
||||
//! every target, the switch, the connection file and the CLI's side with 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"))]
|
||||
|
||||
@@ -0,0 +1,572 @@
|
||||
//! AI agents in the open window: the launcher's switch, the connection file, and where an app's
|
||||
//! `<id>-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));
|
||||
// Held by the watch thread through its probe: gone once the thread has ended.
|
||||
let alive = Arc::new(());
|
||||
let probe = {
|
||||
let (launcher, probes, alive) = (launcher.clone(), probes.clone(), alive.clone());
|
||||
move || {
|
||||
let _ = &alive;
|
||||
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);
|
||||
assert!(wait_for(|| Arc::strong_count(&alive) == 1), "the watch ended with the last switch");
|
||||
let after_end = probes.load(Ordering::Relaxed);
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
assert_eq!(probes.load(Ordering::Relaxed), after_end, "nothing probes after the watch ended");
|
||||
}
|
||||
|
||||
// ---- 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<Window, HeadlessFolders>;
|
||||
|
||||
fn config(dir: &Path, consent: Consent, made: &Arc<Made>) -> LiveConfig<Window, HeadlessFolders> {
|
||||
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<Route<Window, HeadlessFolders>, 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<Route<Window, HeadlessFolders>, 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<PathBuf> {
|
||||
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.to_ascii_uppercase().as_str(), c.addr()),
|
||||
"the token is trimmed, otherwise as written"
|
||||
);
|
||||
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, is missing, isn't a regular file or (on Unix)
|
||||
/// others can read 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}");
|
||||
}
|
||||
// Any token the app's server accepts is passed on: upper case, dashes.
|
||||
write_token(&dir.path().join(TOKEN_FILE), "AB12-cd34-EF56-0000-1111-2222-3333-4444");
|
||||
assert_eq!(find_window(dir.path(), "Test").unwrap().unwrap().token, "AB12-cd34-EF56-0000-1111-2222-3333-4444");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let token = dir.path().join(TOKEN_FILE);
|
||||
write_token(&token, TOKEN);
|
||||
std::fs::set_permissions(&token, std::fs::Permissions::from_mode(0o644)).unwrap();
|
||||
let err = find_window(dir.path(), "Test").err().unwrap();
|
||||
assert!(err.contains("readable by group or others"), "{err}");
|
||||
// A FIFO would block a plain open until something writes to it.
|
||||
std::fs::remove_file(&token).unwrap();
|
||||
assert!(std::process::Command::new("mkfifo").arg(&token).status().unwrap().success());
|
||||
let err = find_window(dir.path(), "Test").err().unwrap();
|
||||
assert!(err.contains("not a regular file"), "{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<Window, HeadlessFolders> = 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(), "Test can't use the automation roots: no such folder");
|
||||
|
||||
let (_listener, _c) = publish(dir.path());
|
||||
let cfg: LiveConfig<Window, HeadlessFolders> = 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(), "couldn't reach Test's window: 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<Mutex<Option<TcpListener>>> = 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<u16> = 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);
|
||||
}
|
||||
|
||||
/// Calls that queued while a start was under way get its error when the app still isn't there,
|
||||
/// rather than starting it again; a call made afterwards tries again.
|
||||
#[test]
|
||||
fn calls_queued_behind_a_failed_start_share_its_error() {
|
||||
let dir = temp_dir("launch-shared");
|
||||
let made = Arc::new(Made::default());
|
||||
let launches = Arc::new(AtomicUsize::new(0));
|
||||
let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made);
|
||||
let entered = Arc::new(AtomicUsize::new(0));
|
||||
let (n, e) = (launches.clone(), entered.clone());
|
||||
// The app is started but never accepts agents within the timeout. The start waits until every
|
||||
// call is under way and then a while longer, so a call that hasn't reached its lookup by the
|
||||
// time the start ends is very unlikely (there is no hook between the two).
|
||||
cfg.launch = Some(Box::new(move || {
|
||||
n.fetch_add(1, Ordering::Relaxed);
|
||||
assert!(wait_for(|| e.load(Ordering::Relaxed) == 4), "every call starts");
|
||||
std::thread::sleep(Duration::from_millis(250));
|
||||
Ok(())
|
||||
}));
|
||||
cfg.launch_timeout = Duration::from_millis(150);
|
||||
let live = Arc::new(TestLive::new(cfg));
|
||||
let calls: Vec<_> = (0..4)
|
||||
.map(|_| {
|
||||
let (live, entered) = (live.clone(), entered.clone());
|
||||
std::thread::spawn(move || {
|
||||
entered.fetch_add(1, Ordering::Relaxed);
|
||||
live.resolve()
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let answers: Vec<_> = calls.into_iter().map(|c| c.join().unwrap()).collect();
|
||||
assert_eq!(launches.load(Ordering::Relaxed), 1, "one start for the calls that came together");
|
||||
for answer in &answers {
|
||||
let err = answer.as_ref().err().unwrap();
|
||||
assert!(err.starts_with("Test didn't accept agents within"), "{err}");
|
||||
}
|
||||
assert!(live.resolve().is_err());
|
||||
assert_eq!(launches.load(Ordering::Relaxed), 2, "a later call starts the app again");
|
||||
}
|
||||
|
||||
/// Allow Agent Control off refuses agents on the CLI's side too, as the app does by not
|
||||
/// listening: no start, and only the command's folders.
|
||||
#[test]
|
||||
fn allow_agent_control_off_counts_as_not_allowed() {
|
||||
let dir = temp_dir("aac-off");
|
||||
let made = Arc::new(Made::default());
|
||||
let mut s = settings(WhenAppClosed::Launch, "/app-in", "/app-out");
|
||||
s.allow_agent_control = false;
|
||||
let mut cfg = config(dir.path(), Consent::new(true, s), &made);
|
||||
cfg.launch = Some(Box::new(|| panic!("nothing may start the app")));
|
||||
cfg.read_roots = paths(&["/cli-in"]);
|
||||
let f = headless_folders(TestLive::new(cfg).resolve());
|
||||
assert_eq!((f.read, f.write), (paths(&["/cli-in"]), None));
|
||||
}
|
||||
|
||||
/// A window route is dropped once no app accepts agents, so a dead client isn't kept or handed
|
||||
/// back.
|
||||
#[test]
|
||||
fn a_window_that_went_away_is_forgotten() {
|
||||
let dir = temp_dir("gone");
|
||||
let made = Arc::new(Made::default());
|
||||
let live = TestLive::new(config(dir.path(), allowed(WhenAppClosed::Error), &made));
|
||||
let (listener, c) = publish(dir.path());
|
||||
window(live.resolve());
|
||||
drop(listener);
|
||||
remove_connection(dir.path(), c.pid);
|
||||
assert!(live.resolve().is_err(), "the app is closed and the choice is an error");
|
||||
assert!(live.current().is_none(), "the dead window is gone");
|
||||
}
|
||||
|
||||
/// A headless session with the app's agent folders ends when the person stops letting agents in;
|
||||
/// one with only the command's folders stays.
|
||||
#[test]
|
||||
fn a_headless_session_with_the_apps_folders_ends_with_consent() {
|
||||
let dir = temp_dir("revoke");
|
||||
let made = Arc::new(Made::default());
|
||||
let on = Arc::new(AtomicBool::new(true));
|
||||
let gate = on.clone();
|
||||
let (b, c) = (made.clone(), made.clone());
|
||||
let cfg: LiveConfig<Window, HeadlessFolders> = LiveConfig::new(
|
||||
"Test",
|
||||
dir.path().to_path_buf(),
|
||||
move |_: &Path| Consent::new(gate.load(Ordering::Relaxed), settings(WhenAppClosed::Headless, "/app-in", "/app-out")),
|
||||
move |w: &Window| {
|
||||
b.connects.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(w.clone())
|
||||
},
|
||||
move |f: &HeadlessFolders| {
|
||||
c.sessions.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(f.clone())
|
||||
},
|
||||
);
|
||||
let live = TestLive::new(cfg);
|
||||
assert_eq!(headless_folders(live.resolve()).read, paths(&["/app-in"]));
|
||||
on.store(false, Ordering::Relaxed);
|
||||
assert_eq!(headless_folders(live.resolve()), HeadlessFolders::default(), "the app's folders went with the consent");
|
||||
on.store(true, Ordering::Relaxed);
|
||||
assert_eq!(headless_folders(live.resolve()), HeadlessFolders::default(), "a session without the app's folders stays");
|
||||
assert_eq!(made.sessions.load(Ordering::Relaxed), 2);
|
||||
}
|
||||
|
||||
/// A huge launch timeout or poll is cut down rather than overflowing the deadline or blocking.
|
||||
#[test]
|
||||
fn a_huge_launch_timeout_or_poll_neither_panics_nor_hangs() {
|
||||
let dir = temp_dir("huge");
|
||||
let made = Arc::new(Made::default());
|
||||
let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made);
|
||||
let (d, app) = (dir.path().to_path_buf(), Arc::new(Mutex::new(None)));
|
||||
let slot = app.clone();
|
||||
cfg.launch = Some(Box::new(move || {
|
||||
*slot.lock().unwrap() = Some(publish(&d).0);
|
||||
Ok(())
|
||||
}));
|
||||
cfg.launch_timeout = Duration::MAX;
|
||||
cfg.poll = Duration::MAX;
|
||||
let started = Instant::now();
|
||||
window(TestLive::new(cfg).resolve());
|
||||
assert!(started.elapsed() < Duration::from_secs(5), "{:?}", started.elapsed());
|
||||
}
|
||||
Reference in new issue
Block a user