Skip to content

Computer use CLI for AI agents

test: remove flaky and slow live tests from CI (#325)

Lahfir1830dde18985
diff --git a/crates/core/src/trace/trace_tests.rs b/crates/core/src/trace/trace_tests.rs
index 52546b0f9..84eed691b 100644
--- a/crates/core/src/trace/trace_tests.rs
+++ b/crates/core/src/trace/trace_tests.rs
@@ -1,5 +1,6 @@
use super::*;
use crate::refs::refs_test_support::HomeGuard;
+use crate::wait::deadline::VirtualClock;
use serde_json::json;
use std::fs;
@@ -90,6 +91,7 @@ fn explicit_trace_opens_eagerly_at_build() {
#[test]
fn segment_lazy_open_creates_trace_dir_on_first_event() {
+ let _clock = VirtualClock::freeze();
let _guard = HomeGuard::new();
let trace_dir = crate::refs::refs_store::RefStore::for_session(Some("run-42"))
.unwrap()
@@ -211,6 +213,7 @@ fn segment_open_rejects_symlinked_trace_dir() {
#[test]
fn trace_meta_is_first_line_of_new_segment() {
+ let _clock = VirtualClock::freeze();
let trace_dir = std::env::temp_dir().join(format!(
"agent-desktop-meta-dir-{}",
std::time::SystemTime::now()
diff --git a/crates/core/src/tree/renderer_accessibility_tests.rs b/crates/core/src/tree/renderer_accessibility_tests.rs
index c42b6cd3a..5248b59fc 100644
--- a/crates/core/src/tree/renderer_accessibility_tests.rs
+++ b/crates/core/src/tree/renderer_accessibility_tests.rs
@@ -181,6 +181,7 @@ struct SwitchAdapter {
struct Walk {
expires_no_earlier_than: std::time::Instant,
expires_no_later_than: std::time::Instant,
+ remaining: std::time::Duration,
timeout_ms: u64,
}
@@ -197,6 +198,7 @@ impl ObservationOps for SwitchAdapter {
walks.push(Walk {
expires_no_earlier_than: before + remaining,
expires_no_later_than: after + remaining,
+ remaining,
timeout_ms: request.deadline.timeout_ms(),
});
if walks.len() == 1 {
@@ -352,19 +354,20 @@ fn a_refused_switch_reports_the_operation_budget_and_is_not_retried() {
#[test]
fn the_credit_for_switch_time_stays_inside_an_inherited_deadline() {
+ let _clock = crate::wait::deadline::VirtualClock::freeze();
let adapter = switch(0, 300);
let window = renderer_window();
let request = snapshot_request(crate::Deadline::after(60_000).unwrap());
let parent = crate::Deadline::detached_after(1_000).unwrap();
- let bound = std::time::Instant::now() + std::time::Duration::from_millis(1_000);
let _scope = crate::wait::deadline::enter_scope(Some(parent));
observe_tree(&adapter, ObservationRoot::Window(&window), &request)
.expect("the walk after the switch still fits the inherited deadline");
let walks = adapter.walks.lock().unwrap();
- assert!(
- walks[1].expires_no_earlier_than <= bound,
+ assert_eq!(
+ walks[1].remaining,
+ parent.remaining(),
"the resumed walk outlives the deadline the command inherited"
);
}
diff --git a/crates/linux/src/system/launch/launch_tests.rs b/crates/linux/src/system/launch/launch_tests.rs
index 1a6c226e6..600658535 100644
--- a/crates/linux/src/system/launch/launch_tests.rs
+++ b/crates/linux/src/system/launch/launch_tests.rs
@@ -99,24 +99,61 @@ fn a_missing_program_is_app_not_found_and_the_error_holds_no_argument_or_environ
assert!(text.contains("tool"));
}
-fn environ_of(pid: u32, program: &str) -> Vec<u8> {
- for _ in 0..200 {
- let comm = std::fs::read_to_string(format!("/proc/{pid}/comm")).unwrap_or_default();
- if comm.trim() == program {
- let environ = std::fs::read(format!("/proc/{pid}/environ")).unwrap_or_default();
- if !environ.is_empty() {
- return environ;
- }
+const REPORTER: &str = r#"report="$1"
+stdin=$(readlink /proc/$$/fd/0)
+stdout=$(readlink /proc/$$/fd/1)
+stderr=$(readlink /proc/$$/fd/2)
+group=$(cut -d' ' -f5 /proc/$$/stat)
+printf '%s
+' "$stdin" "$stdout" "$stderr" "$group" > "$report/facts"
+env -0 > "$report/environ"
+: > "$report/done""#;
+
+struct Report {
+ directory: PathBuf,
+ spawned: Spawned,
+}
+
+impl Report {
+ fn of(launch: &LaunchOptions) -> Self {
+ static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
+ let directory = std::env::temp_dir().join(format!(
+ "launch-report-{}-{}",
+ std::process::id(),
+ NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
+ ));
+ std::fs::create_dir_all(&directory).expect("report directory");
+ let directory_argument = directory.to_string_lossy().into_owned();
+ let plan = plan_of(&["/bin/sh", "-c", REPORTER, "sh", &directory_argument]);
+ let spawned = spawn("reporter", &plan, launch).expect("spawn");
+ let deadline = Instant::now() + Duration::from_secs(30);
+ while !directory.join("done").exists() && Instant::now() < deadline {
+ std::thread::sleep(Duration::from_millis(10));
}
- std::thread::sleep(Duration::from_millis(10));
+ assert!(
+ directory.join("done").exists(),
+ "the reporter never finished"
+ );
+ Self { directory, spawned }
+ }
+
+ fn facts(&self) -> Vec<String> {
+ std::fs::read_to_string(self.directory.join("facts"))
+ .expect("facts")
+ .lines()
+ .map(str::to_owned)
+ .collect()
+ }
+
+ fn environ(&self) -> Vec<u8> {
+ std::fs::read(self.directory.join("environ")).expect("environ")
}
- panic!("the environment of {pid} never became readable");
}
-fn fd_target(pid: u32, fd: u32) -> String {
- std::fs::read_link(format!("/proc/{pid}/fd/{fd}"))
- .map(|path| path.to_string_lossy().into_owned())
- .unwrap_or_default()
+impl Drop for Report {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_dir_all(&self.directory);
+ }
}
#[test]
@@ -125,17 +162,18 @@ fn the_app_gets_the_null_device_its_own_group_and_the_caller_environment_plus_th
env: BTreeMap::from([("LAUNCH_TEST_ADDED".to_owned(), "yes".to_owned())]),
..options()
};
- let spawned = spawn("sleep", &plan_of(&["/bin/sleep", "30"]), &launch).expect("spawn");
- for fd in 0..3 {
- assert_eq!(fd_target(spawned.pid, fd), "/dev/null", "fd {fd}");
- }
- let stat = std::fs::read_to_string(format!("/proc/{}/stat", spawned.pid)).expect("stat");
- let group = stat
- .rsplit(')')
- .next()
- .and_then(|rest| rest.split_whitespace().nth(2));
- assert_eq!(group, Some(spawned.pid.to_string().as_str()));
- let environ = environ_of(spawned.pid, "sleep");
+ let report = Report::of(&launch);
+ let facts = report.facts();
+ assert_eq!(
+ facts,
+ [
+ "/dev/null",
+ "/dev/null",
+ "/dev/null",
+ &report.spawned.pid.to_string()
+ ]
+ );
+ let environ = report.environ();
let variables: Vec<&[u8]> = environ.split(|byte| *byte == 0).collect();
assert!(variables.contains(&b"LAUNCH_TEST_ADDED=yes".as_slice()));
let inherited = std::env::var("PATH").expect("PATH");
@@ -148,18 +186,17 @@ fn the_app_gets_the_null_device_its_own_group_and_the_caller_environment_plus_th
] {
if let Ok(value) = std::env::var(name) {
let line = format!("{name}={value}");
- assert!(
- environ
- .split(|byte| *byte == 0)
- .any(|var| var == line.as_bytes()),
- "{name}"
- );
+ assert!(variables.contains(&line.as_bytes()), "{name}");
}
}
- let pid = spawned.pid;
- kill(&spawned);
- drop(spawned);
- let deadline = Instant::now() + Duration::from_secs(2);
+}
+
+#[test]
+fn a_spawned_child_is_reaped_once_its_guard_goes() {
+ let report = Report::of(&options());
+ let pid = report.spawned.pid;
+ drop(report);
+ let deadline = Instant::now() + Duration::from_secs(10);
while std::path::Path::new(&format!("/proc/{pid}")).exists() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(10));
}
@@ -266,11 +303,9 @@ fn the_first_window_of_an_application_the_launch_started_is_its_window() {
#[test]
fn a_launched_process_carries_the_marker_that_proves_the_caller_started_it() {
- let spawned = spawn("sleeper", &plan_of(&["/bin/sleep", "30"]), &options()).expect("spawns");
- let environment = environ_of(spawned.pid, "sleep");
- kill(&spawned);
+ let report = Report::of(&options());
assert!(crate::system::process::session_origin::has_launch_marker(
- &environment
+ &report.environ()
));
}
diff --git a/crates/linux/src/system/process/proc_scan.rs b/crates/linux/src/system/process/proc_scan.rs
index a1b102922..cdc84baa0 100644
--- a/crates/linux/src/system/process/proc_scan.rs
+++ b/crates/linux/src/system/process/proc_scan.rs
@@ -53,6 +53,16 @@ pub(crate) fn find_running(query: &str) -> Option<(u32, String)> {
}
fn find_in_session(query: &str, session: &SessionKey) -> Option<(u32, String)> {
+ find_with_environ(query, session, &|pid| {
+ std::fs::read(format!("/proc/{pid}/environ")).ok()
+ })
+}
+
+fn find_with_environ(
+ query: &str,
+ session: &SessionKey,
+ environ_of: &dyn Fn(u32) -> Option<Vec<u8>>,
+) -> Option<(u32, String)> {
let index = current_index();
std::fs::read_dir("/proc")
.ok()?
@@ -60,11 +70,7 @@ fn find_in_session(query: &str, session: &SessionKey) -> Option<(u32, String)> {
.filter_map(|entry| entry.file_name().to_string_lossy().parse::<u32>().ok())
.find_map(|pid| {
if (session.bus.is_some() || session.runtime.is_some())
- && !session.owns(
- std::fs::read(format!("/proc/{pid}/environ"))
- .ok()
- .as_deref(),
- )
+ && !session.owns(environ_of(pid).as_deref())
{
return None;
}
diff --git a/crates/linux/src/system/process/proc_scan_tests.rs b/crates/linux/src/system/process/proc_scan_tests.rs
index 8f87e1699..cee86bdce 100644
--- a/crates/linux/src/system/process/proc_scan_tests.rs
+++ b/crates/linux/src/system/process/proc_scan_tests.rs
@@ -1,5 +1,4 @@
use super::SessionKey;
-use std::os::unix::fs::PermissionsExt;
fn key(bus: Option<&str>, runtime: Option<&str>) -> SessionKey {
SessionKey {
@@ -34,89 +33,39 @@ fn session_ownership_requires_an_exact_bus_or_runtime_match() {
assert!(!ours.owns(Some(&environ(&["XDG_RUNTIME_DIR=/run/user/10000"]))));
}
-struct Spawned {
- child: std::process::Child,
- directory: std::path::PathBuf,
- name: String,
-}
-
-impl Drop for Spawned {
- fn drop(&mut self) {
- let _ = self.child.kill();
- let _ = self.child.wait();
- let _ = std::fs::remove_dir_all(&self.directory);
- }
-}
-
const RUNTIME: &str = "/run/user/test-session-a";
const BUS: &str = "unix:path=/run/user/test-session-a/bus";
-const CHILD: &str = "AGENT_DESKTOP_PROC_SCAN_CHILD";
fn this_session() -> SessionKey {
key(Some(BUS), Some(RUNTIME))
}
-fn spawn_uniquely_named(tag: &str) -> Spawned {
- let name = format!("adsc{tag}-{}", std::process::id());
- let directory = std::env::temp_dir().join(format!("{name}-dir"));
- std::fs::create_dir_all(&directory).expect("a directory");
- let program = directory.join(&name);
- std::fs::copy(std::env::current_exe().expect("test executable"), &program)
- .expect("a copy of the test executable");
- std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755)).expect("modes");
- let child = std::process::Command::new(&program)
- .args([
- "--exact",
- "system::process::proc_scan::tests::proc_scan_finds_our_process_and_rejects_it_from_another_session",
- ])
- .env(CHILD, "1")
- .env("XDG_RUNTIME_DIR", RUNTIME)
- .env("DBUS_SESSION_BUS_ADDRESS", BUS)
- .env_remove("DBUS_STARTER_ADDRESS")
- .spawn()
- .expect("a child");
- let started = std::time::Instant::now();
- let short: String = name.chars().take(15).collect();
- let pid = child.id();
- let ready = || {
- std::fs::read_to_string(format!("/proc/{pid}/comm"))
- .is_ok_and(|comm| comm.trim_end() == short)
- && std::fs::read(format!("/proc/{pid}/environ")).is_ok_and(|bytes| !bytes.is_empty())
- };
- while started.elapsed() < std::time::Duration::from_secs(5) && !ready() {
- std::thread::sleep(std::time::Duration::from_millis(20));
- }
- let spawned = Spawned {
- child,
- directory,
- name,
- };
- assert!(
- ready(),
- "child {pid} never showed its name and environment in /proc"
- );
- spawned
+fn environment_of_session_a() -> Vec<u8> {
+ environ(&["HOME=/h", &format!("DBUS_SESSION_BUS_ADDRESS={BUS}")])
}
#[test]
fn proc_scan_finds_our_process_and_rejects_it_from_another_session() {
- if std::env::var_os(CHILD).is_some() {
- std::thread::sleep(std::time::Duration::from_secs(60));
- return;
- }
- let own = spawn_uniquely_named("x");
+ let pid = std::process::id();
+ let facts = crate::system::process::process_facts::read(pid).expect("this process is readable");
+ let name = crate::system::app::app_name::app_name(&facts);
+ let only_this_process = |environment: Vec<u8>| {
+ move |candidate: u32| (candidate == pid).then(|| environment.clone())
+ };
+ let found = super::find_with_environ(
+ &name,
+ &this_session(),
+ &only_this_process(environment_of_session_a()),
+ );
+ assert_eq!(found, Some((pid, facts.comm.clone())));
let elsewhere = key(
Some("unix:path=/run/user/test-session-b/bus"),
Some("/run/user/test-session-b"),
);
- let pid = own.child.id();
- let found = super::find_in_session(&own.name, &this_session()).unwrap_or_else(|| {
- panic!(
- "the scan missed live child {pid}: lookup={:?} environ_readable={}",
- crate::system::process::process_facts::lookup(pid),
- std::fs::read(format!("/proc/{pid}/environ")).is_ok()
- )
- });
- assert_eq!(found.0, pid);
- assert_eq!(super::find_in_session(&own.name, &elsewhere), None);
+ let other_session = super::find_with_environ(
+ &name,
+ &elsewhere,
+ &only_this_process(environment_of_session_a()),
+ );
+ assert_eq!(other_session, None);
}
diff --git a/crates/macos/src/input/clipboard/clipboard_helper_process.rs b/crates/macos/src/input/clipboard/clipboard_helper_process.rs
index dcba27733..66c402d8f 100644
--- a/crates/macos/src/input/clipboard/clipboard_helper_process.rs
+++ b/crates/macos/src/input/clipboard/clipboard_helper_process.rs
@@ -229,7 +229,7 @@ mod tests {
fn hard_deadline_kills_the_helper_process_group() {
let pgid_file = std::env::temp_dir().join(format!("ad-clip-pgid-{}", std::process::id()));
let mut command = Command::new("/bin/sh");
- command.args(["-c", "echo $$ > \"$1\"; sleep 5 & wait", "sh"]);
+ command.args(["-c", "echo $$ > \"$1\"; sleep 60 & wait", "sh"]);
command.arg(&pgid_file);
let error = run(&mut command, &[], Deadline::after(800).unwrap(), None).unwrap_err();
@@ -241,19 +241,18 @@ mod tests {
.parse()
.expect("process group id");
let _ = std::fs::remove_file(&pgid_file);
- let group_gone = Instant::now() + Duration::from_secs(2);
- while unsafe { libc::kill(-pgid, 0) } == 0 && Instant::now() < group_gone {
+ let give_up = Instant::now() + Duration::from_secs(10);
+ while group_has_live_member(pgid) && Instant::now() < give_up {
std::thread::sleep(POLL_INTERVAL);
}
- let probe = unsafe { libc::kill(-pgid, 0) };
- assert_eq!(
- probe, -1,
+ assert!(
+ !group_has_live_member(pgid),
"helper process group {pgid} survived the deadline"
);
- assert_eq!(
- std::io::Error::last_os_error().raw_os_error(),
- Some(libc::ESRCH)
- );
+ }
+
+ fn group_has_live_member(pgid: i32) -> bool {
+ unsafe { libc::kill(-pgid, 0) == 0 }
}
#[test]
diff --git a/crates/macos/src/system/permissions/permission_guide.rs b/crates/macos/src/system/permissions/permission_guide.rs
index 4aa278400..b4228fb5d 100644
--- a/crates/macos/src/system/permissions/permission_guide.rs
+++ b/crates/macos/src/system/permissions/permission_guide.rs
@@ -218,10 +218,23 @@ mod tests {
assert!(lock_file(&path).unwrap().is_none());
child.kill().unwrap();
child.wait().unwrap();
- assert!(lock_file(&path).unwrap().is_some());
+ assert!(lock_released_within(&path, Duration::from_secs(10)));
std::fs::remove_file(&path).unwrap();
}
+ fn lock_released_within(path: &Path, limit: Duration) -> bool {
+ let give_up = Instant::now() + limit;
+ loop {
+ if lock_file(path).unwrap().is_some() {
+ return true;
+ }
+ if Instant::now() >= give_up {
+ return false;
+ }
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ }
+
#[test]
fn grant_probe_reads_only_the_requested_permission() {
let stdout = br#"{"ok":true,"data":{"accessibility":{"state":"granted"},"screen_recording":{"state":"denied"}}}"#;
diff --git a/crates/macos/src/system/permissions/permission_helper_tests.rs b/crates/macos/src/system/permissions/permission_helper_tests.rs
index fbe82afde..525024854 100644
--- a/crates/macos/src/system/permissions/permission_helper_tests.rs
+++ b/crates/macos/src/system/permissions/permission_helper_tests.rs
@@ -104,18 +104,3 @@ fn correlation_tokens_use_full_os_random_shape() {
assert!(valid_token(&token));
assert_eq!(token.len(), TOKEN_BYTES * 2);
}
-
-#[cfg(unix)]
-#[test]
-fn helper_subprocess_timeout_kills_descendants_without_blocking() {
- let started = std::time::Instant::now();
- let error = crate::system::process::run_with_timeout(
- Command::new("/bin/sh").args(["-c", "sleep 5 & wait"]),
- "permission helper timeout fixture",
- std::time::Duration::from_millis(200),
- )
- .unwrap_err();
-
- assert_eq!(error.code, ErrorCode::Timeout);
- assert!(started.elapsed() < std::time::Duration::from_secs(1));
-}
diff --git a/crates/macos/src/system/process/process_state_tests.rs b/crates/macos/src/system/process/process_state_tests.rs
index 7a82f24e8..4220a5664 100644
--- a/crates/macos/src/system/process/process_state_tests.rs
+++ b/crates/macos/src/system/process/process_state_tests.rs
@@ -70,21 +70,17 @@ fn immediately_responsive_pid_classifies_running_with_one_probe() {
#[cfg(target_os = "macos")]
#[test]
fn exited_child_process_is_classified_exited_with_no_code() {
- let mut child = std::process::Command::new("/bin/echo")
- .arg("hi")
+ let mut child = std::process::Command::new("/bin/cat")
+ .stdin(std::process::Stdio::piped())
+ .stdout(std::process::Stdio::null())
.spawn()
- .expect("spawn /bin/echo");
+ .expect("spawn /bin/cat");
let pid = i32::try_from(child.id()).expect("child pid fits macOS pid_t");
let instance = crate::system::process::process_identity::token_for_pid(pid)
.expect("capture child process identity")
- .expect("child remains live before wait");
+ .expect("child blocked on stdin is live");
+ drop(child.stdin.take());
child.wait().expect("wait for exit");
- for _ in 0..50 {
- if !pid_is_alive(pid) {
- break;
- }
- std::thread::sleep(std::time::Duration::from_millis(20));
- }
let state = process_state_impl(
agent_desktop_core::ProcessIdentity {
diff --git a/crates/windows/src/notifications/actions.rs b/crates/windows/src/notifications/actions.rs
index c6826d8fe..c861de5e7 100644
--- a/crates/windows/src/notifications/actions.rs
+++ b/crates/windows/src/notifications/actions.rs
@@ -17,14 +17,6 @@ use super::verify::{
#[path = "actions_tests.rs"]
mod tests;
-#[cfg(all(test, target_os = "windows"))]
-#[path = "actions_live_tests.rs"]
-mod live_tests;
-
-#[cfg(all(test, target_os = "windows"))]
-#[path = "actions_gate_tests.rs"]
-mod gate_tests;
-
/// Removes exactly the identified notification and proves the removal by
/// re-reading the surface.
///
@@ -152,7 +144,11 @@ fn clear_all_still_the_sole_target(
deadline: Deadline,
) -> Result<bool, AdapterError> {
let current = super::list::list_infos(&NotificationFilter::default(), hwnd, deadline)?;
- Ok(current.len() == 1 && same_identity(target, &current[0]))
+ Ok(is_sole_target(target, &current))
+}
+
+fn is_sole_target(target: &NotificationInfo, current: &[NotificationInfo]) -> bool {
+ matches!(current, [only] if same_identity(target, only))
}
fn dismiss_all_impl(
diff --git a/crates/windows/src/notifications/actions_gate_tests.rs b/crates/windows/src/notifications/actions_gate_tests.rs
deleted file mode 100644
index 88e88c1c5..000000000
--- a/crates/windows/src/notifications/actions_gate_tests.rs
+++ /dev/null
@@ -1,85 +0,0 @@
-//! The clear-all substitute's re-verify gate, driven live against the same
-//! staged-toast arrangement the accepted-but-ignored test uses: the substitute
-//! may only fire while the center still holds exactly one entry and it is
-//! still the target, so the identity-mismatch case and the
-//! two-entry-appears case must both answer `false` before anything is
-//! invoked.
-
-#![cfg(target_os = "windows")]
-
-use agent_desktop_core::NotificationInfo;
-
-use super::clear_all_still_the_sole_target;
-use crate::notifications::session::ActionCenterSession;
-use crate::notifications::toast_support::{
- self, StagedToast, TOAST_BODY_SECOND, TOAST_TITLE_SECOND,
-};
-use crate::system::fixture::test_support::{SHELL_SURFACE_LOCK, or_skip_shell};
-use crate::system::shell::raise_oracle::{responded_since, witness_desktop};
-
-use crate::system::fixture::test_time::{deadline, headed};
-
-/// With exactly one staged entry and its own identity the substitute is
-/// faithful and the gate answers true; a fabricated identity the sole entry
-/// does not carry aborts it; a second entry arriving aborts it - the
-/// raced-arrival shape the gate exists to close.
-#[test]
-fn the_clear_all_substitute_fires_only_on_exactly_one_matching_entry() {
- crate::tree::fixture::bootstrap();
- let _lock = SHELL_SURFACE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- toast_support::clear_center(deadline(20_000));
- let witness = witness_desktop();
- let Some(held) = or_skip_shell(
- "action center open for the gate check",
- ActionCenterSession::open(headed(), deadline(15_000)),
- || responded_since(&witness),
- ) else {
- return;
- };
- let _staged = StagedToast::stage();
- let Some(listed) = toast_support::wait_until_listed_held(held.hwnd(), deadline(30_000)) else {
- eprintln!("skip toast staging: this desktop's toast staging produced no entry");
- held.close().expect("the held session restores the surface");
- return;
- };
- assert_eq!(
- listed.len(),
- 1,
- "the staged toast is the only entry after the reset"
- );
- let target = listed.first().expect("one entry").clone();
-
- assert!(
- clear_all_still_the_sole_target(held.hwnd(), &target, deadline(20_000))
- .expect("the re-verify read"),
- "exactly one entry whose identity matches is the one shape the substitute may fire on"
- );
-
- let foreign = NotificationInfo {
- index: 1,
- app_name: target.app_name.clone(),
- title: format!("{} (not the staged entry)", target.title),
- body: None,
- actions: Vec::new(),
- };
- assert!(
- !clear_all_still_the_sole_target(held.hwnd(), &foreign, deadline(20_000))
- .expect("the re-verify read"),
- "an identity the sole entry does not carry must abort the substitute"
- );
-
- let _staged_b = StagedToast::stage_with(TOAST_TITLE_SECOND, TOAST_BODY_SECOND);
- let listed = toast_support::wait_until_count_held(held.hwnd(), 2, deadline(30_000));
- assert_eq!(
- listed.len(),
- 2,
- "the second staged toast is the only other entry"
- );
- assert!(
- !clear_all_still_the_sole_target(held.hwnd(), &target, deadline(20_000))
- .expect("the re-verify read"),
- "an entry arriving after the settle read must abort the substitute - the \
- two-entry-appears case the substitute must never widen into"
- );
- held.close().expect("the held session restores the surface");
-}
diff --git a/crates/windows/src/notifications/actions_live_tests.rs b/crates/windows/src/notifications/actions_live_tests.rs
deleted file mode 100644
index 498fa60ed..000000000
--- a/crates/windows/src/notifications/actions_live_tests.rs
+++ /dev/null
@@ -1,357 +0,0 @@
-use agent_desktop_core::{
- DeliverySemantics, DismissNotificationRequest, ErrorCode, InteractionLease, InteractionPolicy,
- NotificationFilter, NotificationIdentity, NotificationInfo, SnapshotSurface, SystemOps,
-};
-
-use super::{dismiss_notification, notification_action};
-use crate::adapter::WindowsAdapter;
-use crate::notifications::list::list_entries;
-use crate::notifications::session::ActionCenterSession;
-use crate::notifications::toast_support::{
- self, StagedToast, TOAST_BODY, TOAST_BODY_SECOND, TOAST_TITLE, TOAST_TITLE_SECOND,
-};
-use crate::system::fixture::test_support::{
- SHELL_SURFACE_LOCK, or_skip_shell, wait_for_foreground_to_settle,
-};
-use crate::system::shell::raise_oracle::{responded_since, witness_desktop};
-use crate::system::shell::shell_surface::resolve_surface;
-use crate::system::shell::shell_surface_open::close_surface;
-
-use crate::system::fixture::test_time::{deadline, headed};
-
-fn foreground() -> isize {
- use windows_sys::Win32::UI::WindowsAndMessaging::GetForegroundWindow;
- (unsafe { GetForegroundWindow() }) as isize
-}
-
-fn center_open() -> bool {
- resolve_surface(SnapshotSurface::ActionCenter, deadline(10_000))
- .expect("the desktop is readable")
- .is_some()
-}
-
-fn identity_of(info: &NotificationInfo) -> NotificationIdentity {
- NotificationIdentity {
- expected_app: Some(info.app_name.clone()),
- expected_title: Some(info.title.clone()),
- }
-}
-
-fn listed_infos(hwnd: isize) -> Vec<NotificationInfo> {
- list_entries(&NotificationFilter::default(), hwnd, deadline(20_000))
- .expect("the listing reads")
- .into_iter()
- .map(|entry| entry.info)
- .collect()
-}
-
-/// Resets the center, opens it and holds it open, stages one synthetic toast
-/// into the open center, and waits until the listing observes it.
-///
-/// The center stays open for the whole body because the measured staging
-/// behaviour on this host is that a toast joins the center only while the
-/// center is open and is evicted by its next close. The staging guard and the
-/// held session both travel back to the caller, so the sweep and the close run
-/// when the test body exits - held session first, then the toast sweep. The
-/// mutations under test adopt the already-open center without raising it, and
-/// their restore-on-exit leaves it open for the caller's follow-up reads.
-///
-/// A desktop whose shell declines the open, or whose staging never produces
-/// an entry, skips loudly instead: the helper prints why and returns None.
-fn stage_exactly_one_toast_into_held_center()
--> Option<(ActionCenterSession, StagedToast, NotificationInfo)> {
- toast_support::clear_center(deadline(20_000));
- let witness = witness_desktop();
- let held = or_skip_shell(
- "action center open for toast staging",
- ActionCenterSession::open(headed(), deadline(15_000)),
- || responded_since(&witness),
- )?;
- let staged = StagedToast::stage();
- let Some(listed) = toast_support::wait_until_listed_held(held.hwnd(), deadline(30_000)) else {
- eprintln!("skip toast staging: this desktop's toast staging produced no entry");
- return None;
- };
- assert_eq!(
- listed.len(),
- 1,
- "the staged toast is the only entry after the reset"
- );
- let entry = listed.into_iter().next().expect("one entry");
- Some((held, staged, entry))
-}
-
-#[test]
-fn every_notification_info_field_is_populated_as_macos_populates_it() {
- crate::tree::fixture::bootstrap();
- let _lock = SHELL_SURFACE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let Some((held, _staged, staged)) = stage_exactly_one_toast_into_held_center() else {
- return;
- };
-
- assert_eq!(
- staged.index, 1,
- "a lone entry carries the 1-based index the contract gives every entry"
- );
- assert_eq!(staged.title, TOAST_TITLE);
- assert_eq!(
- staged.body.as_deref(),
- Some(TOAST_BODY),
- "the body the toast carried is the body the listing reports"
- );
- assert!(
- !staged.app_name.is_empty(),
- "app_name is filled the way macOS fills it, from the entry's source attribution"
- );
-
- let json = serde_json::to_value(vec![staged.clone()]).expect("the listing serializes");
- let entry = json
- .as_array()
- .and_then(|entries| entries.first())
- .expect("the JSON carries the entry")
- .clone();
- assert!(entry["index"].is_u64());
- assert!(entry["app_name"].is_string() && entry["app_name"] != "");
- assert!(entry["title"].is_string());
- assert_eq!(entry["body"], TOAST_BODY);
- let actions_absent = entry.get("actions").is_none();
- let round_trip: Vec<NotificationInfo> =
- serde_json::from_value(json).expect("the JSON deserializes into NotificationInfo");
- assert_eq!(round_trip[0].index, staged.index);
- assert_eq!(round_trip[0].app_name, staged.app_name);
- assert_eq!(round_trip[0].title, staged.title);
- assert_eq!(round_trip[0].body, staged.body);
- assert_eq!(
- actions_absent,
- staged.actions.is_empty(),
- "empty actions serialize as absent, which is the macOS shape"
- );
- held.close().expect("the held session restores the surface");
-}
-
-#[test]
-fn a_mismatched_identity_is_refused_and_the_entry_survives() {
- crate::tree::fixture::bootstrap();
- let _lock = SHELL_SURFACE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let Some((held, _staged, staged)) = stage_exactly_one_toast_into_held_center() else {
- return;
- };
- let wrong_identity = NotificationIdentity {
- expected_app: None,
- expected_title: Some("a title no staged entry carries".into()),
- };
-
- let error = dismiss_notification(
- staged.index,
- None,
- Some(&wrong_identity),
- headed(),
- deadline(30_000),
- )
- .expect_err("the surface reordered under the caller, so the index is not the identity");
-
- assert_eq!(error.code, ErrorCode::NotificationNotFound);
- assert!(
- !error.message.contains(TOAST_TITLE),
- "the mismatch message is built from the index alone and never names the entry"
- );
- let remaining = listed_infos(held.hwnd());
- assert!(
- remaining.iter().any(|info| info.title == staged.title),
- "the entry the identity refused must survive untouched"
- );
- held.close().expect("the held session restores the surface");
-}
-
-#[test]
-fn an_unknown_action_name_is_refused_and_leaves_the_entry_unchanged() {
- crate::tree::fixture::bootstrap();
- let _lock = SHELL_SURFACE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let Some((held, _staged, staged)) = stage_exactly_one_toast_into_held_center() else {
- return;
- };
- let identity = identity_of(&staged);
- let action_name = "agent-desktop-no-such-action";
-
- let error = notification_action(
- staged.index,
- Some(&identity),
- action_name,
- headed(),
- deadline(30_000),
- )
- .expect_err("a notification offering no such button is refused");
-
- assert_eq!(error.code, ErrorCode::ActionNotSupported);
- assert!(
- error.message.contains(action_name),
- "the refusal names the caller-supplied action name"
- );
- let remaining = listed_infos(held.hwnd());
- assert!(
- remaining.iter().any(|info| info.title == staged.title),
- "nothing was invoked, so the entry is unchanged"
- );
- held.close().expect("the held session restores the surface");
-}
-
-#[test]
-fn a_dismiss_removes_exactly_the_identified_entry() {
- crate::tree::fixture::bootstrap();
- let _lock = SHELL_SURFACE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let Some((held, _staged, staged)) = stage_exactly_one_toast_into_held_center() else {
- return;
- };
- let identity = identity_of(&staged);
-
- let dismissed = dismiss_notification(
- staged.index,
- None,
- Some(&identity),
- headed(),
- deadline(30_000),
- )
- .expect("the identified entry dismisses and the removal verifies");
-
- assert_eq!(dismissed.title, staged.title);
- assert_eq!(dismissed.app_name, staged.app_name);
- let remaining = listed_infos(held.hwnd());
- assert!(
- remaining.iter().all(|info| info.title != staged.title),
- "the re-read proves the identified entry is gone"
- );
- held.close().expect("the held session restores the surface");
-}
-
-#[test]
-fn an_accepted_dismiss_invoke_that_the_shell_ignores_is_action_failed_and_both_entries_survive() {
- crate::tree::fixture::bootstrap();
- let _lock = SHELL_SURFACE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let Some((held, _staged_a, staged)) = stage_exactly_one_toast_into_held_center() else {
- return;
- };
- let _staged_b = StagedToast::stage_with(TOAST_TITLE_SECOND, TOAST_BODY_SECOND);
- let listed = toast_support::wait_until_count_held(held.hwnd(), 2, deadline(30_000));
- assert_eq!(
- listed.len(),
- 2,
- "the second staged toast is the only other entry"
- );
- let second = listed
- .iter()
- .find(|info| info.title == TOAST_TITLE_SECOND)
- .expect("the second toast is listed")
- .clone();
- let identity = identity_of(&second);
-
- let error = dismiss_notification(
- second.index,
- None,
- Some(&identity),
- headed(),
- deadline(30_000),
- )
- .expect_err("the shell accepts the dismiss invoke and ignores it, and with another entry present the clear-all control is no substitute");
-
- assert_eq!(error.code, ErrorCode::ActionFailed);
- assert_eq!(error.disposition, DeliverySemantics::delivered_unverified());
- let remaining = listed_infos(held.hwnd());
- assert_eq!(remaining.len(), 2, "nothing was removed");
- assert!(remaining.iter().any(|info| info.title == staged.title));
- assert!(remaining.iter().any(|info| info.title == second.title));
- held.close().expect("the held session restores the surface");
-}
-
-#[test]
-fn a_strict_headless_list_is_refused_and_the_center_is_not_opened() {
- crate::tree::fixture::bootstrap();
- let _lock = SHELL_SURFACE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let _cleanup = toast_support::CloseCenterOnDrop;
- let _ = close_surface(SnapshotSurface::ActionCenter, deadline(8_000));
- assert!(
- wait_for_foreground_to_settle(),
- "the desktop's foreground must settle before the refusal is staged"
- );
- let before = foreground();
-
- let adapter = WindowsAdapter::new();
- let error = SystemOps::list_notifications(
- &adapter,
- &NotificationFilter::default(),
- InteractionPolicy::headless(),
- deadline(10_000),
- None,
- )
- .expect_err("a strict-headless caller is refused");
-
- assert_eq!(error.code, ErrorCode::PolicyDenied);
- assert_eq!(
- foreground(),
- before,
- "a refusal that moved the foreground is not a refusal"
- );
- assert!(
- !center_open(),
- "the refused listing must not have raised the center"
- );
-}
-
-#[test]
-fn the_dismiss_reaches_the_windows_override_not_the_trait_default() {
- let adapter = WindowsAdapter::new();
- let lease = InteractionLease::guarded(deadline(5_000), ()).expect("lease");
- let identity = NotificationIdentity::default();
-
- let error = SystemOps::dismiss_notification(
- &adapter,
- DismissNotificationRequest {
- index: 1,
- app_filter: None,
- identity: &identity,
- policy: InteractionPolicy::headless(),
- },
- &lease,
- )
- .expect_err("the headless floor refuses before anything is raised");
-
- assert_eq!(
- error.code,
- ErrorCode::PolicyDenied,
- "the trait default would answer PLATFORM_NOT_SUPPORTED instead"
- );
-}
-
-#[test]
-fn a_headed_list_through_the_trait_adopts_the_open_center_without_closing_it() {
- crate::tree::fixture::bootstrap();
- let _lock = SHELL_SURFACE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- toast_support::clear_center(deadline(20_000));
- let witness = witness_desktop();
- let Some(held) = or_skip_shell(
- "action center open for the pre-arrangement",
- ActionCenterSession::open(headed(), deadline(15_000)),
- || responded_since(&witness),
- ) else {
- return;
- };
- let adapter = WindowsAdapter::new();
-
- let listed = SystemOps::list_notifications(
- &adapter,
- &NotificationFilter::default(),
- headed(),
- deadline(20_000),
- Some(&InteractionLease::guarded(deadline(5_000), ()).expect("lease")),
- )
- .expect("a headed observation carries its lease and adopts the open center");
-
- assert!(
- listed.is_empty(),
- "the center was reset; a leak is a staging bug"
- );
- assert!(
- center_open(),
- "the listing's session must restore the state it found: the center was open on entry and stays open"
- );
- held.close().expect("the held session restores the surface");
-}
diff --git a/crates/windows/src/notifications/actions_tests.rs b/crates/windows/src/notifications/actions_tests.rs
index b5ad2c0f5..bb9d5c446 100644
--- a/crates/windows/src/notifications/actions_tests.rs
+++ b/crates/windows/src/notifications/actions_tests.rs
@@ -1,6 +1,9 @@
use agent_desktop_core::{ErrorCode, InteractionPolicy, NotificationIdentity, NotificationInfo};
-use super::{dismiss_all_failures, require_foreground_policy, verify_notification_identity};
+use super::{
+ dismiss_all_failures, is_sole_target, require_foreground_policy, unknown_action_error,
+ verify_notification_identity,
+};
fn info(app: &str, title: &str) -> NotificationInfo {
NotificationInfo {
@@ -150,3 +153,54 @@ fn an_invoke_error_recorded_for_an_entry_that_still_left_is_never_reported() {
assert!(!failures[0].contains("transient invoke error"));
assert!(failures[0].contains("#2"));
}
+
+#[test]
+fn the_clear_all_substitute_fires_only_on_exactly_one_matching_entry() {
+ let target = info("Toaster", "Build finished");
+ let foreign = info("Toaster", "Build finished (not the staged entry)");
+
+ assert!(is_sole_target(&target, std::slice::from_ref(&target)));
+ assert!(!is_sole_target(&target, std::slice::from_ref(&foreign)));
+ assert!(!is_sole_target(&target, &[]));
+ assert!(!is_sole_target(&target, &[target.clone(), foreign]));
+}
+
+#[test]
+fn an_unknown_action_name_is_refused_naming_it_and_nothing_was_delivered() {
+ let error = unknown_action_error("agent-desktop-no-such-action", 3);
+
+ assert_eq!(error.code, ErrorCode::ActionNotSupported);
+ assert!(error.message.contains("agent-desktop-no-such-action"));
+ assert_eq!(
+ error.disposition,
+ agent_desktop_core::DeliverySemantics::not_delivered()
+ );
+}
+
+#[test]
+fn the_dismiss_reaches_the_windows_override_not_the_trait_default() {
+ use agent_desktop_core::{Deadline, DismissNotificationRequest, InteractionLease, SystemOps};
+
+ let adapter = crate::adapter::WindowsAdapter::new();
+ let lease = InteractionLease::guarded(Deadline::detached_after(5_000).expect("deadline"), ())
+ .expect("lease");
+ let identity = NotificationIdentity::default();
+
+ let error = SystemOps::dismiss_notification(
+ &adapter,
+ DismissNotificationRequest {
+ index: 1,
+ app_filter: None,
+ identity: &identity,
+ policy: InteractionPolicy::headless(),
+ },
+ &lease,
+ )
+ .expect_err("the headless floor refuses before anything is raised");
+
+ assert_eq!(
+ error.code,
+ ErrorCode::PolicyDenied,
+ "the trait default would answer PLATFORM_NOT_SUPPORTED instead"
+ );
+}
diff --git a/crates/windows/src/notifications/mod.rs b/crates/windows/src/notifications/mod.rs
index 7ae57bd9d..936a0788d 100644
--- a/crates/windows/src/notifications/mod.rs
+++ b/crates/windows/src/notifications/mod.rs
@@ -3,10 +3,3 @@ pub(crate) mod list;
mod read;
mod session;
mod verify;
-
-#[cfg(all(test, target_os = "windows"))]
-mod toast_support;
-
-#[cfg(all(test, target_os = "windows"))]
-#[path = "wait_tests.rs"]
-mod wait_tests;
diff --git a/crates/windows/src/notifications/read_tests.rs b/crates/windows/src/notifications/read_tests.rs
index 715191b44..f2c440370 100644
--- a/crates/windows/src/notifications/read_tests.rs
+++ b/crates/windows/src/notifications/read_tests.rs
@@ -132,114 +132,6 @@ mod classification {
}
}
-#[cfg(target_os = "windows")]
-mod live {
- use super::super::{find_by_id, read_entries};
- use crate::notifications::session::ActionCenterSession;
- use crate::notifications::toast_support;
- use crate::system::fixture::test_support::{SHELL_SURFACE_LOCK, or_skip_shell};
- use crate::system::fixture::test_time::{deadline, headed};
- use crate::system::shell::raise_oracle::{responded_since, witness_desktop};
- use crate::system::shell::shell_surface_kinds::{EMPTY_CENTER_LANDMARKS, MAIN_LIST_VIEW};
- use crate::tree::element::UIAElement;
-
- /// Counts the list's items with an independent query - a control-type
- /// condition over the whole subtree - so the count the reader returns is
- /// asserted against the tree rather than against the reader's own walk.
- fn independent_list_item_count(root: &UIAElement) -> Option<usize> {
- use uiautomation::types::{ControlType, TreeScope, UIProperty};
- use uiautomation::variants::Variant;
-
- let client = crate::tree::automation::automation_client().ok()?;
- let list = match find_by_id(root, TreeScope::Descendants, MAIN_LIST_VIEW) {
- Ok(Some(list)) => list,
- Ok(None) => {
- let empty = EMPTY_CENTER_LANDMARKS.iter().any(|landmark| {
- find_by_id(root, TreeScope::Descendants, landmark)
- .ok()
- .flatten()
- .is_some()
- });
- return empty.then_some(0);
- }
- Err(_) => return None,
- };
- let condition = client
- .create_property_condition(
- UIProperty::ControlType,
- Variant::from(ControlType::ListItem as i32),
- None,
- )
- .ok()?;
- let items = list.0.find_all(TreeScope::Descendants, &condition).ok()?;
- Some(items.len())
- }
-
- #[test]
- fn the_reader_s_count_matches_the_tree_s_own_list_item_count() {
- crate::tree::fixture::bootstrap();
- let _lock = SHELL_SURFACE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- toast_support::clear_center(deadline(20_000));
- let witness = witness_desktop();
- let Some(session) = or_skip_shell(
- "action center open for the reader count check",
- ActionCenterSession::open(headed(), deadline(15_000)),
- || responded_since(&witness),
- ) else {
- return;
- };
- let _staged = toast_support::StagedToast::stage();
- let Some(listed) = toast_support::wait_until_listed_held(session.hwnd(), deadline(30_000))
- else {
- eprintln!("skip toast staging: this desktop's toast staging produced no entry");
- return;
- };
- assert_eq!(
- listed.len(),
- 1,
- "the staged toast is the only entry after the reset"
- );
-
- let root = crate::tree::automation::root_from_hwnd(session.hwnd(), deadline(10_000))
- .expect("the open center roots");
- let tree_count = independent_list_item_count(&root).expect("the center's tree is readable");
- let read = read_entries(&root, deadline(20_000)).expect("the recognized tree reads");
- session.close().expect("the session restores the surface");
-
- assert_eq!(
- read.len(),
- tree_count,
- "the reader must see exactly the entries the tree carries - a walk bug that drops entries fails here"
- );
- }
-
- #[test]
- fn an_empty_center_is_a_zero_entry_answer_not_a_refusal() {
- crate::tree::fixture::bootstrap();
- let _lock = SHELL_SURFACE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- toast_support::clear_center(deadline(20_000));
- let witness = witness_desktop();
- let Some(session) = or_skip_shell(
- "action center open for the empty-center read",
- ActionCenterSession::open(headed(), deadline(15_000)),
- || responded_since(&witness),
- ) else {
- return;
- };
- let root = crate::tree::automation::root_from_hwnd(session.hwnd(), deadline(10_000))
- .expect("the open center roots");
- let entries = read_entries(&root, deadline(20_000)).expect(
- "an empty center is a legitimate zero-entry answer, never the landmark refusal",
- );
- session.close().expect("the session restores the surface");
-
- assert!(
- entries.is_empty(),
- "the center was reset before this test; any entry here is a staging leak"
- );
- }
-}
-
/// Uses the crate's own hosted fixture window - never the shell's Action
/// Center - so this case stays deterministic.
///
diff --git a/crates/windows/src/notifications/session_tests.rs b/crates/windows/src/notifications/session_tests.rs
index e6a912187..2a3740cfb 100644
--- a/crates/windows/src/notifications/session_tests.rs
+++ b/crates/windows/src/notifications/session_tests.rs
@@ -40,67 +40,3 @@ fn a_clean_cleanup_passes_the_operation_through() {
assert_eq!(value, 41);
}
-
-#[cfg(target_os = "windows")]
-mod live {
- use agent_desktop_core::SnapshotSurface;
-
- use crate::notifications::list::list_notifications;
- use crate::system::fixture::test_support::{SHELL_SURFACE_LOCK, or_skip_shell};
- use crate::system::shell::raise_oracle::{responded_since, witness_desktop};
- use crate::system::shell::shell_surface::resolve_surface;
- use crate::system::shell::shell_surface_open::{close_surface, open_surface};
-
- use crate::system::fixture::test_time::{deadline, headed};
-
- fn center_is_open() -> bool {
- resolve_surface(SnapshotSurface::ActionCenter, deadline(10_000))
- .expect("the desktop is readable")
- .is_some()
- }
-
- #[test]
- fn a_session_on_an_already_open_center_leaves_it_open() {
- crate::tree::fixture::bootstrap();
- let _lock = SHELL_SURFACE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let _ = close_surface(SnapshotSurface::ActionCenter, deadline(8_000));
- let witness = witness_desktop();
- let Some(_surface) = or_skip_shell(
- "action center open for the pre-arrangement",
- open_surface(SnapshotSurface::ActionCenter, headed(), deadline(15_000)),
- || responded_since(&witness),
- ) else {
- return;
- };
-
- let listed = list_notifications(&Default::default(), headed(), deadline(20_000))
- .expect("an already-present center needs no raise, so the listing proceeds");
-
- assert!(
- center_is_open(),
- "the session must restore the state it found: an open center stays open"
- );
- let _ = listed;
- let _ = close_surface(SnapshotSurface::ActionCenter, deadline(8_000));
- }
-
- #[test]
- fn a_session_on_a_closed_center_leaves_it_closed() {
- crate::tree::fixture::bootstrap();
- let _lock = SHELL_SURFACE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let _ = close_surface(SnapshotSurface::ActionCenter, deadline(8_000));
- let witness = witness_desktop();
- let Some(_listed) = or_skip_shell(
- "the closed-then-raised center's listing",
- list_notifications(&Default::default(), headed(), deadline(20_000)),
- || responded_since(&witness),
- ) else {
- return;
- };
-
- assert!(
- !center_is_open(),
- "the session must restore the state it found: a closed center ends closed"
- );
- }
-}
diff --git a/crates/windows/src/notifications/toast_support.rs b/crates/windows/src/notifications/toast_support.rs
deleted file mode 100644
index 454ade6e8..000000000
--- a/crates/windows/src/notifications/toast_support.rs
+++ /dev/null
@@ -1,265 +0,0 @@
-//! Test-only support for the live Action Center scenarios: stages one
-//! synthetic toast under the Windows PowerShell AUMID - the exact staging the
-//! notification-shape probe measured working on this host (A26-3), carrying
-//! only the synthetic literals this suite owns - and sweeps the center clean
-//! on every exit path.
-//!
-//! The sweep dismisses everything the center carries, which is the probe's own
-//! cleanup protocol on this box: the center is machine-global test state and
-//! this suite holds the shell lock for its whole body, so a clean slate at
-//! every test boundary is what keeps the state assertions deterministic.
-
-use std::time::Duration;
-
-use agent_desktop_core::{
- Deadline, InteractionPolicy, NotificationFilter, NotificationInfo, SnapshotSurface,
-};
-
-use crate::notifications::actions;
-use crate::notifications::list::list_infos;
-use crate::system::shell::shell_surface_kinds::MAIN_LIST_VIEW;
-use crate::system::shell::shell_surface_open::close_surface;
-
-pub(crate) const TOAST_TITLE: &str = "agent-desktop-probe-notification";
-pub(crate) const TOAST_BODY: &str = "agent-desktop-probe-notification-body";
-pub(crate) const TOAST_TITLE_SECOND: &str = "agent-desktop-probe-notification-2";
-pub(crate) const TOAST_BODY_SECOND: &str = "agent-desktop-probe-notification-body-2";
-
-const TOAST_AUMID: &str =
- "{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\\WindowsPowerShell\\v1.0\\powershell.exe";
-const POLL_INTERVAL: Duration = Duration::from_millis(500);
-
-/// How long the reader is given to catch up to a toast the independent walk
-/// already sees, before the gap is judged a reader regression.
-const READER_SETTLE_MS: u64 = 3_000;
-
-fn stage_toast(title: &str, body: &str) -> Result<(), String> {
- let script = format!(
- "[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null; \
- [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null; \
- $xml = New-Object Windows.Data.Xml.Dom.XmlDocument; \
- $xml.LoadXml('<toast><visual><binding template=\"ToastGeneric\"><text>{title}</text><text>{body}</text></binding></visual></toast>'); \
- $toast = New-Object Windows.UI.Notifications.ToastNotification($xml); \
- $notifier = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('{TOAST_AUMID}'); \
- $notifier.Show($toast)"
- );
- let output = std::process::Command::new("powershell")
- .args([
- "-NoProfile",
- "-NonInteractive",
- "-ExecutionPolicy",
- "Bypass",
- "-Command",
- &script,
- ])
- .output()
- .map_err(|error| format!("powershell could not be started: {error}"))?;
- if output.status.success() {
- Ok(())
- } else {
- Err(format!(
- "the shell refused the staged toast: {}",
- String::from_utf8_lossy(&output.stderr).trim()
- ))
- }
-}
-
-/// Stages one synthetic toast and sweeps the center clean when dropped, on
-/// every path out of the test body.
-pub(crate) struct StagedToast;
-
-impl StagedToast {
- pub(crate) fn stage() -> Self {
- Self::stage_with(TOAST_TITLE, TOAST_BODY)
- }
-
- pub(crate) fn stage_with(title: &str, body: &str) -> Self {
- if let Err(error) = stage_toast(title, body) {
- panic!("the synthetic toast could not be staged: {error}");
- }
- Self
- }
-}
-
-impl Drop for StagedToast {
- fn drop(&mut self) {
- clear_center(Deadline::detached_after(8_000).expect("cleanup deadline"));
- }
-}
-
-/// Dismisses whatever the center carries, best effort - a cleanup that cannot
-/// report must not fail a test whose assertions already ran.
-pub(crate) fn clear_center(deadline: Deadline) {
- let _ = actions::dismiss_all(None, InteractionPolicy::headed(), deadline);
-}
-
-/// Closes the Action Center when dropped, for tests that arrange the surface's
-/// state themselves and must not leak it to the next test on a failure path.
-pub(crate) struct CloseCenterOnDrop;
-
-impl Drop for CloseCenterOnDrop {
- fn drop(&mut self) {
- let _ = close_surface(
- SnapshotSurface::ActionCenter,
- Deadline::detached_after(8_000).expect("cleanup deadline"),
- );
- }
-}
-
-/// Polls the listing until the staged toast is observable in the center and
-/// returns the listing that carried it, or `None` when the budget expires
-/// without the toast ever appearing - a desktop whose staging the shell never
-/// lands, which the caller classifies as a declined precondition instead of
-/// this wait asserting on. A toast lands in the center a short, variable time
-/// after the shell accepts it, so the wait is on the value itself rather than
-/// on a fixed sleep.
-///
-/// The wait is judged by two observers. The product reader answers the
-/// caller's question - the listing that carried the toast; the independent
-/// walk ([`independent_walk_sees_toast`]) answers whether the held center
-/// carries the toast at all, read straight off the tree. When the walk sees
-/// the toast and the reader still does not report it across a short bounded
-/// re-poll, the reader is regressed and this panics: a reader regression
-/// must fail a test, never expire into a loud skip.
-///
-/// This variant polls inside a center the caller holds open, because the
-/// measured staging behaviour on this host is that a toast joins the center
-/// only while the center is open and leaves it at the next close: a poll that
-/// closed and reopened the center would evict the very entry it waits for.
-pub(crate) fn wait_until_listed_held(
- hwnd: isize,
- deadline: Deadline,
-) -> Option<Vec<NotificationInfo>> {
- let filter = NotificationFilter::default();
- loop {
- if let Some(listed) = listing_contains_toast(&filter, hwnd, deadline) {
- return Some(listed);
- }
- if independent_walk_sees_toast(hwnd, deadline) {
- if let Some(listed) = product_reader_catches_up(hwnd) {
- return Some(listed);
- }
- panic!(
- "the product reader misses an entry the independent walk observes: the \
- held center carries the staged toast but the listing never reports it"
- );
- }
- if deadline.is_expired() {
- return None;
- }
- std::thread::sleep(POLL_INTERVAL);
- }
-}
-
-/// A short bounded re-poll of the product reader alone. The independent walk
-/// has already seen the staged toast, so the only question left is whether
-/// the reader catches up to the tree inside this window - the toast may have
-/// landed between the reader's last poll and the walk - or is proven to miss
-/// an entry the desktop carries. Its budget is detached from the caller's:
-/// the reader's honesty is not the wait's remaining latency.
-fn product_reader_catches_up(hwnd: isize) -> Option<Vec<NotificationInfo>> {
- let filter = NotificationFilter::default();
- let deadline = Deadline::detached_after(READER_SETTLE_MS).expect("re-poll deadline");
- loop {
- if let Some(listed) = listing_contains_toast(&filter, hwnd, deadline) {
- return Some(listed);
- }
- if deadline.is_expired() {
- return None;
- }
- std::thread::sleep(POLL_INTERVAL);
- }
-}
-
-/// One listing attempt, answering whether the staged toast is in it right
-/// now. Both polling loops above share this single-attempt read; only what
-/// they do between attempts differs.
-fn listing_contains_toast(
- filter: &NotificationFilter,
- hwnd: isize,
- deadline: Deadline,
-) -> Option<Vec<NotificationInfo>> {
- let listed = list_infos(filter, hwnd, deadline).ok()?;
- listed
- .iter()
- .any(|info| info.title == TOAST_TITLE)
- .then_some(listed)
-}
-
-/// The independent observation the staging wait is judged against: a raw UIA
-/// walk of the held center's hwnd that locates the notification list by its
-/// measured `MainListView` structure, enumerates its `ListItem` descendants
-/// by control type, and matches the staged toast by a descendant's raw
-/// `Name` - the title is the fixed synthetic literal this suite owns, so an
-/// exact match is safe in tests. Nothing is read through the product reader,
-/// so a reader regression cannot hide behind the oracle that watches it.
-///
-/// Every read failure reads as "not seen": the oracle speaks only when the
-/// tree it can actually observe carries the toast, never from a search that
-/// could not run.
-fn independent_walk_sees_toast(hwnd: isize, deadline: Deadline) -> bool {
- use uiautomation::types::{ControlType, TreeScope, UIProperty};
- use uiautomation::variants::Variant;
-
- let Ok(root) = crate::tree::automation::root_from_hwnd(hwnd, deadline) else {
- return false;
- };
- let Ok(client) = crate::tree::automation::automation_client() else {
- return false;
- };
- let list_condition = match client.create_property_condition(
- UIProperty::AutomationId,
- Variant::from(MAIN_LIST_VIEW),
- None,
- ) {
- Ok(condition) => condition,
- Err(_) => return false,
- };
- let Ok(list) = root.0.find_first(TreeScope::Descendants, &list_condition) else {
- return false;
- };
- let items_condition = match client.create_property_condition(
- UIProperty::ControlType,
- Variant::from(ControlType::ListItem as i32),
- None,
- ) {
- Ok(condition) => condition,
- Err(_) => return false,
- };
- let Ok(items) = list.find_all(TreeScope::Descendants, &items_condition) else {
- return false;
- };
- let title_condition = match client.create_property_condition(
- UIProperty::Name,
- Variant::from(TOAST_TITLE),
- None,
- ) {
- Ok(condition) => condition,
- Err(_) => return false,
- };
- items.iter().any(|item| {
- item.find_first(TreeScope::Descendants, &title_condition)
- .is_ok()
- })
-}
-
-/// The same wait, until the held center carries `count` entries.
-pub(crate) fn wait_until_count_held(
- hwnd: isize,
- count: usize,
- deadline: Deadline,
-) -> Vec<NotificationInfo> {
- let filter = NotificationFilter::default();
- loop {
- match list_infos(&filter, hwnd, deadline) {
- Ok(listed) if listed.len() >= count => return listed,
- Ok(_) => {}
- Err(_) => {}
- }
- assert!(
- !deadline.is_expired(),
- "the center never carried {count} entries"
- );
- std::thread::sleep(POLL_INTERVAL);
- }
-}
diff --git a/crates/windows/src/notifications/wait_tests.rs b/crates/windows/src/notifications/wait_tests.rs
deleted file mode 100644
index c7efa3a4b..000000000
--- a/crates/windows/src/notifications/wait_tests.rs
+++ /dev/null
@@ -1,235 +0,0 @@
-//! Live proof that `wait --notification` works on Windows through the
-//! existing core loop.
-//!
-//! The loop under test lives in `agent_desktop_core::commands::wait`: it
-//! polls the adapter's listing and diffs a fingerprint multiset against a
-//! baseline captured on its own first poll. These tests stage the world that
-//! loop observes and drive it through the same `execute` entry the CLI calls,
-//! so every scenario runs against the real Action Center and the real
-//! Windows listing path - no scenario sleeps past a poll it could have
-//! observed instead.
-//!
-//! The arrival scenario holds the center open for the whole wait because the
-//! measured staging behaviour on this host is that a toast joins the center
-//! only while the center is open and any close evicts the entry (A26-3). The
-//! wait's per-poll sessions adopt an already-present center without closing
-//! it, which is exactly what lets a staged arrival survive the polls; a
-//! center the wait raised itself would be closed between polls and would
-//! evict the entry the wait is for.
-//!
-//! Every leg holds `FIXTURE_APP_NAME_LOCK` before `SHELL_SURFACE_LOCK`, the
-//! crate-wide ordering: the legs raise shell chrome and read the settled
-//! foreground, so the two families whose holders stage the desktop under a
-//! live test must serialize against this one too.
-
-use std::time::{Duration, Instant};
-
-use agent_desktop_core::{
- AppError, CommandContext, ErrorCode, SnapshotSurface, commands::wait,
- commands::wait_surface::SurfaceWait,
-};
-
-use super::session::ActionCenterSession;
-use crate::adapter::WindowsAdapter;
-use crate::notifications::toast_support::{
- self, CloseCenterOnDrop, StagedToast, TOAST_BODY_SECOND, TOAST_TITLE_SECOND,
-};
-use crate::system::fixture::test_support::{
- FIXTURE_APP_NAME_LOCK, SHELL_SURFACE_LOCK, or_skip_shell, wait_for_foreground_to_settle,
- with_interaction_lease_test_lock,
-};
-use crate::system::shell::raise_oracle::{responded_since, witness_desktop};
-use crate::system::shell::shell_surface::resolve_surface;
-use crate::system::shell::shell_surface_open::close_surface;
-
-use crate::system::fixture::test_time::{deadline, headed};
-
-fn center_open() -> bool {
- resolve_surface(SnapshotSurface::ActionCenter, deadline(10_000))
- .expect("the desktop is readable")
- .is_some()
-}
-
-fn notification_wait_args(timeout_ms: u64) -> wait::WaitArgs {
- wait::WaitArgs {
- mode: wait::WaitModeArgs {
- surface: Some(SurfaceWait::Notification),
- ..Default::default()
- },
- predicate: wait::WaitPredicateArgs {
- predicate: None,
- value: None,
- action: None,
- count: None,
- },
- timeout_ms,
- app: None,
- }
-}
-
-/// Resets the center, opens it, and holds it open so the staged baseline
-/// entry and the staged arrival both land in a center the wait's sessions
-/// adopt instead of close. A desktop whose shell declines the open, or whose
-/// staging never produces an entry, skips loudly instead: the helper prints
-/// why and returns None.
-fn hold_center_with_baseline_toast() -> Option<(ActionCenterSession, StagedToast)> {
- toast_support::clear_center(deadline(20_000));
- let witness = witness_desktop();
- let held = or_skip_shell(
- "action center open for the wait baseline",
- ActionCenterSession::open(headed(), deadline(15_000)),
- || responded_since(&witness),
- )?;
- let staged = StagedToast::stage();
- let Some(listed) = toast_support::wait_until_listed_held(held.hwnd(), deadline(30_000)) else {
- eprintln!("skip toast staging: this desktop's toast staging produced no entry");
- return None;
- };
- assert_eq!(
- listed.len(),
- 1,
- "the reset leaves the staged toast as the only entry the baseline can capture"
- );
- Some((held, staged))
-}
-
-#[test]
-fn a_wait_returns_the_notification_that_arrives_during_it_and_not_one_already_present() {
- crate::tree::fixture::bootstrap();
- let _fixture_scope = FIXTURE_APP_NAME_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let _lock = SHELL_SURFACE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let Some((held, _already_present)) = hold_center_with_baseline_toast() else {
- return;
- };
-
- let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
- let stager = std::thread::spawn(move || {
- std::thread::sleep(Duration::from_millis(2_000));
- let _staged = StagedToast::stage_with(TOAST_TITLE_SECOND, TOAST_BODY_SECOND);
- let _ = release_rx.recv();
- });
-
- let started = Instant::now();
- let matched = with_interaction_lease_test_lock(|| {
- wait::execute(
- notification_wait_args(20_000),
- &WindowsAdapter::new(),
- &CommandContext::default().with_headed(true),
- )
- .expect("the wait returns when the staged toast arrives")
- });
- let elapsed = started.elapsed();
-
- assert_eq!(matched["condition"], "notification");
- assert_eq!(matched["matched"], true);
- assert_eq!(
- matched["notification"]["title"], TOAST_TITLE_SECOND,
- "the wait reports the arrival, never an entry the baseline already carried"
- );
- assert_eq!(matched["notification"]["body"], TOAST_BODY_SECOND);
- assert!(
- elapsed >= Duration::from_millis(2_000),
- "the match is the arrival during the wait, not the baseline: took {elapsed:?}"
- );
-
- let _ = release_tx.send(());
- stager.join().expect("the staging thread finishes");
- held.close().expect("the held session restores the surface");
-}
-
-#[test]
-fn a_wait_that_times_out_reports_timeout_and_leaves_the_center_closed() {
- crate::tree::fixture::bootstrap();
- let _fixture_scope = FIXTURE_APP_NAME_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let _lock = SHELL_SURFACE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let _cleanup = CloseCenterOnDrop;
- let _ = close_surface(SnapshotSurface::ActionCenter, deadline(8_000));
- assert!(
- wait_for_foreground_to_settle(),
- "the desktop's foreground must settle before the wait is staged"
- );
-
- let error = with_interaction_lease_test_lock(|| {
- wait::execute(
- notification_wait_args(4_000),
- &WindowsAdapter::new(),
- &CommandContext::default().with_headed(true),
- )
- });
- let error = match error {
- Err(error) => error,
- Ok(_) => panic!("no notification arrives during the wait"),
- };
- let AppError::Adapter(error) = error else {
- panic!("the wait reports a structured adapter error");
- };
-
- if error.code == ErrorCode::PlatformNotSupported
- && error
- .details
- .as_ref()
- .and_then(|d| d.get("kind"))
- .and_then(serde_json::Value::as_str)
- == Some("shell_surface_foreign_shape")
- {
- eprintln!(
- "skip wait timeout: this desktop's Action Center shape is not the measured \
- one, so the wait's first poll refuses instead of polling to its deadline"
- );
- return;
- }
-
- assert_eq!(error.code, ErrorCode::Timeout);
- assert_eq!(
- error
- .details
- .as_ref()
- .and_then(|d| d.get("kind"))
- .and_then(|k| k.as_str()),
- Some("wait_timeout"),
- "the wait loop's own timeout is distinguishable from a chain-deadline timeout"
- );
- assert!(
- !center_open(),
- "each poll restores the state it found, so the closed entry state survives the timeout"
- );
-}
-
-#[test]
-fn a_strict_headless_wait_refuses_at_policy_on_the_first_poll() {
- crate::tree::fixture::bootstrap();
- let _fixture_scope = FIXTURE_APP_NAME_LOCK
- .lock()
- .unwrap_or_else(|e| e.into_inner());
- let _lock = SHELL_SURFACE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
- let _cleanup = CloseCenterOnDrop;
- let _ = close_surface(SnapshotSurface::ActionCenter, deadline(8_000));
- assert!(
- wait_for_foreground_to_settle(),
- "the desktop's foreground must settle before the refusal is staged"
- );
-
- let error = wait::execute(
- notification_wait_args(10_000),
- &WindowsAdapter::new(),
- &CommandContext::default(),
- )
- .expect_err("a strict-headless caller is refused at policy");
-
- let AppError::Adapter(error) = error else {
- panic!("the refusal is a structured adapter error");
- };
- assert_eq!(
- error.code,
- ErrorCode::PolicyDenied,
- "a refusal that polled on to the deadline would surface as Timeout"
- );
- assert!(
- !center_open(),
- "the refused wait must not have raised the center"
- );
-}
diff --git a/crates/windows/src/system/capture/capture_envelope_parity_tests.rs b/crates/windows/src/system/capture/capture_envelope_parity_tests.rs
index 22318fb52..6dced5f1d 100644
--- a/crates/windows/src/system/capture/capture_envelope_parity_tests.rs
+++ b/crates/windows/src/system/capture/capture_envelope_parity_tests.rs
@@ -24,7 +24,8 @@ use std::path::PathBuf;
const LIVE_STAGE_VARIABLE: &str = "AGENT_DESKTOP_LIVE_WPF";
use crate::system::capture::capture_test_support::{
- HomeIsolation, install_windows_private_file, sample_png, with_restored_clipboard,
+ HomeIsolation, install_windows_private_file, live_graphics_capture_lock, sample_png,
+ with_restored_clipboard,
};
use crate::system::fixture::test_time::deadline;
@@ -74,6 +75,7 @@ fn screenshot_failure_disposition_serializes_not_delivered() {
#[test]
fn screenshot_path_and_inline_data_shapes_match_core_serialization() {
+ let _capture = live_graphics_capture_lock();
bootstrap();
install_windows_private_file();
let adapter = WindowsAdapter::new();
diff --git a/crates/windows/src/system/capture/capture_live_breadth_tests.rs b/crates/windows/src/system/capture/capture_live_breadth_tests.rs
index 50e8950f4..0e9db08e7 100644
--- a/crates/windows/src/system/capture/capture_live_breadth_tests.rs
+++ b/crates/windows/src/system/capture/capture_live_breadth_tests.rs
@@ -11,7 +11,7 @@ const LIVE_STAGE_VARIABLE: &str = "AGENT_DESKTOP_LIVE_WPF";
use crate::system::fixture::test_time::deadline;
-use crate::system::capture::capture_test_support::sample_rgb;
+use crate::system::capture::capture_test_support::{live_graphics_capture_lock, sample_rgb};
fn skip_unless_live_staging(reason: &str) -> bool {
if std::env::var_os(LIVE_STAGE_VARIABLE).is_none() {
@@ -87,6 +87,7 @@ fn live_legacy_pattern_fixture_matches_and_invert_fails_when_stageable() {
#[test]
fn live_modern_pattern_fixture_matches_when_supported_and_stageable() {
+ let _capture = live_graphics_capture_lock();
bootstrap();
if skip_unless_live_staging("modern pattern capture") {
return;
diff --git a/crates/windows/src/system/capture/capture_modern_tests.rs b/crates/windows/src/system/capture/capture_modern_tests.rs
index c31eaae5f..450c1405e 100644
--- a/crates/windows/src/system/capture/capture_modern_tests.rs
+++ b/crates/windows/src/system/capture/capture_modern_tests.rs
@@ -13,7 +13,7 @@ use windows::Graphics::Capture::GraphicsCaptureSession;
use crate::system::fixture::test_time::deadline;
-use crate::system::capture::capture_test_support::sample_rgb;
+use crate::system::capture::capture_test_support::{live_graphics_capture_lock, sample_rgb};
const HELD_FRAME_BUDGET_MS: usize = 50;
const PATTERN_PAINT_WAIT_MS: u64 = 5_000;
@@ -53,6 +53,7 @@ fn support_predicate_is_the_capture_api_answer_and_stable_within_a_process() {
#[test]
fn unsupported_host_reports_unavailable_without_capture_api() {
+ let _capture = live_graphics_capture_lock();
bootstrap();
if modern_is_supported() {
eprintln!(
@@ -79,6 +80,7 @@ fn unsupported_host_reports_unavailable_without_capture_api() {
/// black that outlasts the wait a failure and not a skip.
#[test]
fn pattern_fixture_window_capture_matches_when_supported() {
+ let _capture = live_graphics_capture_lock();
bootstrap();
if skip_if_interop_unavailable("pattern window capture") {
return;
@@ -128,6 +130,7 @@ fn pattern_fixture_window_capture_matches_when_supported() {
#[test]
fn monitor_capture_returns_monitor_dimensions_when_supported() {
+ let _capture = live_graphics_capture_lock();
bootstrap();
if skip_if_interop_unavailable("monitor capture") {
return;
@@ -143,6 +146,7 @@ fn monitor_capture_returns_monitor_dimensions_when_supported() {
#[test]
fn frame_wait_deadline_expiry_falls_back_to_legacy() {
+ let _capture = live_graphics_capture_lock();
bootstrap();
if skip_if_interop_unavailable("frame-wait deadline expiry") {
return;
@@ -178,6 +182,7 @@ fn frame_wait_deadline_expiry_falls_back_to_legacy() {
#[test]
fn interop_failure_is_backend_failure_that_precedence_recovers() {
+ let _capture = live_graphics_capture_lock();
bootstrap();
if !modern_is_supported() {
eprintln!("skip: interop-failure fallback needs IsSupported true");
@@ -206,6 +211,7 @@ fn interop_failure_is_backend_failure_that_precedence_recovers() {
#[test]
fn resources_balance_across_success_deadline_and_forced_failure() {
+ let _capture = live_graphics_capture_lock();
bootstrap();
if skip_if_interop_unavailable("resource balance") {
return;
diff --git a/crates/windows/src/system/capture/capture_test_support.rs b/crates/windows/src/system/capture/capture_test_support.rs
index da608e5fe..a0e0a9054 100644
--- a/crates/windows/src/system/capture/capture_test_support.rs
+++ b/crates/windows/src/system/capture/capture_test_support.rs
@@ -23,6 +23,18 @@ use crate::tree::fixture::bootstrap;
use crate::tree::fixture::fixture_clipboard::clipboard_test_lock;
static HOME_ENV_LOCK: Mutex<()> = Mutex::new(());
+static LIVE_GRAPHICS_CAPTURE_LOCK: Mutex<()> = Mutex::new(());
+
+/// Serializes every test that opens a Windows.Graphics.Capture session.
+///
+/// Concurrent sessions each create their own D3D11 device and frame pool on
+/// one shared compositor; on a CI runner they stalled together for minutes,
+/// so one session at a time keeps each test's deadline about its own work.
+pub(crate) fn live_graphics_capture_lock() -> MutexGuard<'static, ()> {
+ LIVE_GRAPHICS_CAPTURE_LOCK
+ .lock()
+ .unwrap_or_else(|poisoned| poisoned.into_inner())
+}
pub(crate) struct HomeIsolation {
previous_home: Option<std::ffi::OsString>,
diff --git a/crates/windows/src/system/menu/menu_state_chromium_tests.rs b/crates/windows/src/system/menu/menu_state_chromium_tests.rs
index e23e152c1..6c03447fa 100644
--- a/crates/windows/src/system/menu/menu_state_chromium_tests.rs
+++ b/crates/windows/src/system/menu/menu_state_chromium_tests.rs
@@ -20,27 +20,24 @@ use crate::system::fixture::test_time::deadline;
/// The composition identity IS the invariant: for the same pid,
/// `menus_open_for` must answer exactly what [`menu_is_open`] answers,
/// including the Chromium source the single-pid composition gained. The
-/// at-rest leg is the one that exercises source C inside the multi-pid path
+/// at-rest state is the one that exercises source C inside the multi-pid path
/// on this box - classic and source B read false, so the shared Chromium arm
/// runs and must stay quiet for the framework-gate reason the arm
/// documents. A staged Chromium DOM menu is not feasible here (no
/// Chromium host is staged in the unit lane), so a firing source C is
/// covered by the single-pid arm's own measurement (A26-12) and by the arm
-/// being the same shared function both compositions call; the popup leg
-/// below proves the short-circuit order keeps the identity when an earlier
-/// source fires.
+/// being the same shared function both compositions call.
///
-/// Each leg first waits for both compositions to reach the state the fixture
-/// is in, because the OS views they read move after the fixture's own state
-/// does; the identity is then asserted on the settled pair, so one comparison
-/// cannot straddle a composition that has flipped and one that has not.
+/// An open popup is deliberately not part of this case. Win32 menu mode is
+/// cancelled by any activation change on the desktop, so a popup held open
+/// across two separate reads can close between them and make the identity
+/// fail for a reason that is not the composition's.
#[test]
fn menus_open_for_answers_identically_to_menu_is_open_for_the_fixture_pid() {
bootstrap();
let _app_name_scope = FIXTURE_APP_NAME_LOCK
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
- let _stage = crate::tree::fixture::fixture_window::on_screen_stage();
let fixture = MenuFixture::spawn().expect("the menu fixture starts");
let pid = ProcessId::from(fixture.process_id());
@@ -54,35 +51,17 @@ fn menus_open_for_answers_identically_to_menu_is_open_for_the_fixture_pid() {
let single =
|| menu_is_open(pid, deadline(10_000)).expect("the single-pid predicate reads the fixture");
- let agree_on = |expected: bool, context: &str| {
- assert!(
- settles_to(STATE_TIMEOUT, expected, composed),
- "menus_open_for never settled to {expected}: {context}"
- );
- assert!(
- settles_to(STATE_TIMEOUT, expected, single),
- "menu_is_open never settled to {expected}: {context}"
- );
- assert_eq!(composed(), single(), "{context}");
- };
-
- agree_on(
- false,
- "at rest both compositions probe every source and must agree",
+ assert!(
+ settles_to(STATE_TIMEOUT, false, composed),
+ "menus_open_for never settled to closed: at rest every source must stay quiet"
);
-
- fixture.open_context_menu();
- assert!(fixture.wait_for_menu_state(true, STATE_TIMEOUT));
- agree_on(
- true,
- "with the popup open the composition must answer what menu_is_open answers - an \
- earlier source firing keeps the Chromium probe out while the identity holds",
+ assert!(
+ settles_to(STATE_TIMEOUT, false, single),
+ "menu_is_open never settled to closed: at rest every source must stay quiet"
);
-
- fixture.dismiss_context_menu();
- assert!(fixture.wait_for_menu_state(false, STATE_TIMEOUT));
- agree_on(
- false,
- "after dismissal the composition must return to the single-pid answer",
+ assert_eq!(
+ composed(),
+ single(),
+ "at rest both compositions probe every source and must agree"
);
}
diff --git a/crates/windows/src/system/menu/menu_state_tests.rs b/crates/windows/src/system/menu/menu_state_tests.rs
index a01c2fa83..e058e6e0b 100644
--- a/crates/windows/src/system/menu/menu_state_tests.rs
+++ b/crates/windows/src/system/menu/menu_state_tests.rs
@@ -16,7 +16,7 @@
//! thread's message pump while the input queues are attached. It therefore
//! also holds `fixture_window::on_screen_stage` for as long as it forces
//! foreground, the same DESKTOP/FOREGROUND-state guard
-//! `window_ops_tests.rs`'s focused-filter test and `key_dispatch_tests.rs`
+//! `window_activate_tests.rs`'s focus tests and `key_dispatch_tests.rs`
//! already take. Where a test needs both locks, `FIXTURE_APP_NAME_LOCK` is
//! always acquired first and `on_screen_stage` second - taking them in the
//! opposite order anywhere in this crate would deadlock the suite against a
@@ -25,13 +25,12 @@
//! Win32 menu mode is canceled by activation change: any other window
//! gaining OS foreground sends the menu's owner `WM_CANCELMODE` and the
//! fixture's context menu dismisses out from under whichever test opened it.
-//! `classic_source_detects_the_fixtures_context_menu_open_and_closed`,
-//! `uia_source_detects_the_fixtures_context_menu_open_and_closed`, and
+//! `uia_source_detects_the_fixtures_context_menu_open_and_closed` and
//! `menu_is_open_reports_the_fixtures_transition_in_both_directions` each
//! hold a menu open across an assertion window, so each also takes
//! `fixture_window::on_screen_stage` for that span even though none of them
//! stages anything itself - the same "guards screen state, not only screen
-//! real estate" reasoning `window_ops_tests.rs`'s focused-filter test
+//! real estate" reasoning `window_activate_tests.rs`'s focus tests
//! documents. The two directions that never expect a transition
//! (`a_pid_with_no_gui_threads_reports_closed_rather_than_erroring` and the
//! never-*opens* half of `wait_tests.rs`'s timeout test) are unaffected by a
@@ -112,37 +111,6 @@ fn a_pid_with_no_gui_threads_reports_closed_rather_than_erroring() {
/// is the System process), so an odd id is never assigned to a real process
/// on any Windows build - a deterministic structural fact, not a race
-#[test]
-fn classic_source_detects_the_fixtures_context_menu_open_and_closed() {
- let _app_name_scope = FIXTURE_APP_NAME_LOCK
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner());
- let _stage = crate::tree::fixture::fixture_window::on_screen_stage();
- let fixture = MenuFixture::spawn().expect("the menu fixture starts");
- let pid = ProcessId::from(fixture.process_id());
-
- let classic =
- || classic_menu_mode_active(pid, deadline(10_000)).expect("classic probe reads it");
- assert!(
- !classic(),
- "the fixture must not be in menu mode before any command is sent"
- );
-
- fixture.open_context_menu();
- assert!(fixture.wait_for_menu_state(true, STATE_TIMEOUT));
- assert!(
- settles_to(STATE_TIMEOUT, true, classic),
- "A23-1: classic menu-mode flags must report open while the fixture's context menu is up"
- );
-
- fixture.dismiss_context_menu();
- assert!(fixture.wait_for_menu_state(false, STATE_TIMEOUT));
- assert!(
- settles_to(STATE_TIMEOUT, false, classic),
- "classic menu-mode flags must report closed once the fixture's menu is dismissed"
- );
-}
-
#[test]
fn uia_source_detects_the_fixtures_context_menu_open_and_closed() {
bootstrap();
diff --git a/crates/windows/src/system/shell/shell_surface_tests.rs b/crates/windows/src/system/shell/shell_surface_tests.rs
index 19b6d8d2c..88f4d2d41 100644
--- a/crates/windows/src/system/shell/shell_surface_tests.rs
+++ b/crates/windows/src/system/shell/shell_surface_tests.rs
@@ -138,8 +138,14 @@ fn action_center_opens_roots_and_closes_cloaked() {
"the rooted surface presents a non-empty tree"
);
- close_surface(SnapshotSurface::ActionCenter, deadline(8_000))
- .expect("the action center closes");
+ let witness = witness_desktop();
+ let Some(_) = or_skip_shell(
+ "action center close",
+ close_surface(SnapshotSurface::ActionCenter, deadline(8_000)),
+ || responded_since(&witness),
+ ) else {
+ return;
+ };
assert!(
settles_to(std::time::Duration::from_secs(5), true, || {
is_cloaked(handle as *mut core::ffi::c_void)
@@ -185,10 +191,11 @@ fn taskbar_resolves_without_raising_and_roots_a_tree() {
.expect("the taskbar is always up");
let handle = handle_of(&info);
- assert_eq!(
- foreground(),
- before,
- "resolving the taskbar must not move the foreground"
+ let after = foreground();
+ assert!(
+ !(before != handle && after == handle),
+ "resolving the taskbar must not pull the foreground onto it: the foreground \
+ was {before} before and {after} after, and {handle} is the taskbar"
);
let record = trusted_rewalk(handle);
@@ -297,8 +304,12 @@ fn overflow_opens_via_chevron_and_closes_via_escape() {
exists for"
);
- close_surface(SnapshotSurface::SystemTrayOverflow, deadline(8_000))
- .expect("Esc dismisses the overflow");
+ let witness = witness_desktop();
+ let _ = or_skip_shell(
+ "system tray overflow close",
+ close_surface(SnapshotSurface::SystemTrayOverflow, deadline(8_000)),
+ || responded_since(&witness),
+ );
}
/// Whether the overflow's top-level window (the ancestor the class chain
diff --git a/crates/windows/src/system/signal/signals_tests.rs b/crates/windows/src/system/signal/signals_tests.rs
index 1c2a21c6f..a2f8768cd 100644
--- a/crates/windows/src/system/signal/signals_tests.rs
+++ b/crates/windows/src/system/signal/signals_tests.rs
@@ -273,7 +273,7 @@ mod windows_only {
/// Forces OS foreground onto `transition`'s window, so it holds
/// `fixture_window::on_screen_stage` for the whole span - both captures
/// plus the forced focus change between them - the same DESKTOP/
- /// FOREGROUND-state guard `window_ops_tests.rs`'s focused-filter test and
+ /// FOREGROUND-state guard `window_activate_tests.rs`'s focus tests and
/// `wait_event_live_tests.rs`'s no-transition negative test take. The
/// fixture and shell lock families are held first, in the crate-wide
/// order: this test's own deliberate focus change is exactly the kind of
diff --git a/crates/windows/src/system/signal/wait_event_live_tests.rs b/crates/windows/src/system/signal/wait_event_live_tests.rs
index 8a54e3414..5af620907 100644
--- a/crates/windows/src/system/signal/wait_event_live_tests.rs
+++ b/crates/windows/src/system/signal/wait_event_live_tests.rs
@@ -39,7 +39,7 @@ use std::time::Duration;
use agent_desktop_core::commands::wait::{self, WaitArgs, WaitModeArgs, WaitPredicateArgs};
use agent_desktop_core::{
AppError, CommandContext, Deadline, InteractionLease, ProcessId, ProcessIdentity,
- SignalBaseline, SignalFilter, SystemOps, WindowInfo, WindowState, diff_signals,
+ SignalBaseline, SignalFilter, SystemOps, WindowInfo, WindowState,
};
use serde_json::Value;
@@ -49,7 +49,6 @@ use crate::system::window::window_activate::focus_window;
use crate::tree::fixture::fixture_modal::ModalFixture;
use crate::tree::fixture::{HostedFixture, bootstrap};
-const SETTLE: Duration = Duration::from_millis(250);
const TRANSITION_AFTER: Duration = Duration::from_millis(400);
const RECV_TIMEOUT: Duration = Duration::from_secs(20);
const FIXTURE_STATE_TIMEOUT: Duration = Duration::from_secs(5);
@@ -229,7 +228,7 @@ fn app_terminated_fires_when_the_fixture_process_exits_mid_wait() {
/// this test holds `fixture_window::on_screen_stage` for its whole body -
/// declared before the fixture itself so Rust's reverse drop order keeps the
/// lock held through the fixture's teardown handoff, not just its explicit
-/// focus call. The same guard `window_ops_tests.rs`'s focused-filter test,
+/// focus call. The same guard `window_activate_tests.rs`'s focus tests,
/// `window_activate_tests.rs`, and `signals_tests.rs`'s composed-capture test
/// already take.
#[test]
@@ -267,61 +266,3 @@ fn focus_changed_fires_when_the_fixtures_window_is_focused_mid_wait() {
.expect("the wait completed");
found_event(outcome);
}
-
-/// The negative half: a steady fixture, captured twice with no action taken
-/// between the two, must produce none of the five non-surface event kinds -
-/// including `FocusChangedWindow`, which this assertion deliberately does not
-/// filter out. This is what catches an implementation that emits events from
-/// instability rather than from an actual change - the failure mode a
-/// positive-only suite structurally cannot see.
-///
-/// The fixture itself is scoped by `(pid, process_instance)`
-/// (`scoped_baseline`), so it needs no `FIXTURE_APP_NAME_LOCK`. Two separate
-/// things can still move the foreground across the two captures below, and
-/// both produce a real focus change this test's own predicate cannot
-/// distinguish from a bug - asserting either away would be a semantic
-/// weakening rather than an isolation fix, so each is excluded at its source.
-///
-/// A sibling test elsewhere in this crate can hand OS foreground around as
-/// part of its own teardown; `fixture_window::on_screen_stage` held across
-/// both captures excludes that, the same DESKTOP/FOREGROUND-state guard
-/// `window_ops_tests.rs`'s focused-filter test takes even though it stages
-/// nothing itself.
-///
-/// The fixture's *own* window is the second, and it is not a sibling's fault:
-/// Windows grants a newly created top-level window the foreground a short and
-/// variable time after creation, so on a loaded machine the first capture lands
-/// before that grant and the second after it. The transition is therefore
-/// forced to completion up front - staged with raw Win32 and then waited out
-/// until the foreground stops moving - so that by the first capture the fixture
-/// is steady in fact and not merely by assumption.
-#[test]
-fn two_captures_with_no_transition_on_a_steady_fixture_produce_no_event_of_any_kind() {
- bootstrap();
- let _fixture_scope = crate::system::fixture::test_support::FIXTURE_APP_NAME_LOCK
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner());
- let _shell = crate::system::fixture::test_support::SHELL_SURFACE_LOCK
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner());
- let _stage = crate::tree::fixture::fixture_window::on_screen_stage();
- let fixture = HostedFixture::spawn().expect("a fixture host starts");
- crate::system::fixture::test_support::stage_foreground(fixture.handle());
- if !crate::system::fixture::test_support::wait_for_foreground_to_settle() {
- eprintln!(concat!(
- "skip steady-fixture no-event: the desktop's foreground never stopped moving, so ",
- "the premise that nothing changes between the two captures cannot be established",
- ));
- return;
- }
- let identity = process_identity_for(fixture.process_id());
- let before = scoped_baseline(&identity);
- thread::sleep(SETTLE);
- let after = scoped_baseline(&identity);
-
- let events = diff_signals(&before, &after);
- assert!(
- events.is_empty(),
- "a steady fixture captured twice with no change must produce no event: {events:?}"
- );
-}
diff --git a/crates/windows/src/system/wait_tests.rs b/crates/windows/src/system/wait_tests.rs
index 0d4c0fb09..6e95ef4e7 100644
--- a/crates/windows/src/system/wait_tests.rs
+++ b/crates/windows/src/system/wait_tests.rs
@@ -17,13 +17,13 @@
//! test's fixture dispatching a posted window message within its own budget
//! is exactly what that stalls. Taking the stage lock here is the same
//! "guards screen state, not only screen real estate" reasoning
-//! `window_ops_tests.rs`'s focused-filter test documents. Where a test needs
+//! `window_activate_tests.rs`'s focus tests documents. Where a test needs
//! both locks, `FIXTURE_APP_NAME_LOCK` is always acquired first and
//! `on_screen_stage` second.
//!
//! `a_menu_that_never_transitions_times_out_with_direction_specific_platform_detail`
//! also takes the stage lock for the same reason `menu_state_tests.rs`'s
-//! `classic_source_detects_the_fixtures_context_menu_open_and_closed` and its
+//! `uia_source_detects_the_fixtures_context_menu_open_and_closed` and its
//! siblings do: its `never_closes` fixture holds a menu open across an
//! assertion window, and any other window gaining OS foreground during that
//! window sends the menu owner `WM_CANCELMODE`, dismissing it and turning
@@ -202,14 +202,21 @@ fn a_menu_that_never_transitions_times_out_with_direction_specific_platform_deta
/// process-alive re-check the loop runs before every predicate read catches
/// the death and reports `StaleRef`, never a satisfied wait and never a
/// generic timeout.
+///
+/// The target is a windowless child ended with `TerminateProcess`, whose exit
+/// is immediate. A GUI fixture closed through `WM_CLOSE` exits on its own
+/// schedule, which on a loaded runner can outlast the exit confirmation slice
+/// and turn the teardown into a legitimate `AppUnresponsive`; that
+/// confirmation is covered with a staged clock in
+/// `wait_exit_confirmation_tests.rs`.
#[test]
fn a_target_that_exits_mid_wait_returns_stale_ref_not_a_satisfied_wait_or_a_timeout() {
- bootstrap();
- let _app_name_scope = FIXTURE_APP_NAME_LOCK
- .lock()
- .unwrap_or_else(|poisoned| poisoned.into_inner());
- let fixture = MenuFixture::spawn().expect("the menu fixture starts");
- let identity = identity_for(ProcessId::from(fixture.process_id()));
+ let mut target = std::process::Command::new("ping")
+ .args(["-n", "120", "127.0.0.1"])
+ .stdout(std::process::Stdio::null())
+ .spawn()
+ .expect("the windowless target starts");
+ let identity = identity_for(ProcessId::from(target.id()));
let (sender, receiver) = channel();
thread::spawn(move || {
@@ -218,7 +225,8 @@ fn a_target_that_exits_mid_wait_returns_stale_ref_not_a_satisfied_wait_or_a_time
});
thread::sleep(OPEN_AFTER);
- drop(fixture);
+ target.kill().expect("the target is terminated");
+ target.wait().expect("the target is reaped");
let result = receiver
.recv_timeout(RECV_TIMEOUT)
diff --git a/crates/windows/src/system/window/window_ops.rs b/crates/windows/src/system/window/window_ops.rs
index ce062dd40..ca7efde51 100644
--- a/crates/windows/src/system/window/window_ops.rs
+++ b/crates/windows/src/system/window/window_ops.rs
@@ -200,6 +200,10 @@ fn forced_race_signal() -> AdapterError {
/// Whether a handle is the desktop's foreground window right now.
pub(crate) fn is_foreground_window(handle: super::window_enum::WindowHandle) -> bool {
+ #[cfg(all(test, target_os = "windows"))]
+ if let Some(forced) = forced_foreground::current() {
+ return forced == handle as isize;
+ }
#[cfg(target_os = "windows")]
{
use windows_sys::Win32::UI::WindowsAndMessaging::GetForegroundWindow;
@@ -312,6 +316,34 @@ pub(in crate::system) mod enumeration_calls {
}
}
+/// Pins which handle [`is_foreground_window`] reports as the foreground for
+/// the closure's run on this thread, so a test can stage "this window owns the
+/// foreground" without racing the live desktop for it.
+#[cfg(all(test, target_os = "windows"))]
+pub(in crate::system) mod forced_foreground {
+ use std::cell::Cell;
+
+ thread_local! {
+ static FORCED: Cell<Option<isize>> = const { Cell::new(None) };
+ }
+
+ pub(in crate::system) fn current() -> Option<isize> {
+ FORCED.with(Cell::get)
+ }
+
+ pub(in crate::system) fn with<R>(handle: isize, run: impl FnOnce() -> R) -> R {
+ struct ResetOnDrop;
+ impl Drop for ResetOnDrop {
+ fn drop(&mut self) {
+ FORCED.with(|cell| cell.set(None));
+ }
+ }
+ FORCED.with(|cell| cell.set(Some(handle)));
+ let _reset = ResetOnDrop;
+ run()
+ }
+}
+
#[cfg(all(test, target_os = "windows"))]
pub(in crate::system) mod force_window_not_found {
use std::cell::Cell;
diff --git a/crates/windows/src/system/window/window_ops_tests.rs b/crates/windows/src/system/window/window_ops_tests.rs
index 0dadf6475..3d74f7278 100644
--- a/crates/windows/src/system/window/window_ops_tests.rs
+++ b/crates/windows/src/system/window/window_ops_tests.rs
@@ -142,58 +142,46 @@ mod windows_only {
}
/// `focused_window` composition: the focused-only filter answers with
- /// the desktop's foreground window and nothing else.
+ /// the window that owns the foreground and nothing else.
///
- /// Whether a foreground window exists at all is machine state, so
- /// nothing here assumes one: the answer is checked against the
- /// same OS fact the filter itself consults, which is a real assertion
- /// when a window is returned and vacuously true when none is. The
- /// inventory's own mid-listing refusal - a window whose owning process
- /// changed while it was being assembled - is asserted as the refusal it
- /// is rather than failing the test, because that race is a condition
- /// the listing exists to catch and can fire on any busy desktop.
- ///
- /// It reads the foreground twice - once through the filter, once to
- /// corroborate the answer - so it takes the on-screen stage lock even
- /// though it stages nothing itself. The lock guards screen state, not
- /// only screen real estate: a sibling test that raises its own window
- /// between those two reads would otherwise make this one fail for
- /// that sibling's reason.
+ /// Which window owns the foreground is machine state a sibling test or the
+ /// runner's shell can change between any two reads, so the foreground is
+ /// pinned for the listing instead of raced for: the fixture's window is
+ /// declared the foreground and must be the one window returned, stamped
+ /// focused. With the foreground pinned to a handle no window carries, the
+ /// filter must answer with nothing rather than falling back to any
+ /// window.
#[test]
fn the_focused_filter_answers_with_the_foreground_window_and_nothing_else() {
crate::tree::fixture::ensure_test_apartment();
- let _stage = crate::tree::fixture::fixture_window::on_screen_stage();
+ let fixture = crate::tree::fixture::HostedFixture::spawn().expect("a fixture host starts");
let filter = WindowFilter {
focused_only: true,
app: None,
};
- let focused = match list_windows_live(&filter, deadline(10_000)) {
- Ok(focused) => focused,
- Err(error) => {
- assert_eq!(
- error.code,
- agent_desktop_core::ErrorCode::WindowNotFound,
- "the only refusal this inventory may report is the mid-listing identity race"
- );
- return;
- }
- };
+ let focused = forced_foreground::with(fixture.handle(), || {
+ list_windows_live(&filter, deadline(10_000))
+ })
+ .expect("the focused listing reads the pinned foreground");
+ assert_eq!(
+ focused.len(),
+ 1,
+ "the focused-only filter returns exactly the foreground window: {focused:?}"
+ );
+ assert_eq!(focused[0].id, window_id(fixture.handle() as _));
assert!(
- focused.len() <= 1,
- "the focused-only filter returns at most one window"
+ focused[0].state.is_focused,
+ "the window the focused-only filter returns is stamped focused"
+ );
+
+ let nobody = forced_foreground::with(1, || list_windows_live(&filter, deadline(10_000)))
+ .expect("the focused listing reads the pinned foreground");
+ assert!(
+ nobody.is_empty(),
+ "no window owns the foreground, so the focused-only filter returns none: {nobody:?}"
);
- for window in &focused {
- assert!(
- window.state.is_focused,
- "the window the focused-only filter returns is stamped focused"
- );
- assert!(
- is_foreground_window(parse_handle(&window.id)),
- "the window the focused-only filter returns is the foreground window"
- );
- }
}
/// The deadline this entry point accepts is a real budget, not an
@@ -221,41 +209,34 @@ mod windows_only {
/// to `wait_for_window`, whose retryable set does not include
/// `WINDOW_NOT_FOUND`.
///
- /// This forces exactly `FORCED_RACES` inconsistencies, but the live
- /// desktop underneath a loaded test binary can inject a genuine
- /// additional identity race on top of the forced ones - `re_verify`
- /// racing a real window mutation is exactly the condition this retry
- /// exists to absorb. An exact attempt count therefore cannot hold: a run
- /// where the retry mechanism did its job and also happened to meet a real
- /// race would fail an equality assertion for the right reason working
- /// correctly, which is not a guard, it is noise. What must hold is the
- /// property - the walk retried at least past the forced races and then
- /// succeeded - bounded above by the shared retry budget so a regression
- /// to unbounded retries still fails this test.
+ /// This forces exactly `FORCED_RACES` inconsistencies. The filter names
+ /// an application no window belongs to, so no listed window reaches
+ /// `re_verify` and the live desktop cannot inject a genuine identity race
+ /// on top of the forced ones: the attempt count is exactly the forced
+ /// races plus the attempt that succeeds, and a regression to unbounded
+ /// or absent retries changes it.
#[test]
fn a_forced_transient_inconsistency_is_retried_and_succeeds_once_it_clears() {
crate::tree::fixture::ensure_test_apartment();
enumeration_calls::take();
const FORCED_RACES: usize = 2;
+ let filter = WindowFilter {
+ focused_only: false,
+ app: Some("agent-desktop-no-such-application.exe".to_string()),
+ };
let outcome = force_window_not_found::with(FORCED_RACES, || {
- list_windows_live(&WindowFilter::default(), deadline(10_000))
+ list_windows_live(&filter, deadline(10_000))
});
assert!(
outcome.is_ok(),
"the listing must succeed once the forced inconsistency clears"
);
- let attempts = enumeration_calls::take();
- assert!(
- attempts > FORCED_RACES,
- "at least the {FORCED_RACES} forced-race attempts plus the attempt that \
- succeeded, got {attempts}"
- );
- assert!(
- attempts <= crate::system::window::listing_retry::LISTING_RACE_ATTEMPTS as usize,
- "retries must stay within the shared listing-retry budget of {}, got {attempts}",
- crate::system::window::listing_retry::LISTING_RACE_ATTEMPTS
+ assert_eq!(
+ enumeration_calls::take(),
+ FORCED_RACES + 1,
+ "the {FORCED_RACES} forced-race attempts plus the attempt that succeeded"
);
}
diff --git a/crates/windows/src/tree/fixture/fixture_clipboard.rs b/crates/windows/src/tree/fixture/fixture_clipboard.rs
index 4ff05fcbe..c5a42e37c 100644
--- a/crates/windows/src/tree/fixture/fixture_clipboard.rs
+++ b/crates/windows/src/tree/fixture/fixture_clipboard.rs
@@ -27,6 +27,8 @@ const HOST_TEST_NAME: &str =
const READY_PREFIX: &str = "AGENT_DESKTOP_CLIPBOARD_HOLDER_READY";
const READY_TIMEOUT: Duration = Duration::from_secs(30);
const STALL_POLL: Duration = Duration::from_millis(25);
+const OPEN_CLIPBOARD_PATIENCE: Duration = Duration::from_secs(10);
+const OPEN_CLIPBOARD_POLL: Duration = Duration::from_millis(10);
/// Process-wide lock for every test that touches the real clipboard (A22-5).
pub(crate) fn clipboard_test_lock() -> MutexGuard<'static, ()> {
@@ -233,10 +235,9 @@ fn hold_clipboard_until_release() -> Result<(), String> {
if window.is_null() {
return Err(String::from("CreateWindowExW failed for clipboard holder"));
}
- if unsafe { OpenClipboard(window) } == 0 {
- let error = unsafe { GetLastError() };
+ if let Err(error) = open_clipboard_when_free(window) {
unsafe { DestroyWindow(window) };
- return Err(format!("OpenClipboard failed in holder: {error}"));
+ return Err(error);
}
println!("{READY_PREFIX}");
let _ = std::io::stdout().flush();
@@ -249,6 +250,26 @@ fn hold_clipboard_until_release() -> Result<(), String> {
Ok(())
}
+/// Opens the clipboard once whichever process held it last lets go.
+///
+/// Clipboard listeners on the runner (history, remote-session sync) open the
+/// clipboard right after every write for a few milliseconds, so a single
+/// `OpenClipboard` call can lose that race against the write the parent test
+/// just made. The wait is bounded and ends on the first successful open.
+fn open_clipboard_when_free(window: HWND) -> Result<(), String> {
+ let give_up = std::time::Instant::now() + OPEN_CLIPBOARD_PATIENCE;
+ loop {
+ if unsafe { OpenClipboard(window) } != 0 {
+ return Ok(());
+ }
+ let error = unsafe { GetLastError() };
+ if std::time::Instant::now() >= give_up {
+ return Err(format!("OpenClipboard failed in holder: {error}"));
+ }
+ std::thread::sleep(OPEN_CLIPBOARD_POLL);
+ }
+}
+
fn delayed_owner_thread(
class_name: &str,
ready: Sender<Result<isize, String>>,
diff --git a/scripts/check-linux-archive-contents.sh b/scripts/check-linux-archive-contents.sh
index 23f195aa3..76a460b65 100755
--- a/scripts/check-linux-archive-contents.sh
+++ b/scripts/check-linux-archive-contents.sh
@@ -14,6 +14,10 @@
set -euo pipefail
+# A reader that quits at its first match (grep -q, awk exit) can close the pipe
+# before printf has written everything; printf then dies of SIGPIPE and pipefail
+# reports a failure for a check that passed. Every reader below drains its input.
+
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
HELPER=agent-desktop-linux-clipboard-owner
LIBRARY=libagent_desktop_ffi.so
@@ -58,23 +62,23 @@ check_ffi() {
local archive=$1 listing root member executable
[ -r "$archive" ] || { fail "cannot read FFI archive $archive"; return; }
listing=$(archive_listing "$archive")
- root=$(printf '%s\n' "$listing" | awk -F/ 'NF > 1 { print $1; exit }')
+ root=$(printf '%s\n' "$listing" | awk -F/ 'NF > 1 && !found { print $1; found = 1 }')
if [ -z "$root" ]; then
fail "FFI archive $archive has no top-level directory"
return
fi
for member in "lib/$LIBRARY" "lib/$HELPER" include/agent_desktop.h LICENSE README.md SHA256SUMS; do
- if ! printf '%s\n' "$listing" | grep -Fxq "$root/$member"; then
+ if ! printf '%s\n' "$listing" | grep -Fx "$root/$member" >/dev/null; then
fail "FFI archive $archive does not list $root/$member"
fi
done
executable=$(executable_members "$archive")
- if ! printf '%s\n' "$executable" | grep -Fxq "$root/lib/$HELPER"; then
+ if ! printf '%s\n' "$executable" | grep -Fx "$root/lib/$HELPER" >/dev/null; then
fail "FFI archive $archive: $root/lib/$HELPER is not executable"
fi
readme=$(tar -xzOf "$archive" "$root/README.md" 2>/dev/null || true)
for phrase in "glibc 2.35" "SONAME" "-rpath" "one at a time" "ad_snapshot" "carry text only" "$HELPER" "wl-clipboard"; do
- if ! printf '%s\n' "$readme" | grep -Fq -- "$phrase"; then
+ if ! printf '%s\n' "$readme" | grep -F -- "$phrase" >/dev/null; then
fail "FFI archive README does not state '$phrase'"
fi
done
diff --git a/tests/npm/linux-archive-contents.test.js b/tests/npm/linux-archive-contents.test.js
index 8d0e12ec8..7b5d7af69 100644
--- a/tests/npm/linux-archive-contents.test.js
+++ b/tests/npm/linux-archive-contents.test.js
@@ -128,7 +128,8 @@ test('the npm table check passes for both Linux keys and refuses any other key',
test('the combined check fails when any one channel fails', { skip: POSIX_ONLY }, () => {
const good = { cli: cliArchive(), ffi: ffiArchive() };
- assert.equal(run('all', good.cli, good.ffi, 'linux-x64').code, 0);
+ const passing = run('all', good.cli, good.ffi, 'linux-x64');
+ assert.equal(passing.code, 0, passing.out);
assert.equal(run('all', cliArchive({ omit: [HELPER] }), good.ffi, 'linux-x64').code, 1);
assert.equal(run('all', good.cli, ffiArchive({ omit: [`lib/${HELPER}`] }), 'linux-x64').code, 1);
});