Skip to content

Computer use CLI for AI agents

fix: close reachable invalid state transitions in sessions, refs, trace, mcp and waits (#602)

Lahfirab7dfb218cdd
diff --git a/crates/core/src/commands/wait_event.rs b/crates/core/src/commands/wait_event.rs
index 005060ee1..5231a02f8 100644
--- a/crates/core/src/commands/wait_event.rs
+++ b/crates/core/src/commands/wait_event.rs
@@ -109,15 +109,15 @@ pub(crate) fn wait_for_event(
input.window_id.as_deref(),
input.window_title.as_deref(),
filter.process.as_ref().map(|process| process.pid),
- ) {
- if confirm_app_terminated(adapter, found, diff_base, deadline) {
- let elapsed = start.elapsed().as_millis();
- return Ok(json!({
- "found": true,
- "event": serde_json::to_value(found)?,
- "elapsed_ms": elapsed,
- }));
- }
+ )
+ .find(|found| confirm_app_terminated(adapter, found, diff_base, deadline))
+ {
+ let elapsed = start.elapsed().as_millis();
+ return Ok(json!({
+ "found": true,
+ "event": serde_json::to_value(found)?,
+ "elapsed_ms": elapsed,
+ }));
}
if disappearance {
seen = Some(merge_signal_baseline(diff_base, &current));
@@ -211,8 +211,8 @@ fn find_match<'a>(
window_id: Option<&str>,
window_title: Option<&str>,
pinned_pid: Option<crate::ProcessId>,
-) -> Option<&'a UiEvent> {
- events.iter().find(|event| {
+) -> impl Iterator<Item = &'a UiEvent> {
+ events.iter().filter(move |event| {
if !requested.same_variant(&event.kind) {
return false;
}
diff --git a/crates/core/src/commands/wait_event_liveness_tests.rs b/crates/core/src/commands/wait_event_liveness_tests.rs
index 94cd7588e..7b7696394 100644
--- a/crates/core/src/commands/wait_event_liveness_tests.rs
+++ b/crates/core/src/commands/wait_event_liveness_tests.rs
@@ -6,6 +6,7 @@ struct LivenessAdapter {
snapshots: Vec<SignalBaseline>,
calls: std::sync::Mutex<usize>,
process_state: Result<ProcessState, ()>,
+ running: Vec<crate::ProcessId>,
process_state_calls: std::sync::Mutex<Vec<crate::ProcessIdentity>>,
}
@@ -15,6 +16,7 @@ impl LivenessAdapter {
snapshots,
calls: std::sync::Mutex::new(0),
process_state,
+ running: Vec::new(),
process_state_calls: std::sync::Mutex::new(Vec::new()),
}
}
@@ -41,7 +43,11 @@ impl SystemOps for LivenessAdapter {
process: crate::ProcessIdentity,
_deadline: crate::Deadline,
) -> Result<ProcessState, AdapterError> {
+ let running = self.running.contains(&process.pid);
self.process_state_calls.lock().unwrap().push(process);
+ if running {
+ return Ok(ProcessState::Running);
+ }
self.process_state
.map_err(|()| AdapterError::not_supported("process_state"))
}
@@ -92,6 +98,26 @@ fn close_to_tray_is_suppressed_but_a_genuine_exit_still_fires() {
);
}
+#[test]
+fn an_unscoped_wait_reports_an_exit_behind_an_app_that_closed_to_tray() {
+ let seed = baseline_with_apps(vec![
+ terminating_app(41, "tray"),
+ terminating_app(42, "exited"),
+ ]);
+ let mut adapter = LivenessAdapter::new(
+ vec![empty_baseline()],
+ Ok(ProcessState::Exited { code: None }),
+ );
+ adapter.running.push(crate::ProcessId::new(41));
+ let mut request = input("app-terminated", None);
+ request.timeout_ms = 300;
+
+ let result = wait_for_event(request, &adapter, Some(Ok(seed))).unwrap();
+
+ assert_eq!(result["found"], true);
+ assert_eq!(result["event"]["pid"], 42);
+}
+
#[test]
fn not_supported_process_state_still_reports_a_genuine_termination() {
let seed = baseline_with_apps(vec![terminating_app(42, "unsupported-check")]);
diff --git a/crates/core/src/context/context_scope_tests.rs b/crates/core/src/context/context_scope_tests.rs
index 283d43992..fc698ccbb 100644
--- a/crates/core/src/context/context_scope_tests.rs
+++ b/crates/core/src/context/context_scope_tests.rs
@@ -252,3 +252,26 @@ fn command_end_omits_secret_and_huge_error_messages() {
assert!(body.len() < 4096);
std::fs::remove_file(path).unwrap();
}
+
+#[test]
+fn a_command_does_not_trace_into_a_session_reaped_while_it_waited_for_its_lease() {
+ let guard = crate::refs::refs_test_support::HomeGuard::new();
+ let home = guard.path().to_path_buf();
+ let manifest = start_session(StartSessionOptions {
+ trace: SessionTraceMode::On,
+ ..Default::default()
+ })
+ .expect("session starts");
+ let dir = crate::session::session_dir(&manifest.id).unwrap();
+ let lock = crate::refs::refs_lock::RefStoreLock::acquire(&dir.join("refstore.lock")).unwrap();
+ let id = manifest.id.clone();
+ let command = std::thread::spawn(move || {
+ crate::refs::set_home_override(Some(home));
+ CommandContext::new(Some(id), None, false)
+ });
+ std::thread::sleep(std::time::Duration::from_millis(200));
+ std::fs::remove_dir_all(&dir).unwrap();
+ drop(lock);
+
+ assert!(!command.join().unwrap().unwrap().trace_enabled());
+}
diff --git a/crates/core/src/context/mod.rs b/crates/core/src/context/mod.rs
index 6f01209ed..51f041143 100644
--- a/crates/core/src/context/mod.rs
+++ b/crates/core/src/context/mod.rs
@@ -89,9 +89,9 @@ impl CommandContext {
if let Some(id) = session_id.as_deref() {
validate_session_id(id)?;
}
+ let session = acquire_session_scope(session_id.clone(), None)?;
let (segment_dir, artifacts_full) =
session_trace_state(session_id.as_deref(), trace_path.is_some())?;
- let session = acquire_session_scope(session_id, None)?;
let cursor_overlay =
session::cursor_overlay_for_session(session.as_ref().map(|scope| scope.id.as_str()))?;
Ok(Self {
@@ -243,6 +243,11 @@ impl CommandContext {
let reuses_parent_session = session_id.as_deref() == self.session_id();
let reuses_parent_trace = reuses_parent_session
|| (self.trace.pending_file_path().is_some() && self.trace.has_sink());
+ let session = if reuses_parent_session {
+ self.session.clone()
+ } else {
+ acquire_session_scope(session_id.clone(), self.inherited_deadline)?
+ };
let (trace, artifacts_full) = if reuses_parent_trace {
(self.trace.clone(), self.artifacts_full)
} else {
@@ -252,11 +257,6 @@ impl CommandContext {
artifacts_full,
)
};
- let session = if reuses_parent_session {
- self.session.clone()
- } else {
- acquire_session_scope(session_id, self.inherited_deadline)?
- };
let cursor_overlay = if reuses_parent_session {
self.options.cursor_overlay.clone()
} else {
diff --git a/crates/core/src/ref_action/mod.rs b/crates/core/src/ref_action/mod.rs
index 85d0d5f3e..b7e50e079 100644
--- a/crates/core/src/ref_action/mod.rs
+++ b/crates/core/src/ref_action/mod.rs
@@ -91,7 +91,7 @@ pub(crate) fn dispatch_resolved_landing(
let preflight = match stable_preflight(&initial_target, &request) {
Ok(preflight) => preflight,
Err(error) => {
- let error = into_adapter_error(error);
+ let error = mark_pre_dispatch_resolution_failure(into_adapter_error(error));
if !crate::ref_action::ref_action_wait_evidence::should_scroll_after_preflight(
&request, &error,
) {
diff --git a/crates/core/src/ref_action/ref_action_wait_unresponsive_tests.rs b/crates/core/src/ref_action/ref_action_wait_unresponsive_tests.rs
index ba14c5676..1662452ce 100644
--- a/crates/core/src/ref_action/ref_action_wait_unresponsive_tests.rs
+++ b/crates/core/src/ref_action/ref_action_wait_unresponsive_tests.rs
@@ -59,3 +59,62 @@ fn auto_wait_retries_a_transiently_unresponsive_accessibility_service() {
assert_eq!(result.action, "click");
assert!(adapter.resolve_calls.load(Ordering::SeqCst) >= 2);
}
+
+struct BusyAtDispatchPreflightAdapter(AtomicU32);
+
+impl ObservationOps for BusyAtDispatchPreflightAdapter {
+ fn resolve_element_strict(
+ &self,
+ _entry: &RefEntry,
+ _deadline: crate::Deadline,
+ ) -> Result<NativeHandle, AdapterError> {
+ Ok(NativeHandle::null())
+ }
+
+ crate::adapter::complete_live_observation!("button", "Run", [capability::CLICK], adapter => {
+ if adapter.0.fetch_add(1, Ordering::SeqCst) == 1 {
+ return Err(AdapterError::timeout("busy").with_details(serde_json::json!({ "retryable": true })));
+ }
+ crate::ElementState {
+ role: "button".into(),
+ states: Vec::new(),
+ value: None,
+ enabled: Some(true),
+ hidden: Some(false),
+ offscreen: Some(false),
+ }
+ });
+ crate::adapter::saved_ref_scope!("button", Some("Run"));
+}
+
+impl ActionOps for BusyAtDispatchPreflightAdapter {
+ fn execute_action(
+ &self,
+ _handle: &NativeHandle,
+ _request: ActionRequest,
+ _lease: &crate::InteractionLease,
+ ) -> Result<crate::actions::action_result::ActionResult, AdapterError> {
+ Ok(crate::actions::action_result::ActionResult::delivered_unverified("click"))
+ }
+}
+
+impl InputOps for BusyAtDispatchPreflightAdapter {}
+impl SystemOps for BusyAtDispatchPreflightAdapter {
+ crate::adapter::guarded_interaction_lease!();
+}
+
+#[test]
+fn auto_wait_retries_a_live_read_timeout_in_the_dispatch_preflight() {
+ let result = execute_with_auto_wait(
+ RefActionWaitCtx {
+ adapter: &BusyAtDispatchPreflightAdapter(AtomicU32::new(0)),
+ entry: &entry(),
+ ref_id: "@e1",
+ context: &CommandContext::default(),
+ },
+ ActionRequest::headless(Action::Click).with_timeout_ms(Some(2_000)),
+ crate::ref_action::ref_action_single::dispatch_resolved,
+ );
+
+ assert_eq!(result.unwrap().action, "click");
+}
diff --git a/crates/core/src/refs/refs_store_prune.rs b/crates/core/src/refs/refs_store_prune.rs
index 96f570e56..f52a68909 100644
--- a/crates/core/src/refs/refs_store_prune.rs
+++ b/crates/core/src/refs/refs_store_prune.rs
@@ -36,7 +36,7 @@ impl RefStore {
);
}
- /// Drops only the refmaps the trace already holds a copy of, leaving every
+ /// Drops only the refmaps the trace holds a byte-identical copy of, leaving every
/// other artifact in place. Being in `ArtifactsMode::Full` is not on its own
/// proof that a copy exists: the artifact budget and a serialisation failure
/// both skip a copy and report success, so a session that recorded more
@@ -57,7 +57,9 @@ impl RefStore {
if validate_snapshot_id(&id).is_err() {
continue;
}
- if duplicates.join(format!("{id}.json")).is_file() {
+ let copy = std::fs::read(duplicates.join(format!("{id}.json")));
+ let original = std::fs::read(entry.path().join("refmap.json"));
+ if copy.is_ok_and(|copy| original.is_ok_and(|original| copy == original)) {
let _ = std::fs::remove_dir_all(entry.path());
}
}
diff --git a/crates/core/src/refs/refs_store_tests.rs b/crates/core/src/refs/refs_store_tests.rs
index f5de66df5..82f1cb8a5 100644
--- a/crates/core/src/refs/refs_store_tests.rs
+++ b/crates/core/src/refs/refs_store_tests.rs
@@ -288,3 +288,27 @@ mod pruning_tests;
#[path = "refs_store_session_tests.rs"]
mod session_tests;
+
+#[test]
+fn discarding_scaffolding_keeps_a_snapshot_drilled_after_its_trace_copy() {
+ let _guard = HomeGuard::new();
+ let store = RefStore::for_session(Some("drilled")).unwrap();
+ let snapshot_id = store.save_new_snapshot(&map_with("Root")).unwrap();
+ let refmaps = crate::trace::trace_artifacts::refmap_artifact_dir(&store.trace_dir());
+ std::fs::create_dir_all(&refmaps).unwrap();
+ std::fs::copy(
+ store.snapshot_path(&snapshot_id),
+ refmaps.join(format!("{snapshot_id}.json")),
+ )
+ .unwrap();
+ store
+ .update_existing_snapshot(&snapshot_id, "@e1", &entry("Root"), |map| {
+ map.allocate(entry("Drilled"));
+ Ok(())
+ })
+ .unwrap();
+
+ store.discard_duplicated_ref_scaffolding();
+
+ assert!(store.snapshot_path(&snapshot_id).is_file());
+}
diff --git a/crates/core/src/session/cursor_profile_tests.rs b/crates/core/src/session/cursor_profile_tests.rs
index 767c13864..63fba1fe4 100644
--- a/crates/core/src/session/cursor_profile_tests.rs
+++ b/crates/core/src/session/cursor_profile_tests.rs
@@ -148,3 +148,31 @@ fn invalid_profile_motion_falls_back_to_session_config() {
master
);
}
+
+#[test]
+fn a_cursor_overlay_write_racing_session_end_cannot_reopen_the_session() {
+ let guard = HomeGuard::new();
+ let home = guard.path().to_path_buf();
+ let manifest = start_session(StartSessionOptions::default()).unwrap();
+ let lock = crate::refs::refs_lock::RefStoreLock::acquire(
+ &session_dir(&manifest.id).unwrap().join("refstore.lock"),
+ )
+ .unwrap();
+ let id = manifest.id.clone();
+ let writer = std::thread::spawn(move || {
+ crate::refs::set_home_override(Some(home));
+ set_cursor_overlay(&id, crate::CursorOverlayConfig::default())
+ });
+ std::thread::sleep(std::time::Duration::from_millis(200));
+ let mut ended = read_manifest(&manifest.id).unwrap().unwrap();
+ ended.ended_at = Some(now_millis());
+ write_manifest(&ended).unwrap();
+ drop(lock);
+
+ assert!(writer.join().unwrap().is_err());
+ assert!(
+ read_manifest(&manifest.id)
+ .unwrap()
+ .is_some_and(|m| m.ended_at.is_some())
+ );
+}
diff --git a/crates/core/src/session/liveness.rs b/crates/core/src/session/liveness.rs
index c34338191..2aaadbd5a 100644
--- a/crates/core/src/session/liveness.rs
+++ b/crates/core/src/session/liveness.rs
@@ -31,19 +31,31 @@ impl Drop for LeaseInner {
}
}
-pub fn acquire(
+/// Takes the session's refstore lock when the session has a manifest. Holding it
+/// excludes GC, lease creation and every other manifest read-modify-write.
+pub(super) fn lock_started_session(
session_id: &str,
deadline: Deadline,
-) -> Result<Option<SessionLivenessLease>, AppError> {
+) -> Result<Option<(RefStoreLock, PathBuf)>, AppError> {
let store = crate::refs::refs_store::RefStore::for_session(Some(session_id))?;
- let base = store.base_dir();
+ let base = store.base_dir().to_path_buf();
if !base.is_dir() {
return Ok(None);
}
- let _store_lock = RefStoreLock::acquire_with_deadline(&base.join("refstore.lock"), deadline)?;
+ let lock = RefStoreLock::acquire_with_deadline(&base.join("refstore.lock"), deadline)?;
if super::read_manifest(session_id)?.is_none() {
return Ok(None);
}
+ Ok(Some((lock, base)))
+}
+
+pub fn acquire(
+ session_id: &str,
+ deadline: Deadline,
+) -> Result<Option<SessionLivenessLease>, AppError> {
+ let Some((_store_lock, base)) = lock_started_session(session_id, deadline)? else {
+ return Ok(None);
+ };
let directory = base.join("liveness");
crate::storage::private_file_parent::ensure_private(&directory)?;
let path = directory.join(lease_filename());
diff --git a/crates/core/src/session/mod.rs b/crates/core/src/session/mod.rs
index 0a76c979e..b56a95c95 100644
--- a/crates/core/src/session/mod.rs
+++ b/crates/core/src/session/mod.rs
@@ -118,6 +118,8 @@ pub fn set_cursor_overlay(
session_id: &str,
cursor_overlay: CursorOverlayConfig,
) -> Result<SessionManifest, AppError> {
+ validate_session_id(session_id)?;
+ let _lock = liveness::lock_started_session(session_id, crate::Deadline::standard()?)?;
let mut manifest = read_manifest(session_id)?.ok_or_else(|| {
AppError::invalid_input_with_suggestion(
format!("Session '{session_id}' has no manifest"),
@@ -327,7 +329,7 @@ pub fn start_session(options: StartSessionOptions) -> Result<SessionManifest, Ap
pub fn end_session(session_id: &str) -> Result<SessionManifest, AppError> {
validate_session_id(session_id)?;
- let _lease = acquire_liveness_lease(session_id)?;
+ let _lock = liveness::lock_started_session(session_id, crate::Deadline::standard()?)?;
let id = session_id.to_string();
let mut manifest = read_manifest(&id)?.ok_or_else(|| {
AppError::invalid_input_with_suggestion(
diff --git a/crates/core/src/session/session_tests.rs b/crates/core/src/session/session_tests.rs
index 1552a9ad2..e0d06434e 100644
--- a/crates/core/src/session/session_tests.rs
+++ b/crates/core/src/session/session_tests.rs
@@ -275,7 +275,11 @@ fn seed_session_refs(id: &str) -> (std::path::PathBuf, String) {
let dir = session_dir(id).unwrap();
let refmaps = dir.join("trace").join("refmaps");
std::fs::create_dir_all(&refmaps).unwrap();
- std::fs::write(refmaps.join(format!("{snapshot_id}.json")), b"{}").unwrap();
+ std::fs::copy(
+ dir.join("snapshots").join(&snapshot_id).join("refmap.json"),
+ refmaps.join(format!("{snapshot_id}.json")),
+ )
+ .unwrap();
std::fs::write(
dir.join("trace").join("42-1.jsonl"),
b"{\"event\":\"command.start\"}\n",
@@ -321,7 +325,11 @@ fn a_refmap_the_trace_never_copied_survives_ending_a_full_session() {
let refmaps = dir.join("trace").join("refmaps");
std::fs::create_dir_all(&refmaps).unwrap();
- std::fs::write(refmaps.join(format!("{copied}.json")), b"{}").unwrap();
+ std::fs::copy(
+ dir.join("snapshots").join(&copied).join("refmap.json"),
+ refmaps.join(format!("{copied}.json")),
+ )
+ .unwrap();
end_session(&manifest.id).unwrap();
diff --git a/crates/core/src/trace/trace_write_budget.rs b/crates/core/src/trace/trace_write_budget.rs
index c53520392..93c194c53 100644
--- a/crates/core/src/trace/trace_write_budget.rs
+++ b/crates/core/src/trace/trace_write_budget.rs
@@ -1,9 +1,5 @@
use crate::refs::refs_lock::RefStoreLock;
-use crate::{
- AppError, Deadline,
- storage::private_file::{open_private_lock, read_private_bounded},
-};
-use std::io::Write;
+use crate::{AppError, Deadline, storage::private_file::read_private_bounded};
use std::path::{Path, PathBuf};
pub(crate) const MAX_SESSION_BYTES: usize = 32 * 1024 * 1024;
@@ -64,11 +60,10 @@ impl TraceWriteBudget {
"Start a new session to continue recording; the existing trace remains readable.",
));
}
- let mut ledger = open_private_lock(&self.directory.join(LEDGER), true)?;
- ledger.set_len(0)?;
- ledger.write_all(&serde_json::to_vec(&self.usage)?)?;
- ledger.sync_data()?;
- Ok(())
+ crate::refs::write_private_file(
+ &self.directory.join(LEDGER),
+ &serde_json::to_vec(&self.usage)?,
+ )
}
}
diff --git a/src/mcp/calls.rs b/src/mcp/calls.rs
index e05b86940..f2d373439 100644
--- a/src/mcp/calls.rs
+++ b/src/mcp/calls.rs
@@ -13,9 +13,16 @@ const EXIT_POLL: Duration = Duration::from_millis(20);
/// Output pipes of a started call.
pub(crate) type Pipes = (Option<ChildStdout>, Option<ChildStderr>);
-/// Each admitted request id, with the child process its call started once it has started one.
+/// Where an admitted call is. A cancelled id stays occupied until its own call finishes.
+enum Slot {
+ Admitted,
+ Running(Child),
+ Cancelled,
+}
+
+/// Each admitted request id with the state of its call.
#[derive(Default)]
-pub(crate) struct Calls(Mutex<HashMap<String, Option<Child>>>);
+pub(crate) struct Calls(Mutex<HashMap<String, Slot>>);
impl Calls {
/// Admits `id` before its call starts; false when a call with that id is already in flight.
@@ -23,7 +30,7 @@ impl Calls {
match self.lock().entry(id.to_string()) {
Entry::Occupied(_) => false,
Entry::Vacant(entry) => {
- entry.insert(None);
+ entry.insert(Slot::Admitted);
true
}
}
@@ -35,32 +42,48 @@ impl Calls {
pub(crate) fn start(&self, id: &Value, command: &mut Command) -> Option<io::Result<Pipes>> {
let mut calls = self.lock();
let slot = calls.get_mut(&id.to_string())?;
+ if matches!(slot, Slot::Cancelled) {
+ return None;
+ }
Some(command.spawn().map(|mut child| {
let pipes = (child.stdout.take(), child.stderr.take());
- *slot = Some(child);
+ *slot = Slot::Running(child);
pipes
}))
}
/// Takes back the child of `id` after its output closed, or `None` when `id` was cancelled.
pub(crate) fn take(&self, id: &Value) -> Option<Child> {
- self.lock().get_mut(&id.to_string()).and_then(Option::take)
+ let mut calls = self.lock();
+ let slot = calls.get_mut(&id.to_string())?;
+ match std::mem::replace(slot, Slot::Admitted) {
+ Slot::Running(child) => Some(child),
+ other => {
+ *slot = other;
+ None
+ }
+ }
}
/// Cancels `id`; an unknown id is ignored. A started child is stopped on its own thread by `terminate`.
pub(crate) fn cancel(&self, id: &Value) {
- let child = self.lock().remove(&id.to_string()).flatten();
- if let Some(child) = child {
+ let slot = self
+ .lock()
+ .get_mut(&id.to_string())
+ .map(|slot| std::mem::replace(slot, Slot::Cancelled));
+ if let Some(Slot::Running(child)) = slot {
std::thread::spawn(move || terminate(child));
}
}
/// Releases `id` once its call has returned; false when it was cancelled, so no response is due.
pub(crate) fn finish(&self, id: &Value) -> bool {
- self.lock().remove(&id.to_string()).is_some()
+ self.lock()
+ .remove(&id.to_string())
+ .is_some_and(|slot| !matches!(slot, Slot::Cancelled))
}
- fn lock(&self) -> MutexGuard<'_, HashMap<String, Option<Child>>> {
+ fn lock(&self) -> MutexGuard<'_, HashMap<String, Slot>> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
}
diff --git a/src/mcp/calls_tests.rs b/src/mcp/calls_tests.rs
index d11584c18..30f8884ba 100644
--- a/src/mcp/calls_tests.rs
+++ b/src/mcp/calls_tests.rs
@@ -24,6 +24,16 @@ fn a_call_cancelled_before_it_starts_never_spawns_and_gets_no_response() {
assert!(!calls.finish(&json!(7)));
}
+#[test]
+fn a_cancelled_id_stays_taken_until_its_own_call_finishes() {
+ let calls = Calls::default();
+ assert!(calls.admit(&json!(5)));
+ calls.cancel(&json!(5));
+ assert!(!calls.admit(&json!(5)));
+ assert!(!calls.finish(&json!(5)));
+ assert!(calls.admit(&json!(5)));
+}
+
#[cfg(unix)]
#[test]
fn a_cancelled_child_gets_sigterm_before_any_kill() {