Skip to content

Computer use CLI for AI agents

fix: preserve macos ref identity and native action reliability

Lahfir3c466098c53b
diff --git a/README.md b/README.md
index d25d1dc48..369bff01c 100644
--- a/README.md
+++ b/README.md
@@ -17,6 +17,8 @@ agent-desktop is a command-line tool and C library that lets an AI agent read an
It ships 60 command names, 56 operational commands. The other four (`key-down`, `key-up`, `mouse-down`, `mouse-up`) refuse to run until a daemon can release a held key or button.
+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.
+
## Installation
```bash
diff --git a/crates/core/src/app_lookup.rs b/crates/core/src/app_lookup.rs
index 658eb2a99..954589511 100644
--- a/crates/core/src/app_lookup.rs
+++ b/crates/core/src/app_lookup.rs
@@ -27,6 +27,7 @@ pub(crate) fn resolve_app(
ErrorCode::AppNotFound,
"No focused application was found when --app was omitted",
)
+ .with_disposition(crate::DeliverySemantics::not_delivered())
.into());
}
[window] => window,
@@ -78,6 +79,7 @@ fn select_unique_app(mut candidates: Vec<AppInfo>, label: &str) -> Result<AppInf
ErrorCode::AppNotFound,
format!("Application '{label}' was not found with exact process identity"),
)
+ .with_disposition(crate::DeliverySemantics::not_delivered())
.with_suggestion(
"Application name as reported by list-apps, with or without .exe suffix on Windows",
)
diff --git a/crates/core/src/app_lookup_tests.rs b/crates/core/src/app_lookup_tests.rs
index 77aab4b08..f43f5c085 100644
--- a/crates/core/src/app_lookup_tests.rs
+++ b/crates/core/src/app_lookup_tests.rs
@@ -292,4 +292,8 @@ fn app_not_found_carries_a_suggestion_naming_the_accepted_forms() {
.suggestion()
.is_some_and(|suggestion| !suggestion.is_empty())
);
+ let AppError::Adapter(error) = error else {
+ panic!("expected adapter error")
+ };
+ assert_eq!(error.disposition, crate::DeliverySemantics::not_delivered());
}
diff --git a/crates/macos/src/actions/scroll_into_view.rs b/crates/macos/src/actions/scroll_into_view.rs
index 34ad88709..9c6a07790 100644
--- a/crates/macos/src/actions/scroll_into_view.rs
+++ b/crates/macos/src/actions/scroll_into_view.rs
@@ -85,7 +85,13 @@ mod imp {
let instant = crate::tree::locator_deadline::from_operation(deadline)?;
let bounds = crate::tree::element_bounds::read_bounds_with_deadline(element, instant)?
.ok_or_else(|| AdapterError::new(ErrorCode::ActionFailed, "Target has no bounds"))?;
- let viewport = match crate::actions::scroll::find_scroll_area(element, deadline)? {
+ let parent = crate::actions::scroll_read::element(element, "AXParent", deadline)?;
+ let viewport = match parent
+ .as_ref()
+ .map(|parent| crate::actions::scroll::find_scroll_area(parent, deadline))
+ .transpose()?
+ .flatten()
+ {
Some(viewport) => viewport,
None => require_window(crate::tree::surface_read::element(
element, "AXWindow", instant,
diff --git a/crates/macos/src/system/appkit_bridge.m b/crates/macos/src/system/appkit_bridge.m
index 356fd07bf..9d291d5d4 100644
--- a/crates/macos/src/system/appkit_bridge.m
+++ b/crates/macos/src/system/appkit_bridge.m
@@ -121,6 +121,8 @@ AgentDesktopBytesResult agent_desktop_copy_workspace_snapshot_json(void) {
@try {
@autoreleasepool {
NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
+ // A command host must consume AppKit launch/exit notifications between requests.
+ CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.001, false);
NSArray<NSRunningApplication *> *running = workspace.runningApplications;
if (running == nil || running.count > 8192) {
result.status = 1;
@@ -154,7 +156,6 @@ AgentDesktopBytesResult agent_desktop_copy_workspace_snapshot_json(void) {
}
NSMutableArray<NSDictionary *> *records =
[NSMutableArray arrayWithCapacity:running.count];
- NSMutableSet<NSNumber *> *seen = [NSMutableSet setWithCapacity:running.count];
for (NSUInteger index = 0; index < running.count; index++) {
NSRunningApplication *app = running[index];
if (![app isKindOfClass:[NSRunningApplication class]]) {
@@ -191,10 +192,6 @@ AgentDesktopBytesResult agent_desktop_copy_workspace_snapshot_json(void) {
continue;
}
NSNumber *pidNumber = @(pid);
- if ([seen containsObject:pidNumber]) {
- [skipped addObject:@{@"pid": @(pid), @"field": @"duplicate_pid", @"index": @(index)}];
- continue;
- }
NSDate *launchDate = app.launchDate;
id launchTime = [NSNull null];
if (launchDate != nil) {
@@ -219,7 +216,6 @@ AgentDesktopBytesResult agent_desktop_copy_workspace_snapshot_json(void) {
}
record[@"bundle_id"] = bundle;
}
- [seen addObject:pidNumber];
[records addObject:record];
}
NSMutableDictionary *snapshot = [@{
diff --git a/crates/macos/src/system/cursor_overlay/spawn.rs b/crates/macos/src/system/cursor_overlay/spawn.rs
index 68342b4b4..d962b6914 100644
--- a/crates/macos/src/system/cursor_overlay/spawn.rs
+++ b/crates/macos/src/system/cursor_overlay/spawn.rs
@@ -144,6 +144,9 @@ fn spawn(
drop(stdin);
while Instant::now() < deadline {
if UnixStream::connect(socket).is_ok() {
+ thread::spawn(move || {
+ let _ = child.wait();
+ });
return Ok(());
}
thread::sleep(Duration::from_millis(10));
diff --git a/crates/macos/src/system/window_inventory.rs b/crates/macos/src/system/window_inventory.rs
index ac2496552..7c0151072 100644
--- a/crates/macos/src/system/window_inventory.rs
+++ b/crates/macos/src/system/window_inventory.rs
@@ -120,6 +120,7 @@ fn require_running_app(
agent_desktop_core::ErrorCode::AppNotFound,
format!("No running application matches '{app_filter}'"),
)
+ .with_disposition(agent_desktop_core::DeliverySemantics::not_delivered())
.with_suggestion("Run 'list-apps' to see running applications, or launch the app first."))
}
diff --git a/crates/macos/src/system/window_inventory_tests.rs b/crates/macos/src/system/window_inventory_tests.rs
index 56c0b009e..96d1b0d80 100644
--- a/crates/macos/src/system/window_inventory_tests.rs
+++ b/crates/macos/src/system/window_inventory_tests.rs
@@ -241,6 +241,10 @@ fn explicit_app_filter_distinguishes_not_running_from_no_windows() {
let empty = rustc_hash::FxHashSet::default();
let error = require_running_app(&empty, "WhatsApp").unwrap_err();
assert_eq!(error.code, agent_desktop_core::ErrorCode::AppNotFound);
+ assert_eq!(
+ error.disposition,
+ agent_desktop_core::DeliverySemantics::not_delivered()
+ );
let running = rustc_hash::FxHashSet::from_iter([42]);
assert!(require_running_app(&running, "WhatsApp").is_ok());
diff --git a/crates/macos/src/system/workspace_apps_records.rs b/crates/macos/src/system/workspace_apps_records.rs
index d479ea26b..ca575ae0b 100644
--- a/crates/macos/src/system/workspace_apps_records.rs
+++ b/crates/macos/src/system/workspace_apps_records.rs
@@ -17,20 +17,23 @@ pub(super) fn bridged_snapshot(bytes: &[u8]) -> Result<BridgedWorkspaceSnapshot,
.get_mut("applications")
.and_then(Value::as_array_mut)
.ok_or_else(|| with_skipped(inventory_error("AppKit omitted applications"), &skipped))?;
- let mut seen = rustc_hash::FxHashSet::default();
+ let mut seen: rustc_hash::FxHashMap<Option<i64>, Value> = rustc_hash::FxHashMap::default();
applications.retain(|app| {
- let field = invalid_field(app).or_else(|| {
- if seen.insert(app["pid"].as_i64()) {
- None
- } else {
+ let field = invalid_field(app).or_else(|| match seen.get(&app["pid"].as_i64()) {
+ Some(previous)
+ if ["launch_time", "bundle_id", "activation_policy"]
+ .iter()
+ .any(|field| previous[*field] != app[*field]) =>
+ {
Some("duplicate_pid")
}
+ _ => None,
});
if let Some(field) = field {
skipped.push(json!({"pid": app["pid"].as_i64().unwrap_or(0), "field": field}));
false
} else {
- true
+ seen.insert(app["pid"].as_i64(), app.clone()).is_none()
}
});
if let (Some(pid), Some(time)) = (
diff --git a/crates/macos/src/system/workspace_apps_skip_tests.rs b/crates/macos/src/system/workspace_apps_skip_tests.rs
index f5a2c5638..27844f406 100644
--- a/crates/macos/src/system/workspace_apps_skip_tests.rs
+++ b/crates/macos/src/system/workspace_apps_skip_tests.rs
@@ -29,7 +29,7 @@ fn malformed_records_are_reported_without_blocking_either_inventory() {
.unwrap();
let bridged = bridged_snapshot(&bytes).unwrap();
assert_eq!(bridged.skipped[0]["field"], field);
- assert_eq!(bridged.skipped[1]["field"], "duplicate_pid");
+ assert_eq!(bridged.skipped.len(), 1);
let owners = window_owner_snapshot_from_json(&bytes, deadline());
if key == "pid" {
assert!(owners.is_err());
@@ -159,3 +159,55 @@ fn skipped_records_preserve_matching_apps_and_retry_missing_names() {
assert_eq!(error.code, ErrorCode::AppUnresponsive);
assert_eq!(error.details.unwrap()["skipped"][0]["pid"], 11);
}
+
+#[test]
+fn workspace_identity_aliases_do_not_make_missing_apps_retryable() {
+ let app =
+ json!({"name":"Finder", "pid":10, "launch_time":100.0, "activation_policy":"regular"});
+ let mut alias = app.clone();
+ alias["name"] = json!("Finder alias");
+ let bytes = serde_json::to_vec(&json!({
+ "applications":[app, alias], "frontmost_pid":10, "frontmost_launch_time":100.0,
+ }))
+ .unwrap();
+ let inventory = apps_inventory_from_json_with(
+ &bytes,
+ deadline(),
+ |_| true,
+ true,
+ |_| Ok(Some("instance-10".into())),
+ )
+ .unwrap();
+ assert_eq!(inventory.apps.len(), 1);
+ require_complete(&inventory.skipped).unwrap();
+ let owners = window_owner_snapshot_from_json(&bytes, deadline()).unwrap();
+ owners.require_match("Missing").unwrap();
+ assert_eq!(owners.frontmost().unwrap().pid, 10);
+}
+
+#[test]
+fn conflicting_workspace_records_remain_incomplete() {
+ let app =
+ json!({"name":"Finder", "pid":10, "launch_time":100.0, "activation_policy":"regular"});
+ for (field, value) in [
+ ("launch_time", json!(101.0)),
+ ("activation_policy", json!("accessory")),
+ ("bundle_id", json!("other.bundle")),
+ ] {
+ let mut conflicting = app.clone();
+ conflicting[field] = value;
+ let bytes = serde_json::to_vec(&json!({
+ "applications":[app, conflicting], "frontmost_pid":0, "frontmost_launch_time":null,
+ }))
+ .unwrap();
+ let inventory = apps_inventory_from_json_with(
+ &bytes,
+ deadline(),
+ |_| true,
+ true,
+ |_| Ok(Some("instance-10".into())),
+ )
+ .unwrap();
+ assert!(require_complete(&inventory.skipped).is_err(), "{field}");
+ }
+}
diff --git a/docs/phases.md b/docs/phases.md
index 80415819a..1909db118 100644
--- a/docs/phases.md
+++ b/docs/phases.md
@@ -2596,6 +2596,19 @@ Phase 5 transforms agent-desktop from functional to enterprise-grade. Persistent
The daemon is a long-running process that maintains state between CLI/MCP invocations, dramatically reducing startup latency.
+macOS already uses a private, automatically started host per snapshot namespace
+for retained native ref identity, with a 15-minute idle lifetime. Session commands
+remain in the caller and batch items route to their selected namespace. Fixture
+coverage includes stale refs after collection changes and host restart, plus batch
+namespace/event-wait compatibility (`tests/e2e/scenarios/ref_churn.sh`,
+`src/batch/execution_tests.rs`, `src/tests/command_host_process.rs`). This does not
+complete Phase 5: immediate object release on session end, cancellation,
+diagnostics/environment parity, primary-phase queue accounting, and the real
+Xcode/SF Symbols qualification in
+`docs/plans/2026-09-20-retained-native-ref-identity.md` remain to be qualified.
+The current host retains objects until idle expiry even after session end.
+
+
**Auto-start:**
- CLI detects if daemon is running by checking for socket file (`~/.agent-desktop/daemon.sock` on Unix, named pipe on Windows)
- If not running, spawns daemon as background process
@@ -2644,7 +2657,7 @@ When daemon is running:
5. Returns JSON response to CLI
6. CLI prints response to stdout
-When daemon is not running, CLI falls back to direct execution (same as Phases 1-4). Daemon is purely an optimization, never a requirement.
+The future general daemon is optional. macOS retained-ref commands already require their namespace host and fail closed when it is unavailable; they cannot fall back to heuristic ref matching.
### Safety Trio: `--dry-run` / `--confirm` / Audit Log (P5-O5)
diff --git a/docs/plans/2026-09-20-retained-native-ref-identity.md b/docs/plans/2026-09-20-retained-native-ref-identity.md
index db2de925a..750824c11 100644
--- a/docs/plans/2026-09-20-retained-native-ref-identity.md
+++ b/docs/plans/2026-09-20-retained-native-ref-identity.md
@@ -1,6 +1,6 @@
# Retain native identity across commands
-Status: core and native retention implemented; persistent CLI host pending; unqualified.
+Status: macOS default CLI host implemented and fixture-qualified; broader real-app and lifecycle qualification remains incomplete.
## Decision
@@ -370,12 +370,20 @@ no session artifact. Concurrent startup and same-PID reuse still pass. All-targe
Clippy, formatting and diff checks pass. Logs: /tmp/ad-native-eval/host-budget-tests.log,
host-budget-process.log, host-budget-clippy.log and final-workspace.log.
-The client is still experimental behind AGENT_DESKTOP_INTERNAL_HOST_CLIENT=1.
-Do not enable default routing based on this checkpoint. Remaining work includes
-restart/stale-ref tests through the client, real Xcode acceptance, batch namespace
-handling, session-end release, cancellation and diagnostics/environment parity.
-Post-action wait shares the total transport budget; independent primary-phase
-queue accounting needs review. The final host integration has not received a new
-performance baseline or full real-app qualification. Prior performance measurements
-do not qualify it. No commit, push or release was made. Provisional rating remains
-8/10; the requested 10/10 objective was not achieved.
+The macOS CLI now starts and reuses the private namespace host by default.
+Session management remains in the caller; batch items route to their selected
+namespace hosts while preserving event baselines and the remaining batch budget.
+The native fixture suite passes 119 checks with one unavailable native TCC-denial
+case skipped; the deterministic denial contract runs. Eight focused checks cover
+removed-row refusal, batch refusal, unchanged-row access, host restart invalidation,
+fresh-snapshot recovery and terminal unknown-app errors. See
+`tests/e2e/scenarios/ref_churn.sh` and `src/tests/command_host_process.rs`.
+
+Alternating fixture performance against 02afee67 measured warm snapshot medians
+of 294ms versus 442ms and get medians of 47ms versus 163ms. Seven cold-start samples
+after warmup measured 359ms versus 358ms. These fixture results do not qualify the
+broader Xcode/SF Symbols acceptance contract. Session-end immediate object release,
+cancellation, diagnostics/environment parity and independent primary-phase queue
+accounting remain unqualified. Retained objects currently expire with their host's
+15-minute idle lifetime. The original 10/10 qualification objective is incomplete;
+Phase 5 owns the remaining lifecycle qualification in `docs/phases.md`.
diff --git a/src/batch/execution.rs b/src/batch/execution.rs
index cf9a3358a..4f742aec5 100644
--- a/src/batch/execution.rs
+++ b/src/batch/execution.rs
@@ -9,7 +9,7 @@ use crate::{cli::Commands, cli_args::batch::BatchArgs};
use super::{
bounded_json::serialized_size,
preparation::{MAX_BATCH_ENTRIES, MAX_BATCH_JSON_BYTES, PreparedCommand, prepare},
- result_entry::{MAX_BATCH_OUTPUT_BYTES, bounded_entry, not_started_entry},
+ result_entry::{MAX_BATCH_OUTPUT_BYTES, not_started_entry},
};
pub(super) fn execute(
@@ -26,7 +26,8 @@ pub(super) fn execute(
let mut results = Vec::with_capacity(total);
let mut results_bytes = 0;
let mut completed = 0;
- let mut pending_baseline: Option<Result<SignalBaseline, AdapterError>> = None;
+ let mut pending_baseline: Option<Result<SignalBaseline, AdapterError>> =
+ context.event_baseline().cloned();
let mut stopped = None;
for index in 0..total {
@@ -99,9 +100,47 @@ pub(super) fn execute(
.with_inherited_deadline(deadline)
.with_event_baseline(current_baseline);
let command = std::mem::replace(&mut commands[index].command, Commands::Version);
- let result = crate::dispatch::dispatch(command, adapter, permission_report, &item_context);
- let failed = result.is_err();
- let (entry, oversized) = bounded_entry(index, &commands[index].name, result, results_bytes);
+ #[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 failed = entry["ok"] != true;
+ let (entry, oversized) = super::result_entry::bounded_completed_entry(
+ index,
+ &commands[index].name,
+ entry,
+ results_bytes,
+ );
completed += 1;
push_small_entry(&mut results, &mut results_bytes, entry);
diff --git a/src/batch/execution_tests.rs b/src/batch/execution_tests.rs
index f592042d3..fc205056c 100644
--- a/src/batch/execution_tests.rs
+++ b/src/batch/execution_tests.rs
@@ -1,3 +1,4 @@
+use crate::batch::result_entry::bounded_entry;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};
diff --git a/src/batch/preparation.rs b/src/batch/preparation.rs
index d7af53db7..71855d563 100644
--- a/src/batch/preparation.rs
+++ b/src/batch/preparation.rs
@@ -13,6 +13,8 @@ pub(super) struct PreparedCommand {
pub name: String,
pub command: Commands,
pub context: CommandContext,
+ #[cfg(target_os = "macos")]
+ pub source: Value,
}
pub(super) fn prepare(
@@ -41,7 +43,7 @@ pub(super) fn prepare(
.collect::<Result<Vec<_>, _>>()?;
parsed
.into_iter()
- .map(|(index, name, command, session)| {
+ .map(|(index, name, command, session, _source)| {
let item_context = context
.for_batch_item(session)
.map_err(|error| located_error(index, &name, error))?;
@@ -51,6 +53,8 @@ pub(super) fn prepare(
name,
command,
context: item_context,
+ #[cfg(target_os = "macos")]
+ source: _source,
})
})
.collect()
@@ -60,7 +64,8 @@ fn parse_one(
index: usize,
item: BatchCommand,
permission_report: &PermissionReport,
-) -> Result<(usize, String, Commands, Option<String>), AppError> {
+) -> Result<(usize, String, Commands, Option<String>, Value), AppError> {
+ let source = json!({"command": item.command, "args": item.args});
let name = item.command.clone();
let session = item.session.clone();
if let Some(session) = session.as_deref() {
@@ -70,7 +75,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))
+ Ok((index, name, command, session, source))
}
fn located_error(index: usize, command: &str, error: AppError) -> AppError {
diff --git a/src/batch/result_entry.rs b/src/batch/result_entry.rs
index 2ebbeb554..5b57df160 100644
--- a/src/batch/result_entry.rs
+++ b/src/batch/result_entry.rs
@@ -9,6 +9,7 @@ use super::bounded_json::serialized_fits;
pub(super) const MAX_BATCH_OUTPUT_BYTES: usize = 4 * 1024 * 1024;
pub(super) const OUTPUT_METADATA_RESERVE: usize = 8 * 1024;
+#[cfg(test)]
pub(super) fn bounded_entry(
index: usize,
command: &str,
@@ -16,6 +17,15 @@ pub(super) fn bounded_entry(
used: usize,
) -> (Value, bool) {
let entry = completed_entry(index, command, result);
+ bounded_completed_entry(index, command, entry, used)
+}
+
+pub(super) fn bounded_completed_entry(
+ index: usize,
+ command: &str,
+ entry: Value,
+ used: usize,
+) -> (Value, bool) {
let available = MAX_BATCH_OUTPUT_BYTES
.saturating_sub(OUTPUT_METADATA_RESERVE)
.saturating_sub(used);
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 5e85d5856..7e26dfb03 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -260,10 +260,10 @@ impl Commands {
}
#[cfg(target_os = "macos")]
- /// The permission guide offers the caller's own app to drag into the
- /// Privacy list, so it cannot run inside a detached command host.
+ /// Permission guidance needs the caller; session management crosses host namespaces.
pub(crate) fn needs_caller_process(&self) -> bool {
- matches!(self, Self::Permissions(args) if args.guide)
+ matches!(self, Self::Session(_) | Self::Batch(_))
+ || matches!(self, Self::Permissions(args) if args.guide)
}
pub(crate) fn is_mutating(&self) -> bool {
diff --git a/src/cli/wait_for_cli_tests.rs b/src/cli/wait_for_cli_tests.rs
index ebb04ff4a..71a28e3b0 100644
--- a/src/cli/wait_for_cli_tests.rs
+++ b/src/cli/wait_for_cli_tests.rs
@@ -141,8 +141,11 @@ fn typed_metadata_couples_name_and_wait_support_to_each_variant() {
#[cfg(target_os = "macos")]
#[test]
-fn only_the_permission_guide_stays_in_the_caller_process() {
+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());
diff --git a/src/command_host.rs b/src/command_host.rs
index 1e4d192c9..9f489ffd8 100644
--- a/src/command_host.rs
+++ b/src/command_host.rs
@@ -14,6 +14,10 @@ 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;
diff --git a/src/command_host_batch.rs b/src/command_host_batch.rs
new file mode 100644
index 000000000..7cfe02882
--- /dev/null
+++ b/src/command_host_batch.rs
@@ -0,0 +1,64 @@
+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_budget.rs b/src/command_host_budget.rs
index b99feb38c..c88ac5f75 100644
--- a/src/command_host_budget.rs
+++ b/src/command_host_budget.rs
@@ -73,6 +73,11 @@ fn budget_ms(cli: &crate::Cli, command: &crate::Commands) -> Result<u64, AppErro
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)
@@ -99,6 +104,10 @@ mod tests {
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,
diff --git a/src/command_host_client.rs b/src/command_host_client.rs
index 1c4df0b7b..1f585120e 100644
--- a/src/command_host_client.rs
+++ b/src/command_host_client.rs
@@ -9,6 +9,22 @@ 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()?;
@@ -21,13 +37,8 @@ pub(super) fn forward(
let request = super::request::HostRequest {
expires_ns,
identity,
- 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<_, _>>()?,
+ args,
+ baseline,
directory: std::env::current_dir()?,
agent_id: cli
.identity
@@ -126,7 +137,6 @@ fn connect_or_start(
command
.env("AGENT_DESKTOP_INTERNAL_COMMAND_HOST", "1")
.env("AGENT_DESKTOP_INTERNAL_HOST_SOCKET", path)
- .env_remove("AGENT_DESKTOP_INTERNAL_HOST_CLIENT")
.env_remove("AGENT_DESKTOP_AGENT_ID")
.env_remove("AGENT_DESKTOP_SESSION")
.process_group(0)
diff --git a/src/command_host_request.rs b/src/command_host_request.rs
index 72100cf79..ac96bb455 100644
--- a/src/command_host_request.rs
+++ b/src/command_host_request.rs
@@ -10,13 +10,15 @@ pub(super) struct HostRequest {
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)) => crate::response(
+ Ok((cli, command, deadline, baseline)) => crate::response(
command.name(),
- crate::execute_with_deadline(cli, command, Some(deadline)),
+ crate::execute_with_deadline(cli, command, Some(deadline), baseline),
),
Err(error) => crate::response("unknown", Err(crate::pre_dispatch_error(error))),
}
@@ -26,7 +28,15 @@ fn prepare(
bytes: &[u8],
identity: &str,
session: Option<&str>,
-) -> Result<(crate::Cli, crate::Commands, agent_desktop_core::Deadline), AppError> {
+) -> 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 {
@@ -46,7 +56,7 @@ fn prepare(
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))
+ Ok((cli, command, deadline, request.baseline))
}
#[cfg(test)]
@@ -66,6 +76,7 @@ mod tests {
directory: PathBuf::from("/"),
agent_id: None,
expires_ns: u64::MAX,
+ baseline: None,
})
.unwrap();
let response = execute(&bytes, "owner", Some("mine"));
diff --git a/src/main.rs b/src/main.rs
index 91ffe6a07..4c371e29c 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -120,9 +120,7 @@ fn run() -> ExitCode {
let cmd_name = cmd.name();
#[cfg(target_os = "macos")]
- if std::env::var("AGENT_DESKTOP_INTERNAL_HOST_CLIENT").as_deref() == Ok("1")
- && !cmd.needs_caller_process()
- {
+ if !cmd.needs_caller_process() {
return match command_host::forward(&cli, &cmd) {
Ok(response) => match emit_response(&response) {
Err(error) => report_output_failure(error),
@@ -136,13 +134,14 @@ fn run() -> ExitCode {
}
fn execute(cli: Cli, cmd: Commands) -> Result<serde_json::Value, AppError> {
- execute_with_deadline(cli, cmd, None)
+ execute_with_deadline(cli, cmd, None, None)
}
fn execute_with_deadline(
cli: Cli,
cmd: Commands,
deadline: Option<agent_desktop_core::Deadline>,
+ baseline: Option<agent_desktop_core::SignalBaseline>,
) -> Result<serde_json::Value, AppError> {
if let Some(deadline) = deadline.filter(|deadline| deadline.is_expired()) {
return Err(pre_dispatch_error(deadline.timeout_error().into()));
@@ -193,6 +192,7 @@ fn execute_with_deadline(
if let Some(deadline) = deadline {
context = context.with_inherited_deadline(deadline);
}
+ context = context.with_event_baseline(baseline.map(Ok));
if let Some(wait) = wait_selector.as_ref() {
validate_wait_for_command(&cmd, wait)?;
}
diff --git a/src/tests/command_host_process.rs b/src/tests/command_host_process.rs
index 02896aa29..59ecb62e5 100644
--- a/src/tests/command_host_process.rs
+++ b/src/tests/command_host_process.rs
@@ -160,7 +160,7 @@ fn socket_host_survives_a_bad_client_and_serves_separate_invocations() {
}
#[test]
-fn experimental_cli_starts_and_reuses_its_host() {
+fn default_cli_starts_and_reuses_its_host() {
use std::hash::{Hash, Hasher};
let directory = std::env::temp_dir().join(format!("ad-host-client-{}", std::process::id()));
let mut hash = std::collections::hash_map::DefaultHasher::new();
@@ -173,7 +173,7 @@ fn experimental_cli_starts_and_reuses_its_host() {
let invoke = || {
Command::new(env!("CARGO_BIN_EXE_agent-desktop"))
.arg("version")
- .env("AGENT_DESKTOP_INTERNAL_HOST_CLIENT", "1")
+ .env_remove("AGENT_DESKTOP_INTERNAL_HOST_CLIENT")
.env_remove("AGENT_DESKTOP_INTERNAL_COMMAND_HOST")
.env_remove("AGENT_DESKTOP_SESSION")
.env("AGENT_DESKTOP_HOME", &directory)
diff --git a/tests/e2e/harness.sh b/tests/e2e/harness.sh
index b41808d48..79fba39a8 100755
--- a/tests/e2e/harness.sh
+++ b/tests/e2e/harness.sh
@@ -43,9 +43,11 @@ release_exclusive_lock() {
setup_isolated_environment() {
local label="$1"
- suite_root="$(mktemp -d "$host_tmp/agent-desktop-${label}.XXXXXX")" || return 1
+ suite_root="$(mktemp -d "/tmp/ad-${label}.XXXXXX")" || return 1
+ suite_root="$(cd "$suite_root" && pwd -P)" || return 1
printf '%s\n' "$$" > "$suite_root/.agent-desktop-e2e-root"
mkdir -p "$suite_root/home" "$suite_root/tmp" "$suite_root/bin" "$suite_root/fixture"
+ chmod 700 "$suite_root/tmp"
export HOME="$suite_root/home"
export TMPDIR="$suite_root/tmp"
export XDG_CACHE_HOME="$suite_root/home/.cache"
@@ -66,6 +68,13 @@ cleanup_isolated_environment() {
owner="$(sed -n '1p' "$suite_root/.agent-desktop-e2e-root" 2>/dev/null)"
fi
if [ "$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
+ fi
trash_recoverably "$suite_root" || true
else
echo "refusing to remove unowned E2E directory: $suite_root" >&2
diff --git a/tests/e2e/run.sh b/tests/e2e/run.sh
index f15442f70..13d2a2c42 100755
--- a/tests/e2e/run.sh
+++ b/tests/e2e/run.sh
@@ -155,4 +155,7 @@ else
badmsg "fixture could not be restarted for the multi-agent cursor probe"
fi
+# shellcheck source=tests/e2e/scenarios/ref_churn.sh
+source "$here/scenarios/ref_churn.sh"
+
finish
diff --git a/tests/e2e/scenarios/interaction.sh b/tests/e2e/scenarios/interaction.sh
index 4afde3d15..4304a319f 100644
--- a/tests/e2e/scenarios/interaction.sh
+++ b/tests/e2e/scenarios/interaction.sh
@@ -45,7 +45,7 @@ interaction_suite() {
verify "[$mode] clear empties field" text-echo "" "$natural_mechanism" "$text_field" clear
note "[$mode] state and value controls"
- local toggle picker native_slider native_stepper scroll_area scroll_before scroll_after scroll_output scroll_mechanism
+ local toggle picker native_slider native_stepper scroll_area scroll_before scroll_after scroll_output scroll_mechanism scroll_ready
require_target toggle checkbox toggle-box
act_target "$toggle" uncheck >/dev/null 2>&1
sleep 0.2
@@ -62,6 +62,10 @@ interaction_suite() {
verify "[$mode] set stepper value" stepper-status "$stepper" semantic_api "$native_stepper" set-value "$stepper"
require_target scroll_area scrollarea scroll-area
+ scroll_ready="$(act_target "$scroll_area" scroll-to 2>/dev/null)"
+ assert "[$mode] scroll viewport is brought into view" \
+ "$([ "$(json_field "$scroll_ready" ok)" = "True" ] && echo 1 || echo 0)" \
+ "$(json_field "$scroll_ready" error.message)"
require_value scroll_before scroll-offset
scroll_output="$(act_target "$scroll_area" scroll --direction "$direction" --amount 10 2>&1)"
sleep 0.4
@@ -69,7 +73,7 @@ interaction_suite() {
scroll_mechanism="$(printf '%s' "$scroll_output" | python3 "$json_tool" delivered-mechanism 2>/dev/null)"
assert "[$mode] scroll moves content" \
"$([ "$scroll_before" != "$scroll_after" ] && [ "$scroll_mechanism" = "$natural_mechanism" ] && echo 1 || echo 0)" \
- "before=$scroll_before after=$scroll_after direction=$direction cmd_ok=$(json_field "$scroll_output" ok) cmd_err=$(json_field "$scroll_output" error.code) mechanism=$scroll_mechanism"
+ "before=$scroll_before after=$scroll_after direction=$direction cmd_ok=$(json_field "$scroll_output" ok) cmd_err=$(json_field "$scroll_output" error.code) mechanism=$scroll_mechanism error=$(json_field "$scroll_output" error.message)"
}
interaction_suite headless
diff --git a/tests/e2e/scenarios/ref_churn.sh b/tests/e2e/scenarios/ref_churn.sh
new file mode 100644
index 000000000..a415608ab
--- /dev/null
+++ b/tests/e2e/scenarios/ref_churn.sh
@@ -0,0 +1,63 @@
+note "Default CLI retains native identity 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 &
+churn_pid=$!
+fixture_owned=1
+require_target_by_id filter button filter-rows
+require_target_by_id alpha textfield shared-title
+require_target_by_id stable textfield stable-editor
+act_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)"
+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/null
+wait "$churn_pid" 2>/dev/null
+fixture_owned=0
+
+note "Complete app inventory gives a terminal unknown-app response"
+run_timed "$bin" snapshot --app "AgentDeskMissing-$churn_pid" --timeout-ms 1500
+assert "unknown app is APP_NOT_FOUND without delivery" \
+ "$([ "$(json_field "$RUN_JSON" error.code)" = "APP_NOT_FOUND" ] && [ "$(json_field "$RUN_JSON" error.disposition.delivery)" = "not_delivered" ] && echo 1 || echo 0)" \
+ "exit=$RUN_EXIT elapsed=$RUN_MS code=$(json_field "$RUN_JSON" error.code)"