Computer use CLI for AI agents
Rust accessibilityaccessibility-apiai-agentsautomationclicomputer-usecomputer-use-agentcomputer-use-agentsdesktop-automationmacosmcprust
fix: remove the macOS command host (#414)
Lahfir7b69db72ee7f
diff --git a/AGENTS.md b/AGENTS.mdindex e308f260a..7b2df100a 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -90,7 +90,7 @@ crates/macos/ agent-desktop-macos: AX APIcrates/windows/ agent-desktop-windows: UI Automationcrates/linux/ agent-desktop-linux: AT-SPIcrates/ffi/ agent-desktop-ffi: cdylib and the committed C header include/agent_desktop.h-src/ agent-desktop binary: cli/, cli_args/, dispatch/, batch/, command_policy/, command_host/,+src/ agent-desktop binary: cli/, cli_args/, dispatch/, batch/, command_policy/,diagnostic/, visual_debug/skills/ agent skills, compiled into the binarytests/ golden fixtures, E2E harness per OS, FFI smoke testsdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 463425eba..d721f35e8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,16 @@# Changelog+## Unreleased++### Bug Fixes++* Remove the macOS command host. Every CLI call runs in its own process, as on Windows and Linux. The npm install and every CLI call stop any command host an earlier version left running. After an install that skips npm scripts, or a manual install, run `agent-desktop version` once.+* Refs from snapshots taken before this release return `STALE_REF`. Take a new snapshot.++### Known Limitations++* On macOS, a ref to a row in a list whose rows share an accessibility identifier can act on another row after the list changes. Take a new snapshot after the list changes.+## [1.0.2](https://github.com/vercel-labs/agent-desktop/compare/v1.0.1...v1.0.2) (2026-10-30)### Featuresdiff --git a/Cargo.lock b/Cargo.lockindex 3135275a4..432d1d680 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -27,7 +27,6 @@ dependencies = ["agent-desktop-windows","base64","clap",- "libc","serde","serde_json","thiserror",diff --git a/README.md b/README.mdindex 3c41e4fc2..5e2c93844 100644--- a/README.md+++ b/README.md@@ -11,7 +11,7 @@ Computer use for AI agents: read and operate desktop apps through the OS accessiA CLI and C library for macOS, Windows and Linux. A snapshot returns JSON with a ref for every element an agent can act on. The agent acts on a ref and snapshots again to check, with no pixel matching; the loop stays in your agent.-On macOS, CLI calls reuse a private command host for each snapshot namespace and binary build. It retains native accessibility objects so a removed row cannot silently resolve to a surviving row with the same identifier. The host exits after 15 idle minutes. `TMPDIR` must be owned by the current user with mode `0700`; the standard macOS per-user temporary directory satisfies this requirement. Headless calls still prohibit foreground activation and synthesized input.+Every CLI call runs in its own process. Headless calls still prohibit foreground activation and synthesized input.Snapshots, clipboard reads, screenshots, command output and debug artifacts can contain private desktop content. Keep them out of public logs and uploads. The optional [JEV helper](skills/jev-desktop/SKILL.md) sends screen descriptions to a configured model provider; it is separate from the native CLI. See [privacy and data handling](docs/faq.md#what-data-can-contain-private-information).diff --git a/crates/core/src/context/mod.rs b/crates/core/src/context/mod.rsindex 66dbac8ba..6f01209ed 100644--- a/crates/core/src/context/mod.rs+++ b/crates/core/src/context/mod.rs@@ -20,7 +20,6 @@ pub use wait_selector::WaitSelector;#[derive(Debug, Clone, Default)]pub struct CommandContext {session: Option<SessionScope>,- pinned_session_namespace: bool,inherited_deadline: Option<crate::Deadline>,trace: TraceConfig,artifacts_full: bool,@@ -97,7 +96,6 @@ impl CommandContext {session::cursor_overlay_for_session(session.as_ref().map(|scope| scope.id.as_str()))?;Ok(Self {session,- pinned_session_namespace: false,inherited_deadline: None,trace: TraceConfig::build(trace_path, segment_dir, trace_strict)?,artifacts_full,@@ -158,15 +156,6 @@ impl CommandContext {self}- pub fn with_pinned_session_namespace(mut self) -> Self {- self.pinned_session_namespace = true;- self- }-- pub fn session_namespace_is_pinned(&self) -> bool {- self.pinned_session_namespace- }-pub fn is_headed(&self) -> bool {self.options.interaction_policy.is_headed()}@@ -248,11 +237,6 @@ impl CommandContext {pub fn for_batch_item(&self, session_id: Option<String>) -> Result<Self, AppError> {let session_id = session_id.or_else(|| self.session_id().map(str::to_owned));- if self.pinned_session_namespace && session_id.as_deref() != self.session_id() {- return Err(AppError::invalid_input(- "A command host cannot switch snapshot namespaces",- ));- }if let Some(id) = session_id.as_deref() {validate_session_id(id)?;}@@ -283,7 +267,6 @@ impl CommandContext {};Ok(Self {session,- pinned_session_namespace: self.pinned_session_namespace,inherited_deadline: self.inherited_deadline,trace,artifacts_full,diff --git a/crates/macos/src/lib.rs b/crates/macos/src/lib.rsindex 3012d7f76..481469dba 100644--- a/crates/macos/src/lib.rs+++ b/crates/macos/src/lib.rs@@ -12,4 +12,5 @@ pub use input::clipboard::helper_entry_from_env as clipboard_helper_from_env;pub use system::cocoa_runtime::ensure_cocoa_multithreaded;pub use system::permissions::permission_guide::entry_from_env as permission_guide_from_env;pub use system::permissions::permission_helper::entry_from_env as permission_prompt_helper_from_env;+pub use system::process::legacy_host::stop_legacy_command_hosts;pub use tree::resolve::retained::RetainedRefSession;diff --git a/crates/macos/src/system/permissions/permission_guide.rs b/crates/macos/src/system/permissions/permission_guide.rsindex 030b2523d..f12b0ef3d 100644--- a/crates/macos/src/system/permissions/permission_guide.rs+++ b/crates/macos/src/system/permissions/permission_guide.rs@@ -16,11 +16,6 @@ const ACCESSIBILITY: u8 = 1;const SCREEN_RECORDING: u8 = 2;const PROBE_TIMEOUT: Duration = Duration::from_secs(3);const MAX_ANCESTORS: usize = 64;-const COMMAND_HOST_ENVS: [&str; 3] = [- "AGENT_DESKTOP_INTERNAL_COMMAND_HOST",- "AGENT_DESKTOP_INTERNAL_HOST_SOCKET",- "AGENT_DESKTOP_INTERNAL_HOST_CLIENT",-];pub(crate) fn start() -> Result<&'static str, AdapterError> {let steps = missing_steps(@@ -46,9 +41,6 @@ pub(crate) fn start() -> Result<&'static str, AdapterError> {})?;let host = host_app().unwrap_or_else(|| executable.clone());let mut command = Command::new(&executable);- for name in COMMAND_HOST_ENVS {- command.env_remove(name);- }hand_over(&mut command, &lock);let mut child = command.env(STEPS_ENV, steps.to_string())@@ -91,9 +83,8 @@ fn run_child(steps: &str) -> bool {unsafe { agent_desktop_permission_guide_run(steps, host.as_ptr(), granted) == 0 }}-/// Each poll runs in a fresh process: a long-lived process keeps the Screen-/// Recording answer it read at launch, and the command host may belong to-/// another terminal app.+/// Each poll runs in a fresh process, because a long-lived process keeps the+/// Screen Recording answer it read at launch.extern "C" fn granted(step: u8) -> bool {let Ok(executable) = std::env::current_exe() else {return false;diff --git a/crates/macos/src/system/process/legacy_host.rs b/crates/macos/src/system/process/legacy_host.rsnew file mode 100644index 000000000..64bacfa7e--- /dev/null+++ b/crates/macos/src/system/process/legacy_host.rs@@ -0,0 +1,189 @@+//! Stops command hosts that earlier agent-desktop versions left running.++use std::mem::{MaybeUninit, size_of};++const HOST_MARKER: &[u8] = b"AGENT_DESKTOP_INTERNAL_COMMAND_HOST=1";+const PROC_UID_ONLY: u32 = 4;+const CS_OPS_IDENTITY: u32 = 11;+const IDENTITY_BUFFER_LEN: usize = 512;+const BLOB_HEADER_LEN: usize = 8;++unsafe extern "C" {+ fn csops(+ pid: libc::pid_t,+ ops: u32,+ useraddr: *mut libc::c_void,+ usersize: usize,+ ) -> libc::c_int;+}++/// Sends SIGKILL to this user's agent-desktop processes whose environment carries the old command+/// host marker. A process whose owner, start time, environment or code-signing identifier cannot be+/// read, or whose identifier is not agent-desktop's, is left alone.+pub fn stop_legacy_command_hosts() {+ let uid = unsafe { libc::geteuid() };+ let own_pid = std::process::id() as libc::pid_t;+ let Some(mut buffer) = argument_buffer() else {+ return;+ };+ for pid in user_processes(uid) {+ if pid <= 0 || pid == own_pid || !has_marker(pid, &mut buffer) {+ continue;+ }+ let Some(started_at) = process_start_time(pid, uid) else {+ continue;+ };+ if !is_agent_desktop(pid) {+ continue;+ }+ if has_marker(pid, &mut buffer) && process_start_time(pid, uid) == Some(started_at) {+ unsafe { libc::kill(pid, libc::SIGKILL) };+ }+ }+}++/// Whether a `KERN_PROCARGS2` buffer carries the host marker in its environment,+/// skipping the executable path and arguments that precede it.+pub(crate) fn environment_has_marker(procargs: &[u8]) -> bool {+ let Some((count, rest)) = procargs.split_first_chunk::<4>() else {+ return false;+ };+ let arguments = i32::from_ne_bytes(*count);+ if arguments <= 0 {+ return false;+ }+ let Some(path_end) = rest.iter().position(|byte| *byte == 0) else {+ return false;+ };+ let rest = &rest[path_end + 1..];+ let Some(arguments_start) = rest.iter().position(|byte| *byte != 0) else {+ return false;+ };+ let mut rest = &rest[arguments_start..];+ for _ in 0..arguments {+ let Some(end) = rest.iter().position(|byte| *byte == 0) else {+ return false;+ };+ rest = &rest[end + 1..];+ }+ while let Some(end) = rest.iter().position(|byte| *byte == 0) {+ let entry = &rest[..end];+ if entry.is_empty() {+ break;+ }+ if entry == HOST_MARKER {+ return true;+ }+ rest = &rest[end + 1..];+ }+ false+}++/// Whether a `CS_OPS_IDENTITY` blob names an agent-desktop build: an 8-byte big-endian magic and+/// length header followed by the NUL-terminated identifier.+fn blob_names_agent_desktop(blob: &[u8]) -> bool {+ let Some(identifier) = blob.get(BLOB_HEADER_LEN..) else {+ return false;+ };+ let Some(end) = identifier.iter().position(|byte| *byte == 0) else {+ return false;+ };+ let identifier = &identifier[..end];+ identifier == b"agent-desktop" || identifier.starts_with(b"agent_desktop-")+}++fn is_agent_desktop(pid: libc::pid_t) -> bool {+ let mut blob = [0u8; IDENTITY_BUFFER_LEN];+ let read = unsafe { csops(pid, CS_OPS_IDENTITY, blob.as_mut_ptr().cast(), blob.len()) };+ read == 0 && blob_names_agent_desktop(&blob)+}++fn user_processes(uid: libc::uid_t) -> Vec<libc::pid_t> {+ let size = unsafe { libc::proc_listpids(PROC_UID_ONLY, uid, std::ptr::null_mut(), 0) };+ let Ok(size) = usize::try_from(size) else {+ return Vec::new();+ };+ let mut pids = vec![0; size / size_of::<libc::pid_t>() + 1];+ loop {+ let Some(bytes) = pids.len().checked_mul(size_of::<libc::pid_t>()) else {+ return Vec::new();+ };+ let Ok(bytes) = i32::try_from(bytes) else {+ return Vec::new();+ };+ let written =+ unsafe { libc::proc_listpids(PROC_UID_ONLY, uid, pids.as_mut_ptr().cast(), bytes) };+ if written <= 0 {+ return Vec::new();+ }+ if written < bytes {+ pids.truncate(written as usize / size_of::<libc::pid_t>());+ return pids;+ }+ pids.resize(pids.len() * 2, 0);+ }+}++fn process_start_time(pid: libc::pid_t, uid: libc::uid_t) -> Option<(u64, u64)> {+ let info = process_info(pid)?;+ (info.pbi_pid == pid as u32 && info.pbi_uid == uid && info.pbi_status != libc::SZOMB)+ .then_some((info.pbi_start_tvsec, info.pbi_start_tvusec))+}++fn process_info(pid: libc::pid_t) -> Option<libc::proc_bsdinfo> {+ let mut info = MaybeUninit::<libc::proc_bsdinfo>::zeroed();+ let size = size_of::<libc::proc_bsdinfo>() as i32;+ let read = unsafe {+ libc::proc_pidinfo(+ pid,+ libc::PROC_PIDTBSDINFO,+ 0,+ info.as_mut_ptr().cast(),+ size,+ )+ };+ (read == size).then(|| unsafe { info.assume_init() })+}++fn argument_buffer() -> Option<Vec<u8>> {+ let mut mib = [libc::CTL_KERN, libc::KERN_ARGMAX];+ let mut max: libc::c_int = 0;+ let mut size = size_of::<libc::c_int>();+ let read = unsafe {+ libc::sysctl(+ mib.as_mut_ptr(),+ 2,+ (&mut max as *mut libc::c_int).cast(),+ &mut size,+ std::ptr::null_mut(),+ 0,+ )+ };+ if read != 0 {+ return None;+ }+ usize::try_from(max)+ .ok()+ .filter(|max| *max > 0)+ .map(|max| vec![0u8; max])+}++fn has_marker(pid: libc::pid_t, buffer: &mut [u8]) -> bool {+ let mut mib = [libc::CTL_KERN, libc::KERN_PROCARGS2, pid];+ let mut size = buffer.len();+ let read = unsafe {+ libc::sysctl(+ mib.as_mut_ptr(),+ 3,+ buffer.as_mut_ptr().cast(),+ &mut size,+ std::ptr::null_mut(),+ 0,+ )+ };+ read == 0 && size <= buffer.len() && environment_has_marker(&buffer[..size])+}++#[cfg(test)]+#[path = "legacy_host_tests.rs"]+mod tests;diff --git a/crates/macos/src/system/process/legacy_host_tests.rs b/crates/macos/src/system/process/legacy_host_tests.rsnew file mode 100644index 000000000..1ce337c33--- /dev/null+++ b/crates/macos/src/system/process/legacy_host_tests.rs@@ -0,0 +1,59 @@+use super::{environment_has_marker, process_start_time};++const MARKER: &str = "AGENT_DESKTOP_INTERNAL_COMMAND_HOST=1";++fn procargs(arguments: &[&str], environment: &[&str]) -> Vec<u8> {+ let mut buffer = (arguments.len() as i32).to_ne_bytes().to_vec();+ buffer.extend_from_slice(b"/usr/local/bin/agent-desktop\0\0\0");+ for field in arguments.iter().chain(environment) {+ buffer.extend_from_slice(field.as_bytes());+ buffer.push(0);+ }+ buffer+}++#[test]+fn the_marker_counts_only_as_an_exact_environment_entry() {+ assert!(environment_has_marker(&procargs(+ &["agent-desktop", ""],+ &["HOME=/Users/a", MARKER]+ )));+ assert!(!environment_has_marker(&procargs(+ &["agent-desktop", MARKER],+ &["HOME=/Users/a"]+ )));+ for entry in [+ "AGENT_DESKTOP_INTERNAL_COMMAND_HOST=0",+ "AGENT_DESKTOP_INTERNAL_COMMAND_HOST=1suffix",+ "OTHER=AGENT_DESKTOP_INTERNAL_COMMAND_HOST=1",+ ] {+ assert!(!environment_has_marker(&procargs(+ &["agent-desktop"],+ &[entry]+ )));+ }+}++#[test]+fn malformed_argument_blocks_fail_closed() {+ assert!(!environment_has_marker(&[1, 0]));+ for count in [0, -1, i32::MAX] {+ let mut buffer = procargs(&["agent-desktop"], &[MARKER]);+ buffer[..4].copy_from_slice(&count.to_ne_bytes());+ assert!(!environment_has_marker(&buffer));+ }+ let mut truncated = procargs(&["agent-desktop"], &[MARKER]);+ truncated.pop();+ assert!(!environment_has_marker(&truncated));+}++#[test]+fn process_start_time_requires_the_process_owner() {+ let uid = unsafe { libc::geteuid() };+ let pid = std::process::id() as libc::pid_t;+ assert!(process_start_time(pid, uid).is_some());+ assert!(process_start_time(pid, uid ^ 1).is_none());+ if uid != 0 {+ assert!(process_start_time(1, uid).is_none());+ }+}diff --git a/crates/macos/src/system/process/mod.rs b/crates/macos/src/system/process/mod.rsindex 98cc1308f..0fe6e7059 100644--- a/crates/macos/src/system/process/mod.rs+++ b/crates/macos/src/system/process/mod.rs@@ -324,6 +324,7 @@ fn output_limit_error(label: &str, stdout: &DrainResult, stderr: &DrainResult) -}))}+pub(crate) mod legacy_host;pub(crate) mod process_apps;pub(crate) mod process_identity;pub(crate) mod process_state;diff --git a/docs/solutions/best-practices/identity-fingerprint-against-os-reorder-2026-04-16.md b/docs/solutions/best-practices/identity-fingerprint-against-os-reorder-2026-04-16.mdindex 6b085ea41..5ba059266 100644--- a/docs/solutions/best-practices/identity-fingerprint-against-os-reorder-2026-04-16.md+++ b/docs/solutions/best-practices/identity-fingerprint-against-os-reorder-2026-04-16.md@@ -79,7 +79,7 @@ discards the bytes rather than attributing them to the wrong surfaceBackend choice (Modern vs Legacy) is orthogonal: the fingerprint appliesregardless of which capture path produces the PNG.-**Element identity inside repeated collections.** A repeated native identifier does not identify a row. After a filter, a different row can take the original position with the same identifier and bounds, and disabling the path optimization does not help, because a broad search still matches them. Do not freeze mutable values to fix this, since ordinary text inputs must stay editable through the same ref. Without the opt-in internal command host (`AGENT_DESKTOP_INTERNAL_COMMAND_HOST=1`, `src/command_host/mod.rs`), no retained-object token is recorded, so `ref_identity::identity_match` in `crates/core/src/refs/ref_identity.rs` returns `Match` on the shared identifier and the aliasing stays reachable in the default CLI.+**Element identity inside repeated collections.** A repeated native identifier does not identify a row. After a filter, a different row can take the original position with the same identifier and bounds, and disabling the path optimization does not help, because a broad search still matches them. Do not freeze mutable values to fix this, since ordinary text inputs must stay editable through the same ref. On macOS, refs carry no retained-object token, so `ref_identity::identity_match` in `crates/core/src/refs/ref_identity.rs` returns `Match` on the shared identifier and the aliasing stays reachable there.## Preventiondiff --git a/npm/scripts/postinstall.js b/npm/scripts/postinstall.jsindex dded59999..d079ffe92 100644--- a/npm/scripts/postinstall.js+++ b/npm/scripts/postinstall.js@@ -185,6 +185,17 @@ function isNodeWrapper(path) {const LINKED_NOTICE = 'Native binary linked: each call runs without the Node launcher.';+/** Runs the installed binary once on macOS so it stops command hosts that earlier versions left running. */+function stopLeftoverHosts(binaryPath) {+ if (platform() !== 'darwin') return;+ try {+ execFileSync(binaryPath, ['version'], { stdio: 'ignore', timeout: 5000 });+ } catch (err) {+ log(`Could not stop command hosts left by an earlier version: ${err.message}`);+ log('Run `agent-desktop version` once to stop them.');+ }+}+function linkBinEntry(directory, binaryName, osPlatform = platform()) {if (!isInstalledPackage(directory)) return false;if (osPlatform === 'win32') {@@ -304,6 +315,7 @@ function main() {installExecutable(customPath, binaryPath);log(`Using binary from AGENT_DESKTOP_BINARY_PATH: ${customPath}`);linkBinEntry(binDir, binaryName);+ stopLeftoverHosts(binaryPath);promptSkillInstall();} catch (err) {log(`Failed to install from AGENT_DESKTOP_BINARY_PATH: ${err.message}`);@@ -331,6 +343,7 @@ function main() {: `Native executable ready: ${binaryName}`,);linkBinEntry(binDir, binaryName);+ stopLeftoverHosts(binaryPath);promptSkillInstall();return;}@@ -373,6 +386,7 @@ function main() {}linkBinEntry(binDir, binaryName);+ stopLeftoverHosts(binaryPath);promptSkillInstall();}diff --git a/scripts/check_architecture.py b/scripts/check_architecture.pyindex e3624829f..4a16ee124 100644--- a/scripts/check_architecture.py+++ b/scripts/check_architecture.py@@ -33,7 +33,7 @@ CORE_DOMAINS = {"actionability", "actions", "adapter", "commands", "context", "c"locator", "notifications", "ref_action", "refs", "response", "session", "snapshot","storage", "system", "trace", "tree", "wait"}BINARY_TOP_FILES = {"main.rs", "Cargo.toml"}-BINARY_DIRS = {"batch", "cli", "cli_args", "command_host", "command_policy", "diagnostic", "dispatch",+BINARY_DIRS = {"batch", "cli", "cli_args", "command_policy", "diagnostic", "dispatch","tests", "visual_debug"}CAPABILITY_HOMES = {"PlatformAdapter": ("adapter.rs",),@@ -83,6 +83,22 @@ CORE_OS_ALLOWLIST = {"trace/trace_tests.rs",}+# Every CLI call is its own process that serves nothing. Only these files may+# open a listener or server, and only for the reason beside them; a new entry+# is a review decision. Test files and inline test modules are not scanned.+LISTENER_ALLOWLIST = {+ "crates/core/src/system/cdp_endpoint.rs",+ "crates/macos/src/system/cursor_overlay/child.rs",+ "crates/windows/src/system/cursor_overlay/server.rs",+}+LISTENER = re.compile(r"(?<![A-Za-z0-9_])(?:(?:UnixListener|TcpListener|UdpSocket|UnixDatagram)\s*::\s*bind\w*"+ r"|CreateNamedPipe[AW]?|NamedPipeServer|ServerOptions|libc\s*::\s*listen)(?![A-Za-z0-9_])")+HOST_MARKER = "AGENT_DESKTOP_INTERNAL_COMMAND_HOST"+HOST_MARKER_ALLOWLIST = {"crates/macos/src/system/process/legacy_host.rs"}+TEST_FILE = re.compile(r"(^|/)tests/|_tests\.rs$|test_support")+TEST_MODULE = re.compile(r"#\s*\[\s*cfg\s*\(\s*test\s*\)\s*\]\s*(?:pub(?:\s*\([^)]*\))?\s+)?mod\s+\w+\s*\{")++STR = re.compile(r"__S(\d+)__")@@ -256,6 +272,18 @@ def mod_decls(src):yield m.group(1), head, path_lit+def production_code(code):+ """The code with every inline `#[cfg(test)] mod name { ... }` block removed."""+ out, i = [], 0+ for m in TEST_MODULE.finditer(code):+ if m.start() < i:+ continue+ out.append(code[i:m.start()])+ i = balanced(code, m.end() - 1)+ out.append(code[i:])+ return "".join(out)++def cfg_test(attrs_text):return any(re.search(r"(?<![A-Za-z0-9_])test(?![A-Za-z0-9_])", c) for c in re.findall(r"cfg\s*\(([^\]]*)\)", attrs_text))@@ -348,6 +376,22 @@ def check(repo):for stale in sorted(CORE_OS_ALLOWLIST - seen):err("G5", f"CORE_OS_ALLOWLIST lists crates/core/src/{stale}, which no longer carries OS-conditional code")+ serving = set()+ for f, src in sources.items():+ rel = os.path.relpath(f, repo).replace(os.sep, "/")+ if TEST_FILE.search(rel):+ continue+ if LISTENER.search(production_code(src.code)):+ if rel in LISTENER_ALLOWLIST:+ serving.add(rel)+ else:+ err("G12", f"{rel} opens a listener or server; every call is its own process and serves nothing, "+ "so a new server needs a LISTENER_ALLOWLIST entry in review")+ if rel not in HOST_MARKER_ALLOWLIST and any(HOST_MARKER in lit for lit in src.lits):+ err("G12", f"{rel} names {HOST_MARKER}, the marker of the removed command host")+ for stale in sorted(LISTENER_ALLOWLIST - serving):+ err("G12", f"LISTENER_ALLOWLIST lists {stale}, which no longer opens a listener")+for p in PLATFORMS:if not os.path.exists(os.path.join(repo, "crates", p, "Cargo.toml")):continue@@ -474,7 +518,7 @@ CLEAN = {"crates/ffi/src/lib.rs": "\n","src/Cargo.toml": '[package]\nname = "agent-desktop"\nversion = "0.0.0"\nedition = "2021"\n[[bin]]\nname = "agent-desktop"\npath = "main.rs"\n''[target.\'cfg(target_os = "linux")\'.dependencies]\nagent-desktop-linux = { path = "../crates/linux" }\n',- "src/main.rs": "mod batch;\nmod cli;\nmod cli_args;\nmod command_host;\nmod command_policy;\nmod diagnostic;\nmod dispatch;\n"+ "src/main.rs": "mod batch;\nmod cli;\nmod cli_args;\nmod command_policy;\nmod diagnostic;\nmod dispatch;\n""mod visual_debug;\n#[cfg(test)]\n#[path = \"tests/main_tests.rs\"]\nmod main_tests;\nfn main() {}\n","src/tests/main_tests.rs": "\n",}@@ -540,14 +584,21 @@ PLANTS = {("crates/core/src/tree/mod.rs", "pub mod node;\n#[cfg_attr(test, path = \"../input/mod.rs\")]\nmod misplaced;\n"),("crates/core/src/tree/mod.rs", "pub mod node;\n#[path = \"@ABS@/crates/core/src/input/mod.rs\"]\nmod misplaced;\n")],}+PLANTS["G12"] = [+ ("crates/macos/src/system/host.rs", "fn f() { let _ = std::os::unix::net::UnixListener::bind(\"/tmp/h.sock\"); }\n"),+ ("crates/core/src/system/host.rs", "fn f() { let _ = std::net::TcpListener::bind((\"127.0.0.1\", 0)); }\n"),+ ("crates/windows/src/system/host.rs", "fn f() { let _ = CreateNamedPipeW; }\n"),+ ("src/host.rs", "const MARKER: &str = \"AGENT_DESKTOP_INTERNAL_COMMAND_HOST=1\";\n"),+]SUPPORT = {"G2": {"crates/core/custom.rs": "fn main() {}\n"},"G8": {"crates/linux/src/input/real_tests.rs": "impl SystemOps for crate::adapter::A {}\n"}}def self_test():"""Plant one violation per case in a minimal clean workspace; every case must fire, the clean tree must pass."""- global CORE_OS_ALLOWLIST+ global CORE_OS_ALLOWLIST, LISTENER_ALLOWLISTsaved = CORE_OS_ALLOWLIST+ saved_listeners = LISTENER_ALLOWLISTtmp = tempfile.mkdtemp(prefix="arch-selftest-")try:def build(overrides):@@ -568,6 +619,7 @@ def self_test():fh.write(text.replace("@ABS@", tmp))CORE_OS_ALLOWLIST = set()+ LISTENER_ALLOWLIST = set()build({})clean = check(tmp)if clean:@@ -583,8 +635,14 @@ def self_test():build({})if not [e for e in check(tmp) if e.startswith("G5:") and "no longer" in e]:raise SystemExit("self-test: a stale CORE_OS_ALLOWLIST entry was not reported")+ CORE_OS_ALLOWLIST = set()+ LISTENER_ALLOWLIST = {"crates/core/src/lib.rs"}+ build({})+ if not [e for e in check(tmp) if e.startswith("G12:") and "no longer" in e]:+ raise SystemExit("self-test: a stale LISTENER_ALLOWLIST entry was not reported")finally:CORE_OS_ALLOWLIST = saved+ LISTENER_ALLOWLIST = saved_listenersshutil.rmtree(tmp, ignore_errors=True)diff --git a/skills/agent-desktop-macos/SKILL.md b/skills/agent-desktop-macos/SKILL.mdindex 03deb4d3f..c1ae3b4f8 100644--- a/skills/agent-desktop-macos/SKILL.md+++ b/skills/agent-desktop-macos/SKILL.md@@ -28,7 +28,7 @@ Read the core skill first (`agent-desktop skills get desktop`) for the observe,1. Run `agent-desktop permissions`.2. If a permission is denied, run `agent-desktop permissions --guide`. It opens the correct System Settings page with a panel that shows the user which app to drag into the list. The user confirms with Touch ID or a password, and the panel moves to the next missing permission by itself. The command returns at once with `"guide": "started"`, `"already_running"` or `"not_needed"`. `agent-desktop permissions --request` shows the system prompts instead.3. If the guide cannot run, open System Settings > Privacy & Security > Accessibility (Device Control and Data Access on macOS 27 and later). Add the launching app and turn it on.-4. Run `agent-desktop permissions` to confirm `granted`. The next agent-desktop call sees a new grant, so the launching app does not need a restart.+4. Run `agent-desktop permissions` to confirm `granted`. The next agent-desktop call sees a new grant, so the launching app does not need a restart. Each command reads permissions in its own process, so a permission granted during a `batch` applies from the next CLI call, not to later items in that batch.5. Run `agent-desktop snapshot -i` to confirm. It reads the focused app. `snapshot --app Finder -i` returns `WINDOW_NOT_FOUND` when Finder has no open window.`permissions` does not prompt. `permissions --request` can prompt, including for Automation. `permissions --guide` does not prompt and covers Accessibility and Screen Recording only. Automation reports `unknown` when macOS would need to prompt.@@ -49,6 +49,8 @@ Read the core skill first (`agent-desktop skills get desktop`) for the observe,**Identity.** `launch` accepts a display name (`"System Settings"`) or a bundle ID (`com.apple.systempreferences`). Other commands take the display name through `--app`. Window IDs such as `w-4521` stay valid for the life of the window. Find them with `list-windows`.+**Repeated collections.** A ref to a row in a list whose rows share an accessibility identifier can act on another row after the list changes. Take a new snapshot after the list changes.+**Keys.** The primary modifier is `cmd`: `press cmd+c`, `press cmd+s`. Quit shortcuts such as `cmd+q`, `cmd+shift+q`, `cmd+alt+esc`, `ctrl+cmd+q` and `cmd+shift+delete` return `POLICY_DENIED` unless you pass `--force`. To quit an app, use `close-app`. Punctuation keys work in combos, as the symbol (`,` `.` `/` `;` `'` `[` `]` `\` `-` `=` `` ` ``) or by name (`comma`, `period`, `slash`, `semicolon`, `quote`, `leftbracket`, `rightbracket`, `backslash`, `minus`, `equal`, `grave`). Each one is sent with the key that types it in the active keyboard layout, so `press cmd+,` opens Settings on ANSI and JIS keyboards alike.**Cursor overlay.** `cursor-overlay enable` draws the agent cursor in a click-through window. It never moves the OS pointer or activates an app. The macOS motion and image limits are in the core `commands-system` reference.diff --git a/src/Cargo.toml b/src/Cargo.tomlindex cb0d44545..d24dcc062 100644--- a/src/Cargo.toml+++ b/src/Cargo.toml@@ -17,7 +17,6 @@ tracing-subscriber.workspace = true[target.'cfg(target_os = "macos")'.dependencies]agent-desktop-macos = { path = "../crates/macos" }-libc.workspace = true[target.'cfg(target_os = "windows")'.dependencies]agent-desktop-windows = { path = "../crates/windows" }@@ -48,6 +47,10 @@ path = "tests/conformance.rs"name = "cli_process"path = "tests/cli_process.rs"+[[test]]+name = "command_host_absent"+path = "tests/command_host_absent.rs"+[[test]]name = "windows_private_file_install"path = "tests/windows_private_file_install.rs"@@ -56,9 +59,5 @@ path = "tests/windows_private_file_install.rs"name = "windows_cursor_overlay_teardown"path = "tests/windows_cursor_overlay_teardown.rs"-[[test]]-name = "command_host_process"-path = "tests/command_host_process.rs"-[lints]workspace = truediff --git a/src/batch/execution.rs b/src/batch/execution.rsindex 4188f82ab..4a01ff3c2 100644--- a/src/batch/execution.rs+++ b/src/batch/execution.rs@@ -100,40 +100,11 @@ pub(super) fn execute(.with_inherited_deadline(deadline).with_event_baseline(current_baseline);let command = std::mem::replace(&mut commands[index].command, Commands::Version);- #[cfg(target_os = "macos")]- let forwarded = if !cfg!(test)- && !context.session_namespace_is_pinned()- && !command.needs_caller_process()- {- Some(crate::command_host::forward_batch_item(- &commands[index].source,- &item_context,- deadline,- ))- } else {- None- };- #[cfg(not(target_os = "macos"))]- let forwarded: Option<Result<Value, AppError>> = None;- let entry = match forwarded {- Some(Ok(mut entry)) => {- entry["index"] = json!(index);- entry- }- result => super::result_entry::completed_entry(- index,- &commands[index].name,- match result {- Some(Err(error)) => Err(error),- _ => crate::dispatch::dispatch(- command,- adapter,- permission_report,- &item_context,- ),- },- ),- };+ let entry = super::result_entry::completed_entry(+ index,+ &commands[index].name,+ crate::dispatch::dispatch(command, adapter, permission_report, &item_context),+ );let failed = entry["ok"] != true;let (entry, oversized) = super::result_entry::bounded_completed_entry(index,diff --git a/src/batch/preparation.rs b/src/batch/preparation.rsindex 71855d563..26e4b06e2 100644--- a/src/batch/preparation.rs+++ b/src/batch/preparation.rs@@ -13,8 +13,6 @@ pub(super) struct PreparedCommand {pub name: String,pub command: Commands,pub context: CommandContext,- #[cfg(target_os = "macos")]- pub source: Value,}pub(super) fn prepare(@@ -43,7 +41,7 @@ pub(super) fn prepare(.collect::<Result<Vec<_>, _>>()?;parsed.into_iter()- .map(|(index, name, command, session, _source)| {+ .map(|(index, name, command, session)| {let item_context = context.for_batch_item(session).map_err(|error| located_error(index, &name, error))?;@@ -53,8 +51,6 @@ pub(super) fn prepare(name,command,context: item_context,- #[cfg(target_os = "macos")]- source: _source,})}).collect()@@ -64,8 +60,7 @@ fn parse_one(index: usize,item: BatchCommand,permission_report: &PermissionReport,-) -> Result<(usize, String, Commands, Option<String>, Value), AppError> {- let source = json!({"command": item.command, "args": item.args});+) -> Result<(usize, String, Commands, Option<String>), AppError> {let name = item.command.clone();let session = item.session.clone();if let Some(session) = session.as_deref() {@@ -75,7 +70,7 @@ fn parse_one(let command = super::parse_command(item).map_err(|error| located_error(index, &name, error))?;crate::command_policy::preflight(&command, permission_report).map_err(|error| located_error(index, &name, error))?;- Ok((index, name, command, session, source))+ Ok((index, name, command, session))}fn located_error(index: usize, command: &str, error: AppError) -> AppError {@@ -108,33 +103,3 @@ fn limit_error(message: &str, details: Value) -> AppError {.with_disposition(DeliverySemantics::not_delivered()).into()}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn a_pinned_namespace_rejects_foreign_item_sessions_before_dispatch() {- let context = CommandContext::default().with_pinned_session_namespace();- match prepare(- r#"[{"command":"version","session":"other"}]"#,- &PermissionReport::default(),- &context,- ) {- Ok(_) => panic!("a foreign item session must be rejected"),- Err(error) => assert!(- error- .to_string()- .contains("cannot switch snapshot namespaces")- ),- }- let prepared = prepare(- r#"[{"command":"version"}]"#,- &PermissionReport::default(),- &context,- )- .unwrap();- assert_eq!(prepared.len(), 1);- assert_eq!(prepared[0].context.session_id(), None);- }-}diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex 7e26dfb03..eb61abe0d 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -259,13 +259,6 @@ impl Commands {self.metadata().post_action_wait}- #[cfg(target_os = "macos")]- /// Permission guidance needs the caller; session management crosses host namespaces.- pub(crate) fn needs_caller_process(&self) -> bool {- matches!(self, Self::Session(_) | Self::Batch(_))- || matches!(self, Self::Permissions(args) if args.guide)- }-pub(crate) fn is_mutating(&self) -> bool {match self {Self::Click(_)diff --git a/src/cli/wait_for_cli_tests.rs b/src/cli/wait_for_cli_tests.rsindex 8d6337e33..23e3e1fd6 100644--- a/src/cli/wait_for_cli_tests.rs+++ b/src/cli/wait_for_cli_tests.rs@@ -136,18 +136,6 @@ fn typed_metadata_names_each_variant() {assert_eq!(find.name(), "find");}-#[cfg(target_os = "macos")]-#[test]-fn caller_coordinates_batches_sessions_and_permission_guidance() {- assert!(command(&["permissions", "--guide"]).needs_caller_process());- assert!(command(&["session", "end", "other"]).needs_caller_process());- assert!(command(&["session", "gc"]).needs_caller_process());- assert!(command(&["batch", "[]"]).needs_caller_process());- assert!(!command(&["permissions"]).needs_caller_process());- assert!(!command(&["permissions", "--request"]).needs_caller_process());- assert!(!command(&["click", "@e1"]).needs_caller_process());-}-#[test]fn mutation_metadata_distinguishes_read_only_and_file_writing_forms() {assert!(command(&["click", "@e1"]).is_mutating());diff --git a/src/command_host/command_host_batch.rs b/src/command_host/command_host_batch.rsdeleted file mode 100644index 7cfe02882..000000000--- a/src/command_host/command_host_batch.rs+++ /dev/null@@ -1,64 +0,0 @@-use agent_desktop_core::{AppError, Deadline, context::CommandContext};-use clap::Parser;-use serde_json::{Value, json};--pub(crate) fn forward_batch_item(- source: &Value,- context: &CommandContext,- deadline: Deadline,-) -> Result<Value, AppError> {- let original =- crate::Cli::try_parse().map_err(|error| AppError::invalid_input(error.to_string()))?;- let mut args = Vec::new();- if let Some(session) = context.session_id() {- args.extend(["--session".into(), session.into()]);- }- if let Some(agent) = context.agent_id() {- args.extend(["--agent-id".into(), agent.into()]);- }- if context.is_headed() {- args.push("--headed".into());- }- if let Some(trace) = original.trace {- args.extend([- "--trace".into(),- trace- .to_str()- .ok_or_else(|| AppError::invalid_input("Trace path must be UTF-8"))?- .into(),- ]);- }- if original.trace_strict {- args.push("--trace-strict".into());- }- if deadline.is_expired() {- return Err(deadline.timeout_error().into());- }- args.extend([- "batch".into(),- json!([source]).to_string(),- "--timeout-ms".into(),- deadline.remaining_ms().to_string(),- ]);- let mut cli =- crate::Cli::try_parse_from(std::iter::once("agent-desktop".to_owned()).chain(args.clone()))- .map_err(|error| AppError::invalid_input(error.to_string()))?;- let command = cli- .command- .take()- .ok_or_else(|| AppError::Internal("Constructed batch command is missing".into()))?;- let baseline = context.event_baseline().cloned().transpose()?;- let response = super::client::forward_args(&cli, &command, args, baseline)?;- if response["ok"] == true {- response["data"]["results"]- .as_array()- .and_then(|entries| entries.first())- .cloned()- .ok_or_else(|| AppError::invalid_input("Command host batch reply has no entry"))- } else {- let mut entry = response;- entry["command"] = source["command"].clone();- entry["execution"] = json!("completed");- Ok(entry)- }-}diff --git a/src/command_host/command_host_budget.rs b/src/command_host/command_host_budget.rsdeleted file mode 100644index 603a852ee..000000000--- a/src/command_host/command_host_budget.rs+++ /dev/null@@ -1,151 +0,0 @@-use agent_desktop_core::{AdapterError, AppError, Deadline};-use std::time::Duration;--pub(super) fn expires_at(cli: &crate::Cli, command: &crate::Commands) -> Result<u64, AppError> {- let budget = budget_ms(cli, command)?;- Deadline::detached_after(budget)?;- now()?- .checked_add(- budget- .checked_mul(1_000_000)- .ok_or_else(|| AppError::invalid_input("Command host budget is too large"))?,- )- .ok_or_else(|| AppError::invalid_input("Command host deadline is too large"))-}--pub(super) fn remaining(expires_ns: u64) -> Result<Duration, AppError> {- remaining_at(expires_ns, now()?)-}--fn remaining_at(expires_ns: u64, now_ns: u64) -> Result<Duration, AppError> {- match expires_ns- .checked_sub(now_ns)- .filter(|remaining| *remaining > 0)- {- Some(remaining) => Ok(Duration::from_nanos(remaining)),- None => Err(AdapterError::timeout("Command host request expired before dispatch").into()),- }-}--fn now() -> Result<u64, AppError> {- let mut time = libc::timespec {- tv_sec: 0,- tv_nsec: 0,- };- if unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut time) } != 0 {- return Err(std::io::Error::last_os_error().into());- }- u64::try_from(time.tv_sec)- .ok()- .and_then(|seconds| seconds.checked_mul(1_000_000_000))- .and_then(|seconds| seconds.checked_add(time.tv_nsec as u64))- .ok_or_else(|| AppError::Internal("Monotonic clock is outside its supported range".into()))-}--fn budget_ms(cli: &crate::Cli, command: &crate::Commands) -> Result<u64, AppError> {- use crate::Commands;- let primary = match command {- Commands::Click(a)- | Commands::DoubleClick(a)- | Commands::TripleClick(a)- | Commands::RightClick(a)- | Commands::Clear(a)- | Commands::Focus(a)- | Commands::Toggle(a)- | Commands::Check(a)- | Commands::Uncheck(a)- | Commands::Expand(a)- | Commands::Collapse(a)- | Commands::ScrollTo(a) => a.timeout_ms,- Commands::Type(a) => a.effective_timeout_ms(),- Commands::SetValue(a) => a.timeout_ms,- Commands::Select(a) => a.timeout_ms,- Commands::Scroll(a) => a.timeout_ms,- Commands::Hover(a) => a.timeout_ms,- Commands::Drag(a) => a.timeout_ms,- Commands::Wait(a) => match a.mode.ms {- Some(ms) => ms- .checked_add(5000)- .ok_or_else(|| AppError::invalid_input("Wait is too long"))?,- None => a.timeout,- },- Commands::Snapshot(a) => a- .timeout_ms- .unwrap_or(agent_desktop_core::DEFAULT_OPERATION_TIMEOUT_MS),- Commands::Find(a) => a- .timeout_ms- .unwrap_or(agent_desktop_core::DEFAULT_OPERATION_TIMEOUT_MS),- Commands::ListApps(a) => a- .timeout_ms- .unwrap_or(agent_desktop_core::DEFAULT_OPERATION_TIMEOUT_MS),- Commands::ListWindows(a) => a- .timeout_ms- .unwrap_or(agent_desktop_core::DEFAULT_OPERATION_TIMEOUT_MS),- Commands::Launch(a) => a.timeout,- Commands::Batch(a) => a.timeout_ms,- _ => agent_desktop_core::DEFAULT_OPERATION_TIMEOUT_MS,- };- let primary = if primary == 0 {- agent_desktop_core::DEFAULT_OPERATION_TIMEOUT_MS- } else {- primary- };- let post_wait = crate::build_wait_selector(cli)?.map_or(0, |wait| wait.timeout_ms);- primary- .checked_add(post_wait)- .ok_or_else(|| AppError::invalid_input("Combined command budget is too large"))-}--#[cfg(test)]-mod tests {- use super::*;- use clap::Parser;-- #[test]- fn queue_time_is_not_refunded_and_expiry_is_terminal() {- assert_eq!(- remaining_at(8000, 2000).unwrap(),- Duration::from_nanos(6000)- );- for now in [8000, 9000] {- assert_eq!(remaining_at(8000, now).unwrap_err().code(), "TIMEOUT");- }- }-- #[test]- fn budgets_follow_typed_arguments_including_post_action_waits() {- for (args, expected) in [- (vec!["ad", "click", "@s123:e1", "--timeout-ms", "123"], 123),- (- vec!["ad", "click", "@s123:e1", "--timeout-ms", "0"],- agent_desktop_core::DEFAULT_OPERATION_TIMEOUT_MS,- ),- (- vec!["ad", "wait", "--text", "absent", "--timeout", "250"],- 250,- ),- (vec!["ad", "snapshot", "--timeout-ms", "30000"], 30000),- (vec!["ad", "find", "--timeout-ms", "30000"], 30000),- (vec!["ad", "list-apps", "--timeout-ms", "30000"], 30000),- (vec!["ad", "list-windows", "--timeout-ms", "30000"], 30000),- (vec!["ad", "wait", "100"], 5100),- (vec!["ad", "batch", "[]", "--timeout-ms", "80000"], 80000),- (- vec![- "ad",- "click",- "@s123:e1",- "--wait-for",- "button",- "--wait-timeout",- "900",- ],- 5900,- ),- ] {- let mut cli = crate::Cli::try_parse_from(args).unwrap();- let command = cli.command.take().unwrap();- assert_eq!(budget_ms(&cli, &command).unwrap(), expected);- }- }-}diff --git a/src/command_host/command_host_client.rs b/src/command_host/command_host_client.rsdeleted file mode 100644index 1b7bb159c..000000000--- a/src/command_host/command_host_client.rs+++ /dev/null@@ -1,214 +0,0 @@-use agent_desktop_core::{AdapterError, AppError, Deadline, DeliverySemantics};-use std::io::{BufReader, BufWriter, Write};-use std::os::unix::net::UnixStream;-use std::os::unix::process::CommandExt;-use std::path::Path;-use std::process::{Command, Stdio};-use std::time::{Duration, Instant};--pub(super) fn forward(- cli: &crate::Cli,- command: &crate::Commands,-) -> Result<serde_json::Value, AppError> {- let args = std::env::args_os()- .skip(1)- .map(|arg| {- arg.into_string()- .map_err(|_| AppError::invalid_input("Host arguments must be UTF-8"))- })- .collect::<Result<_, _>>()?;- forward_args(cli, command, args, None)-}--pub(super) fn forward_args(- cli: &crate::Cli,- command: &crate::Commands,- args: Vec<String>,- baseline: Option<agent_desktop_core::SignalBaseline>,-) -> Result<serde_json::Value, AppError> {- let expires_ns = super::budget::expires_at(cli, command).map_err(crate::pre_dispatch_error)?;- agent_desktop_core::validate_state_root_env()?;- let session = agent_desktop_core::session::resolve_active_session(- cli.identity.session.as_deref(),- std::env::var("AGENT_DESKTOP_SESSION").ok().as_deref(),- )?;- let identity = super::endpoint::identity(session.as_deref())?;- let path = super::endpoint::path(&identity)?;- let request = super::request::HostRequest {- expires_ns,- identity,- args,- baseline,- directory: std::env::current_dir()?,- agent_id: cli- .identity- .agent_id- .clone()- .or_else(|| std::env::var("AGENT_DESKTOP_AGENT_ID").ok()),- };- let mut payload = serde_json::to_vec(&request)?;- payload.push(b'\n');- if payload.len() > super::MAX_REQUEST_BYTES as usize {- return Err(AppError::invalid_input(- "Command host request exceeds its size limit",- ));- }- let remaining = super::budget::remaining(expires_ns).map_err(crate::pre_dispatch_error)?;- let stream = connect_or_start(&path, session.as_deref(), remaining.min(super::IO_TIMEOUT))- .map_err(crate::pre_dispatch_error)?;- let remaining = super::budget::remaining(expires_ns).map_err(crate::pre_dispatch_error)?;- exchange(stream, &payload, remaining).map_err(|error| {- AdapterError::internal("Command host reply was lost; the command may have executed")- .with_platform_detail(error.to_string())- .with_disposition(DeliverySemantics::uncertain())- .into()- })-}--fn exchange(- stream: UnixStream,- payload: &[u8],- remaining: Duration,-) -> Result<serde_json::Value, AppError> {- let reply_deadline = Instant::now() + remaining + Duration::from_secs(2);- let mut output = BufWriter::new(super::output::BoundedWriter::new(- stream.try_clone()?,- remaining.min(super::IO_TIMEOUT),- )?);- output.write_all(payload)?;- output.flush()?;- let reply = super::input::read_frame(- &mut BufReader::new(stream),- 64 * 1024 * 1024,- reply_deadline.saturating_duration_since(Instant::now()),- super::IO_TIMEOUT,- )?;- if reply.last() != Some(&b'\n') || reply.len() > 64 * 1024 * 1024 {- return Err(AppError::invalid_input(- "Command host reply is incomplete or oversized",- ));- }- let value: serde_json::Value = serde_json::from_slice(&reply)?;- if value["version"] != agent_desktop_core::response::output::ENVELOPE_VERSION- || !value["ok"].is_boolean()- {- return Err(AppError::invalid_input(- "Command host reply has an invalid envelope",- ));- }- Ok(value)-}--fn connect(path: &Path, deadline: Instant) -> Result<Option<UnixStream>, AppError> {- if !super::endpoint::validate_socket(path)? {- return Ok(None);- }- match super::connect::connect(path, deadline) {- Ok(stream) => Ok(Some(stream)),- Err(error)- if matches!(- error.kind(),- std::io::ErrorKind::NotFound | std::io::ErrorKind::ConnectionRefused- ) =>- {- Ok(None)- }- Err(error) => Err(error.into()),- }-}--fn connect_or_start(- path: &Path,- session: Option<&str>,- budget: Duration,-) -> Result<UnixStream, AppError> {- let deadline = Instant::now() + budget;- if let Some(stream) = connect(path, deadline)? {- return Ok(stream);- }- let _startup = agent_desktop_core::FileLock::acquire(- &path.with_extension("start.lock"),- Deadline::from_duration(deadline.saturating_duration_since(Instant::now()))?,- "command host startup",- )?;- if let Some(stream) = connect(path, deadline)? {- return Ok(stream);- }- let mut command = Command::new(std::env::current_exe()?);- command- .env("AGENT_DESKTOP_INTERNAL_COMMAND_HOST", "1")- .env("AGENT_DESKTOP_INTERNAL_HOST_SOCKET", path)- .env_remove("AGENT_DESKTOP_AGENT_ID")- .env_remove("AGENT_DESKTOP_SESSION")- .process_group(0)- .stdin(Stdio::null())- .stdout(Stdio::null())- .stderr(Stdio::null());- if let Some(session) = session {- command.env("AGENT_DESKTOP_SESSION", session);- }- let mut child = command.spawn()?;- let result = loop {- if Instant::now() >= deadline {- break Err(AppError::from(AdapterError::timeout(- "Command host startup timed out",- )));- }- match child.try_wait() {- Ok(Some(_)) => {- break Err(AppError::Internal(- "Command host exited during startup".into(),- ));- }- Ok(None) => {}- Err(error) => break Err(error.into()),- }- match connect(path, deadline) {- Ok(Some(stream)) => break Ok(stream),- Ok(None) => std::thread::sleep(Duration::from_millis(10)),- Err(error) => break Err(error),- }- };- if result.is_err() {- let _ = child.kill();- let _ = child.wait();- }- result-}--#[cfg(test)]-mod tests {- use super::*;- use std::io::Read;-- fn replied(bytes: &[u8]) -> Result<serde_json::Value, AppError> {- let bytes = bytes.to_vec();- let (client, mut server) = UnixStream::pair().unwrap();- std::thread::spawn(move || {- let mut request = [0_u8; 64];- let _ = server.read(&mut request);- let _ = server.write_all(&bytes);- });- exchange(client, b"{}\n", Duration::from_secs(30))- }-- #[test]- fn a_reply_without_its_newline_boundary_is_rejected() {- let error = replied(br#"{"version":"2.5","ok":true}"#).unwrap_err();- assert!(error.to_string().contains("incomplete or oversized"));- }-- #[test]- fn a_reply_with_an_invalid_envelope_is_rejected() {- for reply in [- br#"{"version":"9.9","ok":true}"#.as_slice(),- br#"{"version":"2.5","ok":"yes"}"#.as_slice(),- br#"{"version":"2.5"}"#.as_slice(),- ] {- let mut framed = reply.to_vec();- framed.push(b'\n');- let error = replied(&framed).unwrap_err();- assert!(error.to_string().contains("invalid envelope"));- }- }-}diff --git a/src/command_host/command_host_connect.rs b/src/command_host/command_host_connect.rsdeleted file mode 100644index cf8d728bb..000000000--- a/src/command_host/command_host_connect.rs+++ /dev/null@@ -1,84 +0,0 @@-use std::io;-use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};-use std::os::unix::ffi::OsStrExt;-use std::os::unix::net::UnixStream;-use std::path::Path;-use std::time::Instant;--pub(super) fn connect(path: &Path, deadline: Instant) -> io::Result<UnixStream> {- if Instant::now() >= deadline {- return Err(io::ErrorKind::TimedOut.into());- }- let bytes = path.as_os_str().as_bytes();- let mut address = libc::sockaddr_un {- sun_len: 0,- sun_family: libc::AF_UNIX as libc::sa_family_t,- sun_path: [0; 104],- };- if bytes.contains(&0) || bytes.len() >= address.sun_path.len() {- return Err(io::ErrorKind::InvalidInput.into());- }- for (target, source) in address.sun_path.iter_mut().zip(bytes) {- *target = *source as libc::c_char;- }- address.sun_len = (std::mem::offset_of!(libc::sockaddr_un, sun_path) + bytes.len() + 1) as u8;- let raw = unsafe { libc::socket(libc::AF_UNIX, libc::SOCK_STREAM, 0) };- if raw < 0 {- return Err(io::Error::last_os_error());- }- let socket = unsafe { OwnedFd::from_raw_fd(raw) };- if unsafe { libc::fcntl(raw, libc::F_SETFD, libc::FD_CLOEXEC) } < 0 {- return Err(io::Error::last_os_error());- }- let stream = UnixStream::from(socket);- stream.set_nonblocking(true)?;- let result = unsafe {- libc::connect(- stream.as_raw_fd(),- (&address as *const libc::sockaddr_un).cast(),- address.sun_len as libc::socklen_t,- )- };- if result < 0 {- let error = io::Error::last_os_error();- if !matches!(error.raw_os_error(), Some(libc::EINPROGRESS | libc::EINTR)) {- return Err(error);- }- super::input::wait_ready(stream.as_raw_fd(), libc::POLLOUT, deadline)?;- if let Some(error) = stream.take_error()? {- return Err(error);- }- }- if Instant::now() >= deadline {- return Err(io::ErrorKind::TimedOut.into());- }- stream.set_nonblocking(false)?;- Ok(stream)-}--#[cfg(test)]-mod tests {- use super::super::test_dir::TestDir;- use super::*;- use std::os::unix::net::UnixListener;- use std::time::Duration;-- #[test]- fn expired_connection_budget_does_not_enqueue_a_client() {- let dir = TestDir::new();- let path = dir.path().join("connect.sock");- let listener = UnixListener::bind(&path).unwrap();- listener.set_nonblocking(true).unwrap();- assert_eq!(- connect(&path, Instant::now()).unwrap_err().kind(),- io::ErrorKind::TimedOut- );- assert_eq!(- listener.accept().unwrap_err().kind(),- io::ErrorKind::WouldBlock- );- let stream = connect(&path, Instant::now() + Duration::from_secs(10)).unwrap();- let _accepted = listener.accept().unwrap();- assert!(stream.peer_addr().is_ok());- }-}diff --git a/src/command_host/command_host_endpoint.rs b/src/command_host/command_host_endpoint.rsdeleted file mode 100644index 898bd6818..000000000--- a/src/command_host/command_host_endpoint.rs+++ /dev/null@@ -1,126 +0,0 @@-use agent_desktop_core::AppError;-use std::hash::{Hash, Hasher};-use std::os::unix::fs::{DirBuilderExt, FileTypeExt, MetadataExt};-use std::path::{Path, PathBuf};--pub(super) fn identity(session: Option<&str>) -> Result<String, AppError> {- let executable = std::env::current_exe()?;- let metadata = std::fs::metadata(&executable)?;- Ok(serde_json::to_string(&serde_json::json!({- "protocol": 1,- "root": agent_desktop_core::session::agent_desktop_dir()?,- "session": session,- "executable": executable,- "revision": [metadata.dev(), metadata.ino(), metadata.size()],- "modified": [metadata.mtime(), metadata.mtime_nsec()],- "helper": std::env::var_os("AGENT_DESKTOP_MACOS_HELPER_PATH"),- }))?)-}--pub(super) fn path(identity: &str) -> Result<PathBuf, AppError> {- let parent = std::env::temp_dir();- match validate_directory(&parent) {- Ok(()) => {}- Err(AppError::Io(error)) => return Err(error.into()),- Err(_) => {- return Err(AppError::invalid_input(- "Command host requires a private per-user temporary directory",- ));- }- }- let directory = parent.join(format!("agent-desktop-host-{}", unsafe { libc::geteuid() }));- match std::fs::DirBuilder::new().mode(0o700).create(&directory) {- Ok(()) => {}- Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}- Err(error) => return Err(error.into()),- }- validate_directory(&directory)?;- let mut hash = std::collections::hash_map::DefaultHasher::new();- identity.hash(&mut hash);- Ok(directory.join(format!("{:016x}.sock", hash.finish())))-}--pub(super) fn validate_directory(path: &Path) -> Result<(), AppError> {- let metadata = std::fs::symlink_metadata(path)?;- if !metadata.is_dir()- || metadata.file_type().is_symlink()- || metadata.uid() != unsafe { libc::geteuid() }- || metadata.mode() & 0o077 != 0- {- return Err(AppError::invalid_input(- "Command host directory must be private to the current user",- ));- }- Ok(())-}--pub(super) fn validate_socket(path: &Path) -> Result<bool, AppError> {- let metadata = match std::fs::symlink_metadata(path) {- Ok(metadata) => metadata,- Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),- Err(error) => return Err(error.into()),- };- if !metadata.file_type().is_socket()- || metadata.uid() != unsafe { libc::geteuid() }- || metadata.mode() & 0o077 != 0- {- return Err(AppError::invalid_input(- "Command host endpoint is not a private socket",- ));- }- Ok(true)-}--#[cfg(test)]-mod tests {- use super::super::test_dir::TestDir;- use super::*;- use std::os::unix::fs::PermissionsExt;- use std::os::unix::net::UnixListener;-- fn subdirectory(root: &TestDir, name: &str) -> PathBuf {- let path = root.path().join(name);- std::fs::create_dir(&path).unwrap();- path- }-- #[test]- fn directory_validation_rejects_every_non_private_arm() {- let root = TestDir::new();- let loose = subdirectory(&root, "loose");- std::fs::set_permissions(&loose, std::fs::Permissions::from_mode(0o755)).unwrap();- assert!(validate_directory(&loose).is_err());-- let file = loose.join("file");- std::fs::write(&file, b"x").unwrap();- assert!(validate_directory(&file).is_err());-- let target = subdirectory(&root, "target");- let link = root.path().join("link");- std::os::unix::fs::symlink(&target, &link).unwrap();- assert!(validate_directory(&link).is_err());-- let private = subdirectory(&root, "private");- std::fs::set_permissions(&private, std::fs::Permissions::from_mode(0o700)).unwrap();- assert!(validate_directory(&private).is_ok());- }-- #[test]- fn socket_validation_rejects_non_sockets_and_loose_modes() {- let root = TestDir::new();- let dir = root.path();- let missing = dir.join("missing.sock");- assert!(!validate_socket(&missing).unwrap());-- let file = dir.join("file.sock");- std::fs::write(&file, b"x").unwrap();- assert!(validate_socket(&file).is_err());-- let socket = dir.join("ok.sock");- let _listener = UnixListener::bind(&socket).unwrap();- std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o644)).unwrap();- assert!(validate_socket(&socket).is_err());- std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o600)).unwrap();- assert!(validate_socket(&socket).unwrap());- }-}diff --git a/src/command_host/command_host_input.rs b/src/command_host/command_host_input.rsdeleted file mode 100644index 5bf711dab..000000000--- a/src/command_host/command_host_input.rs+++ /dev/null@@ -1,125 +0,0 @@-use std::io::{self, BufRead, BufReader, Read};-use std::os::fd::AsRawFd;-use std::time::{Duration, Instant};--pub(super) fn read_frame(- input: &mut BufReader<impl Read + AsRawFd>,- limit: usize,- idle: Duration,- frame: Duration,-) -> io::Result<Vec<u8>> {- let mut deadline = Instant::now() + idle;- let mut bytes = Vec::new();- loop {- if Instant::now() >= deadline {- return Err(io::ErrorKind::TimedOut.into());- }- if input.buffer().is_empty() {- wait_ready(input.get_ref().as_raw_fd(), libc::POLLIN, deadline)?;- }- if Instant::now() >= deadline {- return Err(io::ErrorKind::TimedOut.into());- }- let available = input.fill_buf()?;- if available.is_empty() {- return Ok(bytes);- }- if bytes.is_empty() {- deadline = Instant::now() + frame;- }- let count = available- .iter()- .position(|byte| *byte == b'\n')- .map_or(available.len(), |index| index + 1)- .min(limit.saturating_add(1).saturating_sub(bytes.len()));- bytes.extend_from_slice(&available[..count]);- input.consume(count);- if bytes.last() == Some(&b'\n') || bytes.len() > limit {- return Ok(bytes);- }- }-}--pub(super) fn wait_ready(fd: std::os::fd::RawFd, events: i16, deadline: Instant) -> io::Result<()> {- loop {- let remaining = deadline.saturating_duration_since(Instant::now());- if remaining.is_zero() {- return Err(io::ErrorKind::TimedOut.into());- }- let timeout = i32::try_from(remaining.as_millis().saturating_add(1)).unwrap_or(i32::MAX);- let mut poll = libc::pollfd {- fd,- events,- revents: 0,- };- let result = unsafe { libc::poll(&mut poll, 1, timeout) };- if result > 0 {- return if poll.revents & libc::POLLNVAL == 0 {- Ok(())- } else {- Err(io::ErrorKind::InvalidInput.into())- };- }- if result < 0 {- let error = io::Error::last_os_error();- if error.kind() != io::ErrorKind::Interrupted {- return Err(error);- }- }- }-}--#[cfg(test)]-mod tests {- use super::*;- use std::io::Write;- use std::os::unix::net::UnixStream;-- #[test]- fn buffered_requests_are_separate_and_do_not_wait_for_more_input() {- let (mut sender, receiver) = UnixStream::pair().unwrap();- sender.write_all(b"[]\n[\"version\"]\n").unwrap();- let mut input = BufReader::new(receiver);- let budget = Duration::from_secs(60);- assert_eq!(- read_frame(&mut input, 100, budget, budget).unwrap(),- b"[]\n"- );- assert_eq!(- read_frame(&mut input, 100, budget, budget).unwrap(),- b"[\"version\"]\n"- );- }-- #[test]- fn a_partial_frame_has_a_deadline_even_while_its_sender_stays_connected() {- let (mut sender, receiver) = UnixStream::pair().unwrap();- sender.write_all(b"[").unwrap();- let error = read_frame(- &mut BufReader::new(receiver),- 100,- Duration::from_secs(60),- Duration::ZERO,- )- .unwrap_err();- assert_eq!(error.kind(), io::ErrorKind::TimedOut);- }-- #[test]- fn expired_idle_budget_does_not_consume_a_queued_request() {- let (mut sender, receiver) = UnixStream::pair().unwrap();- sender.write_all(b"[]\n").unwrap();- let mut input = BufReader::new(receiver);- assert_eq!(- read_frame(&mut input, 100, Duration::ZERO, Duration::ZERO)- .unwrap_err()- .kind(),- io::ErrorKind::TimedOut- );- let budget = Duration::from_secs(60);- assert_eq!(- read_frame(&mut input, 100, budget, budget).unwrap(),- b"[]\n"- );- }-}diff --git a/src/command_host/command_host_output.rs b/src/command_host/command_host_output.rsdeleted file mode 100644index b6fe91df6..000000000--- a/src/command_host/command_host_output.rs+++ /dev/null@@ -1,126 +0,0 @@-use std::io::{self, Write};-use std::os::fd::AsRawFd;-use std::time::{Duration, Instant};--pub(super) struct BoundedWriter<W: Write + AsRawFd> {- output: W,- original_flags: i32,- timeout: Duration,- deadline: Option<Instant>,-}--impl<W: Write + AsRawFd> BoundedWriter<W> {- pub(super) fn new(output: W, timeout: Duration) -> io::Result<Self> {- let original_flags = unsafe { libc::fcntl(output.as_raw_fd(), libc::F_GETFL) };- if original_flags < 0 {- return Err(io::Error::last_os_error());- }- if unsafe {- libc::fcntl(- output.as_raw_fd(),- libc::F_SETFL,- original_flags | libc::O_NONBLOCK,- )- } < 0- {- return Err(io::Error::last_os_error());- }- Ok(Self {- output,- original_flags,- timeout,- deadline: None,- })- }-- fn attempt<T>(&mut self, mut operation: impl FnMut(&mut W) -> io::Result<T>) -> io::Result<T> {- let deadline = *self- .deadline- .get_or_insert_with(|| Instant::now() + self.timeout);- loop {- if Instant::now() >= deadline {- return Err(io::ErrorKind::TimedOut.into());- }- match operation(&mut self.output) {- Err(error) if error.kind() == io::ErrorKind::WouldBlock => {- super::input::wait_ready(self.output.as_raw_fd(), libc::POLLOUT, deadline)?;- }- Err(error) if error.kind() == io::ErrorKind::Interrupted => {}- result => return result,- }- }- }-}--impl<W: Write + AsRawFd> Write for BoundedWriter<W> {- fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {- self.attempt(|output| output.write(bytes))- }-- fn flush(&mut self) -> io::Result<()> {- self.attempt(Write::flush)?;- self.deadline = None;- Ok(())- }-}--impl<W: Write + AsRawFd> Drop for BoundedWriter<W> {- fn drop(&mut self) {- unsafe { libc::fcntl(self.output.as_raw_fd(), libc::F_SETFL, self.original_flags) };- }-}--#[cfg(test)]-mod tests {- use super::*;- use std::io::Read;- use std::os::unix::net::UnixStream;-- #[test]- fn output_deadline_stops_dispatch_after_one_command() {- let (sender, _unread_receiver) = UnixStream::pair().unwrap();- let writer = BoundedWriter::new(sender, Duration::from_millis(20)).unwrap();- let mut calls = 0;- let error = super::super::serve(io::Cursor::new(b"[]\n[]\n"), writer, |_| {- calls += 1;- agent_desktop_core::response::output::Response::ok(- "snapshot",- serde_json::json!({- "tree": "x".repeat(4 * 1024 * 1024),- }),- )- })- .unwrap_err();- assert!(matches!(error, agent_desktop_core::AppError::Io(error)- if error.kind() == io::ErrorKind::TimedOut));- assert_eq!(calls, 1);- }-- #[test]- fn complete_frames_reset_the_budget_and_restore_nonblocking_mode() {- for initially_nonblocking in [false, true] {- let (sender, mut receiver) = UnixStream::pair().unwrap();- sender.set_nonblocking(initially_nonblocking).unwrap();- {- let mut writer =- BoundedWriter::new(sender.try_clone().unwrap(), Duration::from_secs(60))- .unwrap();- let flags = unsafe { libc::fcntl(sender.as_raw_fd(), libc::F_GETFL) };- assert!(flags >= 0);- assert_ne!(flags & libc::O_NONBLOCK, 0);- writer.write_all(b"one\n").unwrap();- assert!(writer.deadline.is_some());- writer.flush().unwrap();- assert!(writer.deadline.is_none());- writer.write_all(b"two\n").unwrap();- writer.flush().unwrap();- }- let flags = unsafe { libc::fcntl(sender.as_raw_fd(), libc::F_GETFL) };- assert!(flags >= 0);- assert_eq!(flags & libc::O_NONBLOCK != 0, initially_nonblocking);- let mut bytes = [0; 8];- receiver.read_exact(&mut bytes).unwrap();- assert_eq!(&bytes, b"one\ntwo\n");- }- }-}diff --git a/src/command_host/command_host_request.rs b/src/command_host/command_host_request.rsdeleted file mode 100644index 646c7c0d8..000000000--- a/src/command_host/command_host_request.rs+++ /dev/null@@ -1,92 +0,0 @@-use agent_desktop_core::{AppError, response::output::Response};-use serde::{Deserialize, Serialize};-use std::path::PathBuf;--#[derive(Serialize, Deserialize)]-#[serde(deny_unknown_fields)]-pub(super) struct HostRequest {- pub identity: String,- pub args: Vec<String>,- pub directory: PathBuf,- pub agent_id: Option<String>,- pub expires_ns: u64,- #[serde(default)]- pub baseline: Option<agent_desktop_core::SignalBaseline>,-}--pub(super) fn execute(bytes: &[u8], identity: &str, session: Option<&str>) -> Response {- match prepare(bytes, identity, session) {- Ok((cli, command, deadline, baseline)) => crate::response(- command.name(),- crate::execute_with_deadline(cli, command, Some(deadline), baseline),- ),- Err(error) => crate::response("unknown", Err(crate::pre_dispatch_error(error))),- }-}--fn prepare(- bytes: &[u8],- identity: &str,- session: Option<&str>,-) -> Result<- (- crate::Cli,- crate::Commands,- agent_desktop_core::Deadline,- Option<agent_desktop_core::SignalBaseline>,- ),- AppError,-> {- let request: HostRequest = serde_json::from_slice(bytes)- .map_err(|_| AppError::invalid_input("Invalid command host request envelope"))?;- if request.identity != identity {- return Err(AppError::invalid_input(- "Command host identity does not match the caller",- ));- }- if !request.directory.is_absolute() {- return Err(AppError::invalid_input(- "Command host working directory must be absolute",- ));- }- let (mut cli, command) = super::parse_request(&serde_json::to_vec(&request.args)?, session)?;- if cli.identity.agent_id.is_none() {- cli.identity.agent_id = request.agent_id;- }- let deadline =- agent_desktop_core::Deadline::from_duration(super::budget::remaining(request.expires_ns)?)?;- std::env::set_current_dir(&request.directory)?;- Ok((cli, command, deadline, request.baseline))-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn wrong_identity_or_namespace_never_changes_the_working_directory() {- let before = std::env::current_dir().unwrap();- for (identity, args) in [- ("another executable", vec!["version"]),- ("owner", vec!["--session", "other", "version"]),- ] {- let bytes = serde_json::to_vec(&HostRequest {- identity: identity.into(),- args: args.into_iter().map(str::to_owned).collect(),- directory: PathBuf::from("/"),- agent_id: None,- expires_ns: u64::MAX,- baseline: None,- })- .unwrap();- let response = execute(&bytes, "owner", Some("mine"));- let response = serde_json::to_value(response).unwrap();- assert_eq!(response["ok"], false);- assert_eq!(- response["error"]["disposition"]["delivery"],- "not_delivered"- );- assert_eq!(std::env::current_dir().unwrap(), before);- }- }-}diff --git a/src/command_host/command_host_socket.rs b/src/command_host/command_host_socket.rsdeleted file mode 100644index bae7ad3ee..000000000--- a/src/command_host/command_host_socket.rs+++ /dev/null@@ -1,147 +0,0 @@-use agent_desktop_core::{AppError, response::output::Response};-use std::io::{self, BufReader, BufWriter};-use std::os::fd::AsRawFd;-use std::os::unix::fs::PermissionsExt;-use std::os::unix::net::{UnixListener, UnixStream};-use std::path::Path;-use std::time::Instant;--pub(super) fn run(- path: &Path,- mut execute: impl FnMut(&[u8]) -> Response,- stop_after_reply: impl Fn() -> bool,-) -> Result<(), AppError> {- validate_parent(path)?;- let _owner = agent_desktop_core::FileLock::acquire(- &path.with_extension("owner.lock"),- agent_desktop_core::Deadline::after(1000)?,- "command host ownership",- )?;- if super::endpoint::validate_socket(path)? {- std::fs::remove_file(path)?;- }- let listener = UnixListener::bind(path)?;- std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;- listener.set_nonblocking(true)?;- loop {- match super::input::wait_ready(- listener.as_raw_fd(),- libc::POLLIN,- Instant::now() + super::IDLE_TIMEOUT,- ) {- Err(error) if error.kind() == io::ErrorKind::TimedOut => return Ok(()),- result => result?,- }- let stream = match listener.accept() {- Ok((stream, _)) => stream,- Err(error) if error.kind() == io::ErrorKind::WouldBlock => continue,- Err(error) => return Err(error.into()),- };- if let Err(error) = serve_connection(stream, &mut execute) {- tracing::warn!(%error, "command host connection ended without a complete reply");- }- if stop_after_reply() {- return Ok(());- }- }-}--fn validate_parent(path: &Path) -> Result<(), AppError> {- let parent = path- .parent()- .filter(|_| path.is_absolute())- .ok_or_else(|| AppError::invalid_input("Command host socket requires an absolute path"))?;- super::endpoint::validate_directory(parent)-}--fn serve_connection(- stream: UnixStream,- execute: impl FnMut(&[u8]) -> Response,-) -> Result<(), AppError> {- let mut uid = 0;- let mut gid = 0;- if unsafe { libc::getpeereid(stream.as_raw_fd(), &mut uid, &mut gid) } != 0 {- return Err(io::Error::last_os_error().into());- }- if uid != unsafe { libc::geteuid() } {- return Err(AppError::invalid_input(- "Command host peer has a different owner",- ));- }- let mut input = BufReader::new(stream.try_clone()?);- let mut consumed = false;- super::serve_frames(- || {- if consumed {- return Ok(Vec::new());- }- consumed = true;- super::input::read_frame(- &mut input,- super::MAX_REQUEST_BYTES as usize,- super::IO_TIMEOUT,- super::IO_TIMEOUT,- )- },- BufWriter::new(super::output::BoundedWriter::new(- stream,- super::IO_TIMEOUT,- )?),- execute,- )-}--#[cfg(test)]-mod tests {- use super::*;- use std::io::{Read, Write};-- #[test]- fn the_host_returns_after_a_reply_that_asks_it_to_stop() {- let scratch = super::super::test_dir::TestDir::new();- std::fs::set_permissions(scratch.path(), std::fs::Permissions::from_mode(0o700)).unwrap();- let path = scratch.path().join("h.sock");- let (finished, result) = std::sync::mpsc::channel();- let server_path = path.clone();- std::thread::spawn(move || {- let outcome = run(- &server_path,- |_| Response::ok("version", serde_json::json!({})),- || true,- );- finished.send(outcome.is_ok()).unwrap();- });- let give_up = Instant::now() + std::time::Duration::from_secs(10);- let mut client = loop {- if let Ok(stream) = UnixStream::connect(&path) {- break stream;- }- assert!(Instant::now() < give_up, "host did not bind");- std::thread::sleep(std::time::Duration::from_millis(10));- };- client.write_all(b"[]\n").unwrap();- let mut reply = Vec::new();- client.read_to_end(&mut reply).unwrap();- assert!(!reply.is_empty());- assert_eq!(- result.recv_timeout(std::time::Duration::from_secs(10)),- Ok(true)- );- }-- #[test]- fn each_connection_dispatches_only_one_request() {- let (server, mut client) = UnixStream::pair().unwrap();- client.write_all(b"[]\n[]\n").unwrap();- let mut calls = 0;- serve_connection(server, |_| {- calls += 1;- Response::ok("version", serde_json::json!({}))- })- .unwrap();- let mut bytes = Vec::new();- client.read_to_end(&mut bytes).unwrap();- assert_eq!(calls, 1);- assert_eq!(bytes.iter().filter(|byte| **byte == b'\n').count(), 1);- }-}diff --git a/src/command_host/command_host_test_dir.rs b/src/command_host/command_host_test_dir.rsdeleted file mode 100644index 26a10ed9e..000000000--- a/src/command_host/command_host_test_dir.rs+++ /dev/null@@ -1,29 +0,0 @@-use std::path::{Path, PathBuf};-use std::sync::atomic::{AtomicU64, Ordering};--static NEXT: AtomicU64 = AtomicU64::new(0);--pub(super) struct TestDir(PathBuf);--impl TestDir {- pub(super) fn new() -> Self {- let path = std::env::temp_dir().join(format!(- "ad-host-{}-{}",- std::process::id(),- NEXT.fetch_add(1, Ordering::Relaxed)- ));- let _ = std::fs::remove_dir_all(&path);- std::fs::create_dir(&path).unwrap();- Self(path)- }-- pub(super) fn path(&self) -> &Path {- &self.0- }-}--impl Drop for TestDir {- fn drop(&mut self) {- let _ = std::fs::remove_dir_all(&self.0);- }-}diff --git a/src/command_host/mod.rs b/src/command_host/mod.rsdeleted file mode 100644index 130981b25..000000000--- a/src/command_host/mod.rs+++ /dev/null@@ -1,348 +0,0 @@-use agent_desktop_core::{AppError, response::output::Response, session::resolve_active_session};-use clap::Parser;-use std::io::Write;-#[cfg(test)]-use std::io::{BufRead, Read};-use std::os::fd::AsFd;--const MAX_REQUEST_BYTES: u64 = 1_048_576;-const RETAINED_PRUNE_INTERVAL: usize = 4_096;-const IDLE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(900);-const IO_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);--pub(crate) fn is_host_process() -> bool {- std::env::var("AGENT_DESKTOP_INTERNAL_COMMAND_HOST").as_deref() == Ok("1")-}--#[path = "command_host_batch.rs"]-mod batch;-pub(crate) use batch::forward_batch_item;--#[path = "command_host_budget.rs"]-mod budget;--#[path = "command_host_client.rs"]-mod client;-#[path = "command_host_connect.rs"]-mod connect;-#[path = "command_host_endpoint.rs"]-mod endpoint;-#[path = "command_host_input.rs"]-mod input;-#[path = "command_host_output.rs"]-mod output;-#[path = "command_host_request.rs"]-mod request;-#[path = "command_host_socket.rs"]-mod socket;-#[cfg(test)]-#[path = "command_host_test_dir.rs"]-mod test_dir;--pub(crate) fn forward(- cli: &crate::Cli,- command: &crate::Commands,-) -> Result<serde_json::Value, AppError> {- client::forward(cli, command)-}--pub(crate) fn run() -> Result<(), AppError> {- let session =- resolve_active_session(None, std::env::var("AGENT_DESKTOP_SESSION").ok().as_deref())?;- let owner = agent_desktop_macos::RetainedRefSession::start()?;- let store = agent_desktop_core::refs::refs_store::RefStore::for_session(session.as_deref())?;- let mut next_prune = RETAINED_PRUNE_INTERVAL;- let identity = endpoint::identity(session.as_deref())?;- let socket_path = std::env::var_os("AGENT_DESKTOP_INTERNAL_HOST_SOCKET");- let reported_missing_permission = std::cell::Cell::new(false);- let execute = |bytes: &[u8]| {- if owner.capture_count() >= next_prune {- match store.retained_object_tokens() {- Ok(tokens) => owner.retain(&tokens),- Err(error) => {- tracing::warn!(%error, "retained-token inventory failed; pruning deferred");- }- }- next_prune = owner- .capture_count()- .saturating_add(RETAINED_PRUNE_INTERVAL);- }- let response = if socket_path.is_some() {- request::execute(bytes, &identity, session.as_deref())- } else {- execute_request(bytes, session.as_deref())- };- if reports_missing_permission(&response) {- reported_missing_permission.set(true);- }- response- };- if let Some(ref path) = socket_path {- return socket::run(std::path::Path::new(&path), execute, || {- reported_missing_permission.get()- });- }- let input = std::io::stdin();- let output = std::fs::File::from(std::io::stdout().as_fd().try_clone_to_owned()?);- let mut input = std::io::BufReader::new(input.lock());- serve_frames(- || {- input::read_frame(- &mut input,- MAX_REQUEST_BYTES as usize,- IDLE_TIMEOUT,- IO_TIMEOUT,- )- },- std::io::BufWriter::new(output::BoundedWriter::new(output, IO_TIMEOUT)?),- execute,- )?;- Ok(())-}--/// macOS keeps the Accessibility answer a process read before a grant, so a-/// host that told a caller a permission is missing exits after that reply and-/// the next call starts a host that sees the new grant.-fn reports_missing_permission(response: &Response) -> bool {- let denied = |report: &serde_json::Value| report["accessibility"]["state"] == "denied";- response- .error- .as_ref()- .is_some_and(|error| error.code == "PERM_DENIED")- || response- .data- .as_ref()- .is_some_and(|data| denied(data) || denied(&data["permissions"]))-}--fn execute_request(bytes: &[u8], session: Option<&str>) -> Response {- let result = parse_request(bytes, session);- match result {- Ok((cli, command)) => {- let name = command.name();- crate::response(name, crate::execute(cli, command))- }- Err(error) => crate::response("unknown", Err(error)),- }-}--fn parse_request(- bytes: &[u8],- session: Option<&str>,-) -> Result<(crate::Cli, crate::Commands), AppError> {- let args: Vec<String> = serde_json::from_slice(bytes).map_err(|_| {- AppError::invalid_input("Host request must be a JSON array of CLI arguments")- })?;- let mut cli =- crate::Cli::try_parse_from(std::iter::once("agent-desktop".to_owned()).chain(args))- .map_err(|error| {- AppError::invalid_input(crate::diagnostic::bounded_text(&error.to_string(), 512))- })?;- let selected = resolve_active_session(cli.identity.session.as_deref(), session)?;- if selected.as_deref() != session {- return Err(AppError::invalid_input(- "A command host cannot switch snapshot namespaces",- ));- }- let command = cli- .command- .take()- .ok_or_else(|| AppError::invalid_input("Host request requires a command"))?;- Ok((cli, command))-}--#[cfg(test)]-fn serve(- mut input: impl BufRead,- output: impl Write,- execute: impl FnMut(&[u8]) -> Response,-) -> Result<(), AppError> {- serve_frames(- || {- let mut bytes = Vec::new();- input- .by_ref()- .take(MAX_REQUEST_BYTES + 1)- .read_until(b'\n', &mut bytes)?;- Ok(bytes)- },- output,- execute,- )-}--fn serve_frames(- mut read_frame: impl FnMut() -> std::io::Result<Vec<u8>>,- mut output: impl Write,- mut execute: impl FnMut(&[u8]) -> Response,-) -> Result<(), AppError> {- loop {- let bytes = read_frame().map_err(|error| {- if error.kind() == std::io::ErrorKind::TimedOut {- AppError::Adapter(- agent_desktop_core::AdapterError::timeout(- "Command host request did not arrive before its input deadline",- )- .with_disposition(agent_desktop_core::DeliverySemantics::not_delivered()),- )- } else {- AppError::from(error)- }- })?;- if bytes.is_empty() {- return Ok(());- }- let oversized = bytes.len() as u64 > MAX_REQUEST_BYTES;- let incomplete = bytes.last() != Some(&b'\n');- let response = if oversized || incomplete {- crate::response(- "unknown",- Err(AppError::invalid_input(- "Host request is oversized or lacks its newline terminator",- )),- )- } else {- execute(&bytes)- };- serde_json::to_writer(&mut output, &response).map_err(|error| {- std::io::Error::new(- error.io_error_kind().unwrap_or(std::io::ErrorKind::Other),- error,- )- })?;- output.write_all(b"\n")?;- output.flush()?;- if oversized || incomplete {- return Ok(());- }- }-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn a_host_stops_after_it_reports_a_missing_permission() {- let report = |accessibility: &str| serde_json::json!({ "accessibility": { "state": accessibility } });- assert!(reports_missing_permission(&Response::ok(- "permissions",- report("denied")- )));- assert!(reports_missing_permission(&Response::ok(- "status",- serde_json::json!({ "permissions": report("denied") })- )));- assert!(reports_missing_permission(&crate::response(- "snapshot",- Err(AppError::Adapter(- agent_desktop_core::AdapterError::permission_denied()- ))- )));- assert!(!reports_missing_permission(&Response::ok(- "permissions",- report("granted")- )));- assert!(!reports_missing_permission(&Response::ok(- "version",- serde_json::json!({})- )));- }-- #[test]- fn repeated_commands_reuse_dispatch_and_preserve_envelopes() {- let mut output = Vec::new();- serve(- std::io::Cursor::new(b"[\"version\"]\n[\"version\"]\n"),- &mut output,- |bytes| execute_request(bytes, None),- )- .unwrap();- let responses: Vec<serde_json::Value> = output- .split(|byte| *byte == b'\n')- .filter(|line| !line.is_empty())- .map(|line| serde_json::from_slice(line).unwrap())- .collect();- assert_eq!(responses.len(), 2);- assert!(- responses- .iter()- .all(|response| response["ok"] == true && response["command"] == "version")- );- }-- #[test]- fn incomplete_or_oversized_frames_never_dispatch() {- for bytes in [- b"[\"version\"]".to_vec(),- vec![b'x'; MAX_REQUEST_BYTES as usize + 1],- ] {- let mut output = Vec::new();- serve(std::io::Cursor::new(bytes), &mut output, |_| {- panic!("must not dispatch")- })- .unwrap();- let response: serde_json::Value = serde_json::from_slice(&output).unwrap();- assert_eq!(response["error"]["code"], "INVALID_ARGS");- assert_eq!(- response["error"]["disposition"]["delivery"],- "not_delivered"- );- }- }-- #[test]- fn request_cannot_cross_session_namespace() {- assert!(parse_request(b"[\"--session\",\"other\",\"version\"]", Some("owner")).is_err());- assert!(parse_request(b"[\"--session\",\"owner\",\"version\"]", Some("owner")).is_ok());- assert!(parse_request(b"[\"version\"]", Some("owner")).is_ok());- }-- #[test]- fn a_lost_reply_never_replays_the_command() {- let mut attempts = 0;- let error = serve(std::io::Cursor::new(b"[]\n[]\n"), RejectWrites, |_| {- attempts += 1;- Response::ok("click", serde_json::json!({}))- })- .unwrap_err();- assert!(- matches!(error, AppError::Io(error) if error.kind() == std::io::ErrorKind::BrokenPipe)- );- assert_eq!(attempts, 1);- }-- #[test]- fn a_frame_timeout_never_dispatches_or_reads_another_request() {- let mut reads = 0;- let error = serve_frames(- || {- reads += 1;- Err(std::io::ErrorKind::TimedOut.into())- },- Vec::new(),- |_| panic!("timed-out frame must not dispatch"),- )- .unwrap_err();- let response = crate::response("host", Err(error));- let response = serde_json::to_value(response).unwrap();- assert_eq!(response["error"]["code"], "TIMEOUT");- assert_eq!(- response["error"]["disposition"]["delivery"],- "not_delivered"- );- assert_eq!(reads, 1);- }-- struct RejectWrites;-- impl Write for RejectWrites {- fn write(&mut self, _bytes: &[u8]) -> std::io::Result<usize> {- Err(std::io::ErrorKind::BrokenPipe.into())- }-- fn flush(&mut self) -> std::io::Result<()> {- Ok(())- }- }-}diff --git a/src/dispatch/session.rs b/src/dispatch/session.rsindex 06fb0bc86..67b19aafb 100644--- a/src/dispatch/session.rs+++ b/src/dispatch/session.rs@@ -27,19 +27,11 @@ pub(crate) fn dispatch(}SessionAction::End(e) => {let id = resolve_end_session_id(e.id, context.session_id())?;- if context.session_namespace_is_pinned() && Some(id.as_str()) != context.session_id() {- return Err(AppError::invalid_input(- "A command host cannot end a foreign session",- ));- }let value = session::execute(session::SessionAction::End { id: id.clone() })?;super::cursor_overlay::tear_down(adapter, &CursorOverlayControl::disable(id))?;Ok(value)}SessionAction::List => session::execute(session::SessionAction::List),- SessionAction::Gc(_) if context.session_namespace_is_pinned() => Err(- AppError::invalid_input("A command host cannot run global session garbage collection"),- ),SessionAction::Gc(g) => session::execute(session::SessionAction::Gc {older_than_secs: g.older_than,ended_only: g.ended,diff --git a/src/dispatch/session_tests.rs b/src/dispatch/session_tests.rsindex 69fe07a70..53ca30283 100644--- a/src/dispatch/session_tests.rs+++ b/src/dispatch/session_tests.rs@@ -211,68 +211,6 @@ fn session_end_reports_uncertain_when_overlay_teardown_fails_after_persisting()assert!(home.path().join("sessions").join(manifest.id).is_dir());}-#[test]-fn a_pinned_namespace_rejects_foreign_session_end_and_global_gc() {- let context = CommandContext::default().with_pinned_session_namespace();- let foreign_end = super::dispatch(- SessionArgs {- action: SessionAction::End(SessionEndArgs {- id: Some("other".into()),- }),- },- &NoopAdapter,- &context,- )- .expect_err("ending a foreign session must be rejected");- assert_eq!(foreign_end.code(), "INVALID_ARGS");- assert!(- foreign_end- .to_string()- .contains("cannot end a foreign session")- );-- let global_gc = super::dispatch(- SessionArgs {- action: SessionAction::Gc(SessionGcArgs {- older_than: None,- ended: false,- }),- },- &NoopAdapter,- &context,- )- .expect_err("global gc must be rejected in a pinned namespace");- assert_eq!(global_gc.code(), "INVALID_ARGS");-}--#[test]-fn a_pinned_namespace_still_allows_ending_its_own_session() {- let _home = HomeGuard::new();- let manifest = agent_desktop_core::session::start_session(StartSessionOptions {- trace: SessionTraceMode::Off,- artifacts: ArtifactsMode::Events,- name: None,- })- .unwrap();- let context = CommandContext::new(Some(manifest.id.clone()), None, false)- .unwrap()- .with_pinned_session_namespace();- let result = super::dispatch(- SessionArgs {- action: SessionAction::End(SessionEndArgs {- id: Some(manifest.id.clone()),- }),- },- &NoopAdapter,- &context,- );- result.expect("a pinned namespace may end its own session");- let ended = agent_desktop_core::session::read_manifest(&manifest.id)- .unwrap()- .expect("manifest remains readable");- assert!(ended.ended_at.is_some());-}-#[test]fn session_gc_ended_reclaims_an_ended_session_that_recorded_trace_events() {let home = HomeGuard::new();diff --git a/src/main.rs b/src/main.rsindex c889b9fb1..788faee98 100644--- a/src/main.rs+++ b/src/main.rs@@ -3,8 +3,6 @@mod batch;mod cli;mod cli_args;-#[cfg(target_os = "macos")]-mod command_host;mod command_policy;mod diagnostic;mod dispatch;@@ -33,10 +31,6 @@ use std::process::ExitCode;const EXIT_INVALID_ARGS: u8 = 2;fn main() -> ExitCode {- #[cfg(target_os = "macos")]- if command_host::is_host_process() {- unsafe { libc::umask(0o077) };- }let code = run_command();#[cfg(target_os = "linux")]agent_desktop_linux::end_input_session();@@ -60,14 +54,7 @@ fn run_command() -> ExitCode {return ExitCode::from(exit_code);}#[cfg(target_os = "macos")]- if command_host::is_host_process() {- init_tracing(false);- return match command_host::run() {- Ok(()) => ExitCode::SUCCESS,- Err(AppError::Io(error)) => report_output_failure(error),- Err(error) => finish("host", Err(error)),- };- }+ agent_desktop_macos::stop_legacy_command_hosts();run()}@@ -131,17 +118,6 @@ fn run() -> ExitCode {};let cmd_name = cmd.name();- #[cfg(target_os = "macos")]- if !cmd.needs_caller_process() {- return match command_host::forward(&cli, &cmd) {- Ok(response) => match emit_response(&response) {- Err(error) => report_output_failure(error),- Ok(()) if response["ok"] == true => ExitCode::SUCCESS,- Ok(()) => ExitCode::FAILURE,- },- Err(error) => finish(cmd_name, Err(error)),- };- }finish(cmd_name, execute(cli, cmd))}@@ -197,10 +173,6 @@ fn execute_with_deadline(let mut context = context.with_agent_id(agent_id).map_err(pre_dispatch_error)?;- #[cfg(target_os = "macos")]- if command_host::is_host_process() {- context = context.with_pinned_session_namespace();- }if let Some(deadline) = deadline {context = context.with_inherited_deadline(deadline);}diff --git a/src/tests/command_host_absent.rs b/src/tests/command_host_absent.rsnew file mode 100644index 000000000..d48c3e158--- /dev/null+++ b/src/tests/command_host_absent.rs@@ -0,0 +1,173 @@+#![cfg(target_os = "macos")]++use std::os::unix::fs::{DirBuilderExt, MetadataExt};+use std::os::unix::net::UnixListener;+use std::os::unix::process::ExitStatusExt;+use std::path::{Path, PathBuf};+use std::process::{Child, Command, ExitStatus, Output, Stdio};+use std::sync::Mutex;+use std::time::{Duration, Instant};++const MARKER: &str = "AGENT_DESKTOP_INTERNAL_COMMAND_HOST";+const SIGKILL: i32 = 9;++static HOST_TEST_LOCK: Mutex<()> = Mutex::new(());++struct KilledOnDrop(Child);++impl Drop for KilledOnDrop {+ fn drop(&mut self) {+ let _ = self.0.kill();+ let _ = self.0.wait();+ }+}++fn private_dir(label: &str) -> PathBuf {+ let path = PathBuf::from(format!("/tmp/adh-{label}-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&path);+ std::fs::DirBuilder::new()+ .mode(0o700)+ .create(&path)+ .expect("create private dir");+ path+}++fn run(args: &[&str], tmpdir: &Path) -> Output {+ let output = Command::new(env!("CARGO_BIN_EXE_agent-desktop"))+ .args(args)+ .env("TMPDIR", tmpdir)+ .env("AGENT_DESKTOP_HOME", tmpdir.join("home"))+ .env_remove(MARKER)+ .stdin(Stdio::null())+ .output()+ .expect("binary runs");+ assert!(output.status.success(), "{args:?}: {output:?}");+ output+}++fn spawn_renamed_copy(tmpdir: &Path, name: &str, marked: bool, args: &[&str]) -> KilledOnDrop {+ let executable = tmpdir.join(name);+ std::fs::copy(env!("CARGO_BIN_EXE_agent-desktop"), &executable).expect("copy binary");+ let mut command = Command::new(&executable);+ command+ .args(args)+ .env("TMPDIR", tmpdir)+ .env("AGENT_DESKTOP_HOME", tmpdir.join("home"))+ .env_remove(MARKER)+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null());+ if marked {+ command.env(MARKER, "1");+ }+ KilledOnDrop(command.spawn().expect("copy starts"))+}++fn exit_within(child: &mut KilledOnDrop, limit: Duration) -> Option<ExitStatus> {+ let deadline = Instant::now() + limit;+ while Instant::now() < deadline {+ if let Some(status) = child.0.try_wait().expect("poll child") {+ return Some(status);+ }+ std::thread::sleep(Duration::from_millis(20));+ }+ None+}++#[test]+fn commands_never_reach_or_remove_a_command_host_socket() {+ let _lock = HOST_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());+ let tmpdir = private_dir("socket");+ let uid = std::fs::metadata(&tmpdir).expect("stat tmpdir").uid();+ let host_dir = tmpdir.join(format!("agent-desktop-host-{uid}"));+ std::fs::DirBuilder::new()+ .mode(0o700)+ .create(&host_dir)+ .expect("create host dir");+ let socket = host_dir.join("0123456789abcdef.sock");+ let listener = UnixListener::bind(&socket).expect("bind decoy socket");+ listener.set_nonblocking(true).expect("nonblocking");++ run(&["version"], &tmpdir);+ run(&["list-apps"], &tmpdir);+ run(&["batch", r#"[{"command":"version"}]"#], &tmpdir);++ assert!(+ matches!(listener.accept(), Err(error) if error.kind() == std::io::ErrorKind::WouldBlock),+ "a command connected to the host socket"+ );+ assert!(socket.exists(), "a command removed the socket file");+ let entries: Vec<_> = std::fs::read_dir(&host_dir)+ .expect("read host dir")+ .map(|entry| entry.expect("read host entry").path())+ .collect();+ assert_eq!(entries, vec![socket], "a command created host files");+ let _ = std::fs::remove_dir_all(&tmpdir);+}++#[test]+fn a_call_stops_marked_processes_under_any_name_and_leaves_others_running() {+ let _lock = HOST_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());+ let tmpdir = private_dir("marker");+ let mut marked = spawn_renamed_copy(&tmpdir, "renamed-host", true, &["wait", "10000"]);+ let mut unmarked = spawn_renamed_copy(&tmpdir, "ordinary-copy", false, &["wait", "10000"]);++ run(&["version"], &tmpdir);++ let status = exit_within(&mut marked, Duration::from_secs(3)).expect("marked copy survived");+ assert_eq!(status.signal(), Some(SIGKILL), "{status}");+ assert!(+ exit_within(&mut unmarked, Duration::from_secs(1)).is_none(),+ "a process without the marker was stopped"+ );+ let _ = std::fs::remove_dir_all(&tmpdir);+}++#[test]+fn a_marked_copy_running_version_exits_successfully() {+ let _lock = HOST_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());+ let tmpdir = private_dir("self");+ let mut marked = spawn_renamed_copy(&tmpdir, "agent-desktop", true, &["version"]);++ let status =+ exit_within(&mut marked, Duration::from_secs(3)).expect("marked version copy did not exit");+ assert!(status.success(), "marked version copy failed: {status}");+ assert_eq!(status.signal(), None, "marked version copy was killed");+ let _ = std::fs::remove_dir_all(&tmpdir);+}++#[test]+#[ignore = "helper process spawned by a_marked_process_that_is_not_agent_desktop_survives_a_call"]+fn marked_process_helper_sleeps() {+ std::thread::sleep(Duration::from_secs(10));+}++#[test]+fn a_marked_process_that_is_not_agent_desktop_survives_a_call() {+ let _lock = HOST_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());+ let tmpdir = private_dir("foreign");+ let mut foreign = KilledOnDrop(+ Command::new(std::env::current_exe().expect("test binary path"))+ .args([+ "--ignored",+ "--exact",+ "marked_process_helper_sleeps",+ "--nocapture",+ ])+ .env(MARKER, "1")+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .expect("helper starts"),+ );+ std::thread::sleep(Duration::from_millis(500));++ run(&["version"], &tmpdir);++ assert!(+ exit_within(&mut foreign, Duration::from_secs(1)).is_none(),+ "a marked process that is not agent-desktop was stopped"+ );+ let _ = std::fs::remove_dir_all(&tmpdir);+}diff --git a/src/tests/command_host_process.rs b/src/tests/command_host_process.rsdeleted file mode 100644index 3c10f609a..000000000--- a/src/tests/command_host_process.rs+++ /dev/null@@ -1,326 +0,0 @@-#![cfg(target_os = "macos")]--use std::io::{Read, Write};-use std::os::fd::{AsRawFd, OwnedFd};-use std::os::unix::net::UnixStream;-use std::process::{Command, Stdio};-use std::time::{Duration, Instant};--fn host_identity(directory: &std::path::Path) -> String {- use std::os::unix::fs::MetadataExt;- let executable = std::path::Path::new(env!("CARGO_BIN_EXE_agent-desktop"));- let metadata = std::fs::metadata(executable).unwrap();- serde_json::json!({- "protocol": 1,- "root": directory,- "session": null,- "executable": executable,- "revision": [metadata.dev(), metadata.ino(), metadata.size()],- "modified": [metadata.mtime(), metadata.mtime_nsec()],- "helper": std::env::var_os("AGENT_DESKTOP_MACOS_HELPER_PATH"),- })- .to_string()-}--fn future_deadline() -> u64 {- let mut time = libc::timespec {- tv_sec: 0,- tv_nsec: 0,- };- assert_eq!(- unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut time) },- 0- );- time.tv_sec as u64 * 1_000_000_000 + time.tv_nsec as u64 + 60_000_000_000-}--struct TestDir(std::path::PathBuf);--impl TestDir {- fn new() -> Self {- use std::os::unix::fs::DirBuilderExt;- static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);- let path = std::path::Path::new("/tmp").join(format!(- "ad-host-{}-{}",- std::process::id(),- NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)- ));- let _ = std::fs::remove_dir_all(&path);- std::fs::DirBuilder::new()- .mode(0o700)- .create(&path)- .unwrap();- Self(path)- }-}--impl Drop for TestDir {- fn drop(&mut self) {- let _ = std::fs::remove_dir_all(&self.0);- }-}--struct HostProcess(std::process::Child);--impl Drop for HostProcess {- fn drop(&mut self) {- let _ = self.0.kill();- let _ = self.0.wait();- }-}--#[test]-fn socket_host_survives_a_bad_client_and_serves_separate_invocations() {- let scratch = TestDir::new();- let directory = scratch.0.clone();- let socket = directory.join("h.sock");- let mut child = HostProcess(- Command::new(env!("CARGO_BIN_EXE_agent-desktop"))- .env("AGENT_DESKTOP_INTERNAL_COMMAND_HOST", "1")- .env("AGENT_DESKTOP_INTERNAL_HOST_SOCKET", &socket)- .env_remove("AGENT_DESKTOP_SESSION")- .env("AGENT_DESKTOP_HOME", &directory)- .stdin(Stdio::null())- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .spawn()- .unwrap(),- );- let deadline = Instant::now() + Duration::from_secs(10);- loop {- if UnixStream::connect(&socket).is_ok() {- break;- }- if child.0.try_wait().unwrap().is_some() {- let mut diagnostic = String::new();- child- .0- .stdout- .take()- .unwrap()- .read_to_string(&mut diagnostic)- .unwrap();- child- .0- .stderr- .take()- .unwrap()- .read_to_string(&mut diagnostic)- .unwrap();- panic!("host exited before binding: {diagnostic}");- }- assert!(Instant::now() < deadline, "host did not bind");- std::thread::sleep(Duration::from_millis(10));- }- for (request, expected) in [("[\n", false), ("[\"version\"]\n[\"version\"]\n", false)] {- let mut client = UnixStream::connect(&socket).unwrap();- client- .set_read_timeout(Some(Duration::from_secs(10)))- .unwrap();- client.write_all(request.as_bytes()).unwrap();- let mut reply = Vec::new();- client.read_to_end(&mut reply).unwrap();- let envelope: serde_json::Value = serde_json::from_slice(&reply).unwrap();- assert_eq!(envelope["ok"], expected);- assert_eq!(reply.iter().filter(|byte| **byte == b'\n').count(), 1);- }- let identity = host_identity(&directory);- let mut expired = UnixStream::connect(&socket).unwrap();- expired- .set_read_timeout(Some(Duration::from_secs(10)))- .unwrap();- writeln!(- expired,- "{}",- serde_json::json!({- "identity": identity,- "args": ["session", "start"],- "directory": directory,- "agent_id": null,- "expires_ns": 0,- })- )- .unwrap();- let mut rejected = String::new();- expired.read_to_string(&mut rejected).unwrap();- let rejected: serde_json::Value = serde_json::from_str(&rejected).unwrap();- assert_eq!(rejected["error"]["code"], "TIMEOUT");- assert_eq!(- rejected["error"]["disposition"]["delivery"],- "not_delivered"- );- assert!(- !directory.join("sessions").exists(),- "expired request must not create a session"- );- for _ in 0..2 {- let mut client = UnixStream::connect(&socket).unwrap();- client- .set_read_timeout(Some(Duration::from_secs(10)))- .unwrap();- let request = serde_json::json!({- "identity": identity,- "args": ["version"],- "directory": directory,- "agent_id": null,- "expires_ns": future_deadline(),- });- writeln!(client, "{request}").unwrap();- let mut reply = String::new();- client.read_to_string(&mut reply).unwrap();- let reply: serde_json::Value = serde_json::from_str(&reply).unwrap();- assert_eq!(reply["ok"], true, "{reply}");- }- assert!(child.0.try_wait().unwrap().is_none());-}--#[test]-fn default_cli_starts_and_reuses_its_host() {- use std::hash::{Hash, Hasher};- use std::os::unix::{fs::PermissionsExt, process::CommandExt};- let directory = std::env::temp_dir().join(format!("ad-host-client-{}", std::process::id()));- let mut hash = std::collections::hash_map::DefaultHasher::new();- host_identity(&directory).hash(&mut hash);- let socket = std::env::temp_dir().join(format!(- "agent-desktop-host-{}/{:016x}.sock",- unsafe { libc::geteuid() },- hash.finish(),- ));- let invoke = || {- let mut command = Command::new(env!("CARGO_BIN_EXE_agent-desktop"));- unsafe {- command.pre_exec(|| {- libc::umask(0);- Ok(())- });- }- command- .arg("version")- .env_remove("AGENT_DESKTOP_INTERNAL_HOST_CLIENT")- .env_remove("AGENT_DESKTOP_INTERNAL_COMMAND_HOST")- .env_remove("AGENT_DESKTOP_SESSION")- .env("AGENT_DESKTOP_HOME", &directory)- .stdout(Stdio::piped())- .stderr(Stdio::piped())- .spawn()- .unwrap()- };- let first = invoke();- let concurrent = invoke();- let deadline = Instant::now() + Duration::from_secs(10);- loop {- match std::fs::metadata(&socket) {- Ok(metadata) => {- assert_eq!(metadata.permissions().mode() & 0o077, 0);- break;- }- Err(error) if error.kind() == std::io::ErrorKind::NotFound => {- assert!(Instant::now() < deadline, "host did not bind");- std::thread::yield_now();- }- Err(error) => panic!("socket metadata failed: {error}"),- }- }- let first = first.wait_with_output().unwrap();- let concurrent = concurrent.wait_with_output().unwrap();- let stream = UnixStream::connect(&socket).unwrap();- let mut pid: libc::pid_t = 0;- let mut size = std::mem::size_of_val(&pid) as libc::socklen_t;- assert_eq!(- unsafe {- libc::getsockopt(- stream.as_raw_fd(),- libc::SOL_LOCAL,- libc::LOCAL_PEERPID,- (&mut pid as *mut libc::pid_t).cast(),- &mut size,- )- },- 0- );- drop(stream);- let second = invoke().wait_with_output().unwrap();- let reused = UnixStream::connect(&socket).unwrap();- let mut second_pid: libc::pid_t = 0;- let lookup = unsafe {- libc::getsockopt(- reused.as_raw_fd(),- libc::SOL_LOCAL,- libc::LOCAL_PEERPID,- (&mut second_pid as *mut libc::pid_t).cast(),- &mut size,- )- };- drop(reused);- assert!(pid > 0);- unsafe { libc::kill(pid, libc::SIGTERM) };- assert_eq!(lookup, 0);- assert_eq!(- second_pid, pid,- "separate invocations must reuse the native owner"- );- for result in [first, concurrent, second] {- let reply: serde_json::Value = serde_json::from_slice(&result.stdout).unwrap();- assert!(result.status.success(), "{reply}");- assert_eq!(reply["ok"], true);- assert_eq!(reply["command"], "version");- }-}--#[test]-fn unread_reply_exits_without_shutdown_flush_or_next_dispatch() {- let (sender, mut receiver) = UnixStream::pair().unwrap();- let size: libc::c_int = 4096;- assert_eq!(- unsafe {- libc::setsockopt(- sender.as_raw_fd(),- libc::SOL_SOCKET,- libc::SO_SNDBUF,- (&size as *const libc::c_int).cast(),- std::mem::size_of_val(&size) as libc::socklen_t,- )- },- 0- );- let output: OwnedFd = sender.into();- let scratch = TestDir::new();- let mut child = Command::new(env!("CARGO_BIN_EXE_agent-desktop"))- .env("AGENT_DESKTOP_INTERNAL_COMMAND_HOST", "1")- .env_remove("AGENT_DESKTOP_SESSION")- .env("AGENT_DESKTOP_HOME", &scratch.0)- .stdin(Stdio::piped())- .stdout(Stdio::from(output))- .stderr(Stdio::piped())- .spawn()- .unwrap();- let pid = child.id();- let mut stdin = child.stdin.take().unwrap();- stdin- .write_all(b"[\"skills\",\"get\",\"desktop\",\"--full\"]\n[\"version\"]\n")- .unwrap();- let mut stderr = child.stderr.take().unwrap();- let (exited, exit) = std::sync::mpsc::channel();- std::thread::spawn(move || {- let _ = exited.send(child.wait());- });- let status = match exit.recv_timeout(Duration::from_secs(20)) {- Ok(status) => status.unwrap(),- Err(_) => {- unsafe { libc::kill(pid as libc::pid_t, libc::SIGKILL) };- panic!("host failed to exit while its output remained unread");- }- };- drop(stdin);- let mut diagnostics = String::new();- stderr.read_to_string(&mut diagnostics).unwrap();- assert_eq!(status.code(), Some(1), "{diagnostics}");- assert!(diagnostics.contains("timed out"), "{diagnostics}");- let mut bytes = Vec::new();- receiver.read_to_end(&mut bytes).unwrap();- assert!(bytes.starts_with(b"{\"version\":"));- assert!(- !bytes.contains(&b'\n'),- "must not finish or dispatch the next reply"- );-}diff --git a/tests/e2e/README.md b/tests/e2e/README.mdindex 94d7828bb..82f7b8cb2 100644--- a/tests/e2e/README.md+++ b/tests/e2e/README.md@@ -86,7 +86,7 @@ helper that returns a bare `@eN`.| `scenarios/error_contract.sh` | Exit code and `error.code` envelopes an agent branches on, `batch` continue/stop/reject semantics || `scenarios/keyboard.sh` | `press` key combos observed through the fixture's own text readout, blocked-combo and unknown-modifier refusals || `scenarios/trace_performance.sh` | Trace artifacts, redaction, timings, cleanup |-| `scenarios/ref_churn.sh` | `STALE_REF` after the UI really changes, on a dedicated fixture process (`AGENT_DESKTOP_FIXTURE_REF_CHURN=1`), with and without the opt-in command host |+| `scenarios/ref_churn.sh` | `STALE_REF` after the UI really changes, on a dedicated fixture process (`AGENT_DESKTOP_FIXTURE_REF_CHURN=1`) || `scenarios/notifications.sh` | Real Notification Center lifecycle || `permission-contract.sh` | Deterministic AE5 mapping tests without mutating TCC || `electron-live.sh`, `electron_metrics*.py` | Opt-in installed Electron/Chromium app measurement |diff --git a/tests/e2e/harness.sh b/tests/e2e/harness.shindex 472a94ca2..57b8e05bc 100755--- a/tests/e2e/harness.sh+++ b/tests/e2e/harness.sh@@ -68,13 +68,6 @@ cleanup_isolated_environment() {owner="$(sed -n '1p' "$suite_root/.agent-desktop-e2e-root" 2>/dev/null)"fiif [ "$owner" = "$$" ]; then- # The staged binary owns any retained AX objects and inherited lease.- if [ -n "$prepared_binary" ]; then- local host_pid- for host_pid in $(pgrep -fx "$prepared_binary" 2>/dev/null); do- kill "$host_pid" 2>/dev/null || true- done- firemove_artifact "$suite_root" || trueelseecho "refusing to remove unowned E2E directory: $suite_root" >&2diff --git a/tests/e2e/scenarios/ref_churn.sh b/tests/e2e/scenarios/ref_churn.shindex a415608ab..f861f4515 100644--- a/tests/e2e/scenarios/ref_churn.sh+++ b/tests/e2e/scenarios/ref_churn.sh@@ -1,4 +1,4 @@-note "Default CLI retains native identity across collection changes"+note "Ref behavior across collection changes"MODE_FLAG=""AGENT_DESKTOP_FIXTURE_REF_CHURN=1 AGENT_DESKTOP_FIXTURE_NO_ACTIVATE=1 \"$fixture_app/Contents/MacOS/AgentDeskFixture" >/dev/null 2>&1 &@@ -9,49 +9,15 @@ require_target_by_id alpha textfield shared-titlerequire_target_by_id stable textfield stable-editoract_target "$filter" click >/dev/null 2>&1"$bin" wait --text "Restore rows" --app "$app" --timeout 5000 >/dev/null 2>&1-output="$("$bin" set-value "$(target_ref "$alpha")" poisoned 2>/dev/null)"-ok="$(json_field "$output" ok)"-code="$(json_field "$output" error.code)"-delivery="$(json_field "$output" error.disposition.delivery)"-assert "removed row is refused without delivery" \- "$([ "$ok" = "False" ] && [ "$code" = "STALE_REF" ] && [ "$delivery" = "not_delivered" ] && echo 1 || echo 0)" \- "ok=$ok code=$code delivery=$delivery"-batch_payload="$(python3 - "$(target_ref "$alpha")" <<'BATCH_PY'-import json, sys-print(json.dumps([{"command": "set-value", "args": {"ref_id": sys.argv[1], "value": "poisoned"}}]))-BATCH_PY-)"-batch_output="$("$bin" batch "$batch_payload" 2>/dev/null)"-assert "batch also refuses the removed row without delivery" \- "$([ "$(json_field "$batch_output" data.results.0.error.code)" = "STALE_REF" ] && [ "$(json_field "$batch_output" data.results.0.error.disposition.delivery)" = "not_delivered" ] && echo 1 || echo 0)" \- "code=$(json_field "$batch_output" data.results.0.error.code)"-beta_seen="$("$bin" wait --text "Beta stored: Beta" --app "$app" --timeout 3000 2>/dev/null)"-assert "surviving row kept its value" \- "$([ "$(json_field "$beta_seen" data.found)" = "True" ] && echo 1 || echo 0)" \- "found=$(json_field "$beta_seen" data.found)"+duplicate_identifier_note="known limitation: a removed row's ref can resolve to the surviving row that shares shared-title"+skipmsg "removed row is refused without delivery: $duplicate_identifier_note"+skipmsg "batch also refuses the removed row without delivery: $duplicate_identifier_note"+skipmsg "surviving row kept its value: $duplicate_identifier_note"stable_write="$("$bin" set-value "$(target_ref "$stable")" stable-ok 2>/dev/null)"stable_seen="$(wait_target "$stable" value 3000 --value stable-ok 2>/dev/null)"assert "unchanged editor remains editable through its ref" \"$([ "$(json_field "$stable_write" ok)" = "True" ] && [ "$(json_field "$stable_seen" data.found)" = "True" ] && echo 1 || echo 0)" \"ok=$(json_field "$stable_write" ok) found=$(json_field "$stable_seen" data.found)"-pgrep -fx "$raw_bin" | while read -r host_pid; do- kill "$host_pid" 2>/dev/null || true-done-for _ in $(seq 1 100); do- [ -z "$(pgrep -fx "$raw_bin" 2>/dev/null)" ] && break- sleep 0.02-done-assert "task-owned command hosts stopped" \- "$([ -z "$(pgrep -fx "$raw_bin" 2>/dev/null)" ] && echo 1 || echo 0)" ""-restarted_read="$("$bin" get "$(target_ref "$stable")" 2>/dev/null)"-assert "host restart invalidates retained refs" \- "$([ "$(json_field "$restarted_read" error.code)" = "STALE_REF" ] && echo 1 || echo 0)" \- "code=$(json_field "$restarted_read" error.code)"-require_target_by_id fresh_stable textfield stable-editor-fresh_read="$("$bin" get "$(target_ref "$fresh_stable")" 2>/dev/null)"-assert "fresh snapshot after host restart restores access" \- "$([ "$(json_field "$fresh_read" ok)" = "True" ] && echo 1 || echo 0)" \- "ok=$(json_field "$fresh_read" ok)"kill "$churn_pid" 2>/dev/nullwait "$churn_pid" 2>/dev/nullfixture_owned=0diff --git a/tests/e2e/test_harness_contract.py b/tests/e2e/test_harness_contract.pyindex 16a5f463c..c0475b945 100644--- a/tests/e2e/test_harness_contract.py+++ b/tests/e2e/test_harness_contract.py@@ -362,7 +362,6 @@ class KeyboardAndRefChurnLegTests(unittest.TestCase):def test_ref_churn_reads_the_fixture_readouts_not_the_command_result(self):source = REF_CHURN.read_text()- self.assertIn('--text "Beta stored: Beta"', source)self.assertIn('wait_target "$stable" value 3000 --value stable-ok', source)self.assertIn("data.found", source)@@ -396,7 +395,6 @@ class KeyboardAndRefChurnLegTests(unittest.TestCase):for path in (KEYBOARD, REF_CHURN, RELIABILITY):used = literal_error_codes(path.read_text())self.assertEqual(used - known, set(), path.name)- self.assertIn("STALE_REF", literal_error_codes(REF_CHURN.read_text()))self.assertIn("STALE_REF", literal_error_codes(RELIABILITY.read_text()))self.assertEqual(literal_error_codes(KEYBOARD.read_text()), {"POLICY_DENIED", "INVALID_ARGS"}diff --git a/tests/npm/postinstall.test.js b/tests/npm/postinstall.test.jsindex 5365cdb7d..7a7d72d30 100644--- a/tests/npm/postinstall.test.js+++ b/tests/npm/postinstall.test.js@@ -519,9 +519,7 @@ test('a failed relink that leaves an older native entry fails the install', {}});-test('postinstall links the bin entry of an installed package to the native binary', {- skip: process.platform === 'win32',-}, async () => {+function installWithNativeScript(script) {const root = join(temporaryDirectory(), 'node_modules', 'agent-desktop');for (const part of ['package.json', 'bin/agent-desktop', 'lib/platform.js', 'scripts/postinstall.js']) {mkdirSync(join(root, part, '..'), { recursive: true });@@ -529,17 +527,35 @@ test('postinstall links the bin entry of an installed package to the native bina}const source = join(temporaryDirectory(), 'release');mkdirSync(source);- writeFileSync(join(source, 'agent-desktop'), 'native', { mode: 0o755 });+ const ran = join(source, 'ran');+ writeFileSync(join(source, 'agent-desktop'), `#!/bin/sh\necho "$@" >> '${ran}'\n${script}`, { mode: 0o755 });writeFileSync(join(source, 'agent-desktop-macos-helper'), 'helper', { mode: 0o755 });process.env.AGENT_DESKTOP_BINARY_PATH = join(source, 'agent-desktop');- try {- const { code, stderr } = await runScriptWithOsStub(join(root, 'scripts', 'postinstall.js'), 'darwin', 'arm64');- assert.equal(code, 0, stderr);- assert.match(stderr, /Native binary linked: each call runs without the Node launcher/);- } finally {- delete process.env.AGENT_DESKTOP_BINARY_PATH;- }+ return runScriptWithOsStub(join(root, 'scripts', 'postinstall.js'), 'darwin', 'arm64')+ .then((result) => ({ ...result, root, ran }))+ .finally(() => { delete process.env.AGENT_DESKTOP_BINARY_PATH; });+}++test('postinstall links the bin entry of an installed package to the native binary, then runs it once', {+ skip: process.platform === 'win32',+}, async () => {+ const { code, stderr, root, ran } = await installWithNativeScript('');+ assert.equal(code, 0, stderr);+ assert.match(stderr, /Native binary linked: each call runs without the Node launcher/);+ assert.equal(readFileSync(ran, 'utf8'), 'version\n');+ assert.doesNotMatch(stderr, /Could not stop command hosts/);const entry = lstatSync(join(root, 'bin', 'agent-desktop'));assert.equal(entry.ino, lstatSync(join(root, 'bin', 'agent-desktop-darwin-arm64')).ino);assert.equal(readFileSync(join(root, 'bin', 'agent-desktop-macos-helper'), 'utf8'), 'helper');});++test('a failed leftover host cleanup warns without failing the install or the link', {+ skip: process.platform === 'win32',+}, async () => {+ const { code, stderr, root } = await installWithNativeScript('exit 1\n');+ assert.equal(code, 0, stderr);+ assert.match(stderr, /Could not stop command hosts left by an earlier version/);+ assert.match(stderr, /Run `agent-desktop version` once to stop them/);+ const entry = lstatSync(join(root, 'bin', 'agent-desktop'));+ assert.equal(entry.ino, lstatSync(join(root, 'bin', 'agent-desktop-darwin-arm64')).ino);+});