Skip to content

Computer use CLI for AI agents

fix: preserve partial snapshots after observation expires (#372)

Lahfir53e072dc6e20
diff --git a/crates/core/src/commands/wait.rs b/crates/core/src/commands/wait.rs
index a9acf5a00..f5e4db053 100644
--- a/crates/core/src/commands/wait.rs
+++ b/crates/core/src/commands/wait.rs
@@ -230,7 +230,7 @@ fn wait_for_text(
};
if matched {
let store = RefStore::for_session(context.session_id())?;
- let snapshot_id = store.save_new_snapshot(&result.refmap)?;
+ let snapshot_id = result.save_refmap(&store)?;
trace_artifacts::copy_refmap_if_full(
context,
&store,
diff --git a/crates/core/src/commands/wait_scenario_count_tests.rs b/crates/core/src/commands/wait_scenario_count_tests.rs
index b4c665354..6a44b26e8 100644
--- a/crates/core/src/commands/wait_scenario_count_tests.rs
+++ b/crates/core/src/commands/wait_scenario_count_tests.rs
@@ -96,6 +96,10 @@ text_tree_adapter!(
IncompleteTextTreeAdapter,
doc_window(vec![ready_button("ready one"), truncated_container(2)])
);
+text_tree_adapter!(ExpiringIncompleteTextTreeAdapter, {
+ crate::wait::deadline::sleep(std::time::Duration::from_millis(31));
+ doc_window(vec![ready_button("ready one"), truncated_container(2)])
+});
text_tree_adapter!(
AllHiddenIncompleteAdapter,
doc_window(vec![truncated_container(2)])
@@ -202,3 +206,24 @@ fn text_wait_with_count_on_complete_observation_times_out_when_count_differs() {
assert_eq!(details["kind"], "wait_timeout");
assert_eq!(details["expected_count"], 1);
}
+
+#[test]
+fn text_wait_persists_a_partial_match_after_the_inherited_deadline() {
+ let _guard = crate::refs::refs_test_support::HomeGuard::new();
+ let _clock = crate::wait::deadline::VirtualClock::freeze();
+ let inherited = crate::Deadline::detached_after(30).unwrap();
+ let deadline_scope = crate::wait::deadline::enter_scope(Some(inherited));
+
+ let value = execute(
+ text_wait_args("ready", None, 30_000),
+ &ExpiringIncompleteTextTreeAdapter,
+ &CommandContext::default(),
+ )
+ .expect("a visible text match must survive the expired inherited deadline");
+ assert!(inherited.is_expired());
+ assert_eq!(value["found"], true);
+ let ref_id = value["ref"].as_str().unwrap();
+ drop(deadline_scope);
+ let entry = RefStore::new().unwrap().load_ref(ref_id).unwrap();
+ assert_eq!(entry.identity.name.as_deref(), Some("ready one"));
+}
diff --git a/crates/core/src/commands/wait_selector.rs b/crates/core/src/commands/wait_selector.rs
index d092e8553..0e2e4d298 100644
--- a/crates/core/src/commands/wait_selector.rs
+++ b/crates/core/src/commands/wait_selector.rs
@@ -233,7 +233,7 @@ fn materialized_response(
elapsed_ms: u128,
) -> Result<Value, AppError> {
let store = RefStore::for_session(context.session_id())?;
- let snapshot_id = store.save_new_snapshot(&result.refmap)?;
+ let snapshot_id = result.save_refmap(&store)?;
trace_artifacts::copy_refmap_if_full(context, &store, &snapshot_id, &result.refmap)?;
result.bind_snapshot_id(snapshot_id);
emit_snapshot_saved(context, &result)?;
diff --git a/crates/core/src/commands/wait_selector_inherited_deadline_tests.rs b/crates/core/src/commands/wait_selector_inherited_deadline_tests.rs
index f22b11ad9..4574ac55c 100644
--- a/crates/core/src/commands/wait_selector_inherited_deadline_tests.rs
+++ b/crates/core/src/commands/wait_selector_inherited_deadline_tests.rs
@@ -85,3 +85,36 @@ fn expired_inherited_deadline_without_a_snapshot_still_emits_wait_timeout() {
);
assert_eq!(details["last_error"]["code"], "APP_NOT_FOUND");
}
+
+#[test]
+fn matched_partial_snapshot_is_persisted_after_the_inherited_deadline() {
+ let _guard = HomeGuard::new();
+ let clock = crate::wait::deadline::VirtualClock::freeze();
+ let inherited = crate::Deadline::detached_after(30).unwrap();
+ let deadline_scope = crate::wait::deadline::enter_scope(Some(inherited));
+ let mut tree = window_node(vec![button_node("saved")]);
+ tree.subtree_truncated = true;
+ let input = base_input("button:saved", false);
+ let result = snapshot::build(
+ &StaticTreeAdapter { tree },
+ &input.opts,
+ input.app.as_deref(),
+ None,
+ inherited,
+ )
+ .unwrap();
+ assert!(!result.complete);
+ clock.advance(std::time::Duration::from_millis(31));
+
+ let value = materialized_response(result, &CommandContext::default(), &input, 31)
+ .expect("a matched partial snapshot must survive the expired inherited deadline");
+ assert_eq!(value["matched_selector"], "button:saved");
+ assert_eq!(value["complete"], false);
+ let snapshot_id = value["snapshot_id"].as_str().unwrap();
+ drop(deadline_scope);
+ let refmap = RefStore::new().unwrap().load(Some(snapshot_id)).unwrap();
+ assert_eq!(
+ refmap.get("@e1").unwrap().identity.name.as_deref(),
+ Some("saved")
+ );
+}
diff --git a/crates/core/src/refs/refs_lock.rs b/crates/core/src/refs/refs_lock.rs
index 516d4e870..98fb0d177 100644
--- a/crates/core/src/refs/refs_lock.rs
+++ b/crates/core/src/refs/refs_lock.rs
@@ -14,11 +14,9 @@ impl RefStoreLock {
Self::acquire_with_deadline(path, deadline)
}
- /// Recovery-path lock: the budget is detached from the (possibly already
- /// expired) inherited command deadline. Use ONLY for post-deadline
- /// diagnostic work — e.g. persisting the last built snapshot after a wait
- /// timeout — which must run after the operation's own deadline has expired
- /// and must not collapse to an immediate `lock_timeout`.
+ /// Recovery-path lock: the budget is detached from an inherited command
+ /// deadline so an already-built partial snapshot or wait result can still
+ /// be persisted.
pub(crate) fn acquire_detached(path: &Path) -> Result<Self, AppError> {
let deadline = Deadline::detached_after(LOCK_TIMEOUT_MS)?;
Self::acquire_with_deadline(path, deadline)
diff --git a/crates/core/src/refs/refs_store.rs b/crates/core/src/refs/refs_store.rs
index 8f46b07eb..81f50aabd 100644
--- a/crates/core/src/refs/refs_store.rs
+++ b/crates/core/src/refs/refs_store.rs
@@ -48,11 +48,9 @@ impl RefStore {
}
/// Recovery-path variant of [`save_new_snapshot`]: the ref-store write
- /// lock is acquired with a deadline detached from any inherited (and
- /// possibly already-expired) command deadline. Used by post-timeout
- /// diagnostic persistence, which runs after the operation's own deadline
- /// has expired and must not collapse to an immediate `lock_timeout` that
- /// would replace the intended `wait_timeout` envelope.
+ /// lock is acquired with a deadline detached from any inherited command
+ /// deadline. Use it to persist an already-built partial snapshot or a
+ /// post-timeout wait result after its command deadline expires.
pub(crate) fn save_new_snapshot_detached(&self, refmap: &RefMap) -> Result<String, AppError> {
self.with_write_lock_detached(|| self.save_new_snapshot_unlocked_with_id(refmap))
}
diff --git a/crates/core/src/snapshot/mod.rs b/crates/core/src/snapshot/mod.rs
index 0e40ed6a3..45859b9ce 100644
--- a/crates/core/src/snapshot/mod.rs
+++ b/crates/core/src/snapshot/mod.rs
@@ -26,6 +26,14 @@ pub struct SnapshotResult {
}
impl SnapshotResult {
+ pub(crate) fn save_refmap(&self, store: &RefStore) -> Result<String, AppError> {
+ if self.complete {
+ store.save_new_snapshot(&self.refmap)
+ } else {
+ store.save_new_snapshot_detached(&self.refmap)
+ }
+ }
+
pub(crate) fn bind_snapshot_id(&mut self, snapshot_id: String) {
crate::refs::ref_token::qualify_tree_refs(&mut self.tree, &snapshot_id);
self.snapshot_id = Some(snapshot_id);
@@ -345,7 +353,7 @@ pub fn run_with_context(
crate::Deadline::after(timeout_ms)?,
)?;
let store = RefStore::for_session(context.session_id())?;
- let snapshot_id = store.save_new_snapshot(&result.refmap)?;
+ let snapshot_id = result.save_refmap(&store)?;
trace_artifacts::copy_refmap_if_full(context, &store, &snapshot_id, &result.refmap)?;
result.bind_snapshot_id(snapshot_id);
emit_snapshot_saved(context, &result)?;
@@ -391,6 +399,10 @@ mod tokenless_capture_tests;
#[path = "tokenless_drill_tests.rs"]
mod tokenless_drill_tests;
+#[cfg(test)]
+#[path = "snapshot_deadline_tests.rs"]
+mod deadline_tests;
+
#[cfg(test)]
#[path = "snapshot_window_tests.rs"]
mod window_tests;
diff --git a/crates/core/src/snapshot/snapshot_deadline_tests.rs b/crates/core/src/snapshot/snapshot_deadline_tests.rs
new file mode 100644
index 000000000..fb2ac619e
--- /dev/null
+++ b/crates/core/src/snapshot/snapshot_deadline_tests.rs
@@ -0,0 +1,88 @@
+use super::*;
+use crate::adapter::{ActionOps, InputOps, ObservationOps, SystemOps, WindowFilter};
+use crate::locator::live_locator::{ObservationRequest, ObservationRoot, ObservedTree};
+use crate::refs::refs_test_support::HomeGuard;
+use std::time::Duration;
+
+struct PartialSnapshotAdapter;
+
+impl ObservationOps for PartialSnapshotAdapter {
+ fn observe_tree(
+ &self,
+ root: ObservationRoot<'_>,
+ _request: &ObservationRequest,
+ ) -> Result<ObservedTree, crate::AdapterError> {
+ crate::wait::deadline::sleep(Duration::from_millis(31));
+ let tree = crate::AccessibilityNode {
+ ref_id: None,
+ role: "window".into(),
+ identity: Default::default(),
+ presentation: Default::default(),
+ children_count: None,
+ subtree_truncated: true,
+ children: Vec::new(),
+ };
+ crate::adapter::observed_tree(&root, tree)
+ }
+
+ fn list_windows(
+ &self,
+ _filter: &WindowFilter,
+ _deadline: crate::Deadline,
+ ) -> Result<Vec<crate::WindowInfo>, crate::AdapterError> {
+ Ok(vec![crate::WindowInfo {
+ id: "w-1".into(),
+ title: "Test".into(),
+ app: "TestApp".into(),
+ pid: crate::ProcessId::new(42),
+ process_instance: Some("test-instance".into()),
+ bounds: None,
+ state: Default::default(),
+ }])
+ }
+}
+
+impl ActionOps for PartialSnapshotAdapter {}
+impl InputOps for PartialSnapshotAdapter {}
+impl SystemOps for PartialSnapshotAdapter {}
+
+#[test]
+fn expired_snapshot_deadline_persists_partial_tree_and_releases_the_store_lock() {
+ let _home = HomeGuard::new();
+ let _clock = crate::wait::deadline::VirtualClock::freeze();
+ let inherited = crate::Deadline::detached_after(30).unwrap();
+ let deadline_scope = crate::wait::deadline::enter_scope(Some(inherited));
+ let context = crate::CommandContext::default();
+ let adapter = PartialSnapshotAdapter;
+
+ let result = run_with_context(
+ &adapter,
+ &TreeOptions::default(),
+ &SnapshotTarget {
+ app_name: Some("TestApp"),
+ window_id: None,
+ },
+ &context,
+ 30,
+ )
+ .expect("a partial snapshot should persist after its observation deadline");
+
+ assert!(!result.complete);
+ let snapshot_id = result.snapshot_id.expect("snapshot id");
+ drop(deadline_scope);
+ let store = RefStore::new().unwrap();
+ assert_eq!(store.latest_snapshot_id().unwrap(), Some(snapshot_id));
+
+ let next = run_with_context(
+ &adapter,
+ &TreeOptions::default(),
+ &SnapshotTarget {
+ app_name: Some("TestApp"),
+ window_id: None,
+ },
+ &context,
+ 1_000,
+ )
+ .expect("a later snapshot should acquire the released ref-store lock");
+ assert!(next.snapshot_id.is_some());
+}
diff --git a/crates/core/src/trace/trace_read/input_tests.rs b/crates/core/src/trace/trace_read/input_tests.rs
index 23a81467e..95a3bbb9a 100644
--- a/crates/core/src/trace/trace_read/input_tests.rs
+++ b/crates/core/src/trace/trace_read/input_tests.rs
@@ -102,9 +102,12 @@ fn session_writer_preserves_readability_at_aggregate_byte_limit() {
file.write_all(&vec![b'\n'; target - written]).unwrap();
drop(file);
let writer = crate::trace::TraceConfig::build(None, Some(dir.clone()), true).unwrap();
- let error = writer
- .emit("last", None, serde_json::json!({}))
- .unwrap_err();
+ let error = {
+ let _clock = crate::wait::deadline::VirtualClock::freeze();
+ writer
+ .emit("last", None, serde_json::json!({}))
+ .unwrap_err()
+ };
assert!(error.to_string().contains("recording limit"), "{error}");
let trace = read_merged(
&dir,
@@ -126,9 +129,12 @@ fn session_writer_preserves_readability_at_aggregate_event_limit() {
}
drop(file);
let writer = crate::trace::TraceConfig::build(None, Some(dir.clone()), true).unwrap();
- let error = writer
- .emit("last", None, serde_json::json!({}))
- .unwrap_err();
+ let error = {
+ let _clock = crate::wait::deadline::VirtualClock::freeze();
+ writer
+ .emit("last", None, serde_json::json!({}))
+ .unwrap_err()
+ };
assert!(error.to_string().contains("recording limit"), "{error}");
let trace = read_merged(
&dir,