From 463acfe5bd8ae005159354319312258ece4e3b71 Mon Sep 17 00:00:00 2001 From: aiongg Date: Mon, 16 Nov 2026 12:38:25 +0000 Subject: [PATCH] merge-fwe: FW16 E4: craft_automation::agents: agent settings, the launcher's switch (AgentSwitch) and the connection file --- crates/automation/Cargo.toml | 4 +- crates/automation/src/agents/connection.rs | 117 +++++++++++++++++ crates/automation/src/agents/mod.rs | 42 ++++++ crates/automation/src/agents/settings.rs | 118 +++++++++++++++++ crates/automation/src/agents/switch.rs | 94 +++++++++++++ crates/automation/src/lib.rs | 3 +- crates/automation/tests/it/agents.rs | 146 +++++++++++++++++++++ crates/automation/tests/it/main.rs | 1 + 8 files changed, 522 insertions(+), 3 deletions(-) create mode 100644 crates/automation/src/agents/connection.rs create mode 100644 crates/automation/src/agents/mod.rs create mode 100644 crates/automation/src/agents/settings.rs create mode 100644 crates/automation/src/agents/switch.rs create mode 100644 crates/automation/tests/it/agents.rs diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index c8f74bfba..f82a4c14f 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -22,8 +22,8 @@ default = [] # input) and `ui` stories. Without it the crate has no egui: `ControlOptions`, `ControlClient`, # `Params` and the recorded actions' model and files. ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:egui"] -# The Actions panel's stories and mock, and the integration binary `tests/it`. -screen-testing = ["ui", "craft-ui/testing"] +# The Actions panel's and the Agents page's stories and mock, and the integration binary `tests/it`. +screen-testing = ["ui", "agents", "craft-ui/testing"] # Agents in the open window (desktop): the ArtCraft Launcher's switch, the connection file an # app's `-cli mcp` reads, and with `ui` the link host and the Agents page. The agent settings # build on every target without it. diff --git a/crates/automation/src/agents/connection.rs b/crates/automation/src/agents/connection.rs new file mode 100644 index 000000000..f34ee3c40 --- /dev/null +++ b/crates/automation/src/agents/connection.rs @@ -0,0 +1,117 @@ +//! 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}; + +use crate::AutomationError; + +/// 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) -> AutomationError { + AutomationError::Io(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) -> Result<(), AutomationError> { + 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) -> Result, AutomationError> { + 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/automation/src/agents/mod.rs b/crates/automation/src/agents/mod.rs new file mode 100644 index 000000000..11366be2b --- /dev/null +++ b/crates/automation/src/agents/mod.rs @@ -0,0 +1,42 @@ +//! AI agents in the open window: whether the person lets agents use the app, and how an agent's +//! client finds the app's control server without being told. +//! +//! 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`]). +//! +//! While agents may connect, the app serves its control channel on loopback ([`AgentLink`], over +//! [`crate::server`]) and publishes where in its settings folder ([`CONNECTION_FILE`]): the port, +//! its process id and the token file ([`TOKEN_FILE`], created `0600` on Unix). The app's +//! `-cli mcp` reads that file on every tool call, then the token from the file it names, so an +//! MCP client's configuration never holds a port or a token. +//! +//! The file holds no secret. A crashed (or, on macOS, quit) app can leave it behind; nothing then +//! listens on its port ([`probe`]), and the app's next launch removes it +//! ([`remove_stale_connection`]). Until then another program could take that port, so a client +//! checks that [`Connection::pid`] is still running before it sends anything derived from the +//! token, and authenticates with the challenge handshake ([`crate::security::ServerHandshake`]). +//! +//! | 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 link host | [`AgentLink`], [`AgentLinkStatus`], [`LinkProblem`], [`LinkUpdate`] | desktop, features `agents` and `ui` | +//! +//! The Agents page of Preferences is [`crate::ui::agents`]. + +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 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 switch::{AgentSwitch, POLL, launcher_allows, mcp_flag}; diff --git a/crates/automation/src/agents/settings.rs b/crates/automation/src/agents/settings.rs new file mode 100644 index 000000000..a2e9c9a32 --- /dev/null +++ b/crates/automation/src/agents/settings.rs @@ -0,0 +1,118 @@ +//! 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 { + use super::*; + use craft_ui::testing::trial; + + // The saved names read back as the same choice, and nothing else reads as one. + #[trial] + 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. + #[trial] + 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/automation/src/agents/switch.rs b/crates/automation/src/agents/switch.rs new file mode 100644 index 000000000..28af63d83 --- /dev/null +++ b/crates/automation/src/agents/switch.rs @@ -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 craft_host::Wake; + +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`. + /// Without the `AI-MCP` flag nothing is watched: the launcher's list means nothing then. + pub fn watch(app_id: &'static str, wake: Wake) -> 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: Wake) -> 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.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/automation/src/lib.rs b/crates/automation/src/lib.rs index 9d1f8fea9..52e967ead 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -3,7 +3,7 @@ //! Drive a running Craft app from tests, agents and the CLI, and record and play actions. //! //! [`actions`] and [`ui::actions`] build on every target: the recorded-action list, its player -//! and the Actions panel. The rest is desktop only. +//! and the Actions panel; so do the agent settings in [`agents`]. The rest is desktop only. //! //! A transport thread ([`server`], or a channel in tests) turns each JSON line into a //! [`control::ControlRequest`]; the UI thread drains them between frames through @@ -17,6 +17,7 @@ #![warn(missing_docs)] pub mod actions; +pub mod agents; #[cfg(feature = "ui")] pub mod ui; diff --git a/crates/automation/tests/it/agents.rs b/crates/automation/tests/it/agents.rs new file mode 100644 index 000000000..b0392dd49 --- /dev/null +++ b/crates/automation/tests/it/agents.rs @@ -0,0 +1,146 @@ +//! Agents in the open window: the launcher's switch, the connection file, the link host and the +//! Agents page. + +use std::net::TcpListener; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::time::Duration; + +use craft_automation::agents::{ + AgentSwitch, CONNECTION_FILE, Connection, TOKEN_FILE, agents_allowed, read_connection, remove_connection, remove_stale_connection, + write_connection, +}; +use craft_host::Wake; +use craft_ui::runtime::motion; +use craft_ui::testing::trial; + +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 = motion::now(); + while !done() { + if started.elapsed() > Duration::from_secs(5) { + return false; + } + std::thread::sleep(Duration::from_millis(5)); + } + true +} + +/// With the `AI-MCP` flag only the launcher's switch decides; without it the app's earlier consent. +#[trial] +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. +#[trial] +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(); + Wake::new(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)); + // Many polls with nothing changed. + 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); + // The thread sees the switch gone at its next poll and stops probing. + 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"); +} + +/// A published connection reads back in its documented shape, and only the process that wrote it removes it. +#[trial] +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. +#[trial] +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}"); +} diff --git a/crates/automation/tests/it/main.rs b/crates/automation/tests/it/main.rs index 4aa0f596c..89d9855b2 100644 --- a/crates/automation/tests/it/main.rs +++ b/crates/automation/tests/it/main.rs @@ -3,6 +3,7 @@ #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] mod actions; +mod agents; mod control; mod dialogs; mod screenshot;