Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(sandbox): name a Local Network block when a resumed Space waits for its services (CUA-1807) (#5363)
Francesco Bonacci3bfb1d1d1464
diff --git a/libs/cua/crates/cua-sandbox-core/src/sandbox.rs b/libs/cua/crates/cua-sandbox-core/src/sandbox.rsindex ee852f33c2..588590a91a 100644--- a/libs/cua/crates/cua-sandbox-core/src/sandbox.rs+++ b/libs/cua/crates/cua-sandbox-core/src/sandbox.rs@@ -3372,11 +3372,22 @@ impl Sandbox {/// Waits until every probe passes or `timeout` elapses.pub async fn wait_ready(&self, probes: &[Probe], timeout: Duration) -> Result<()> {let deadline = Instant::now() + timeout;+ let grace = cua_vmm::probe::unreachable_grace();for probe in probes {+ let mut unreachable = cua_vmm::probe::UnreachableWatch::default();loop {- let ok = self.probe_once(probe).await;- if ok {- break;+ let now = tokio::time::Instant::now();+ match self.probe_once(probe).await {+ ProbeTry::Passed => break,+ ProbeTry::NotYet => unreachable.reset(),+ // No route the whole grace (on macOS: Local Network+ // privacy), or still none at the deadline: say so, as a+ // create does, instead of a bare timeout.+ ProbeTry::Unreachable { addr, error } => {+ if unreachable.observe(now) >= grace || Instant::now() >= deadline {+ return Err(unreachable_failure(&addr, &error));+ }+ }}// A probe can never pass once the instance is gone: fail// fast instead of waiting out the budget.@@ -3419,7 +3430,7 @@ impl Sandbox {}}- async fn probe_once(&self, probe: &Probe) -> bool {+ async fn probe_once(&self, probe: &Probe) -> ProbeTry {let per_try = Duration::from_secs(10);if let (Probe::Tcp(guest_port), Target::Local { .. }) = (probe, &self.target) {// Ask the runtime first: a host-side connect through a@@ -3427,15 +3438,15 @@ impl Sandbox {// guest listens.if let Ok(rt) = self.mgr.local() {match rt.guest_tcp_listening(&self.name, *guest_port).await {- Ok(Some(listening)) => return listening,+ Ok(Some(listening)) => return listening.into(),Ok(None) => {}- Err(_) => return false,+ Err(_) => return ProbeTry::NotYet,}}}if let Target::Contrib { provider, instance } = &self.target {let Ok(ep) = provider.0.endpoint(instance, probe_port(probe)) else {- return false;+ return ProbeTry::NotYet;};let (path, want) = match probe {Probe::Tcp(_) => ("/", None),@@ -3447,7 +3458,7 @@ impl Sandbox {.http.request("GET", &ep.url_for(path), &ep.headers, None, per_try).await;- return match (resp, want) {+ let passed = match (resp, want) {// Through the provider's proxy a TCP probe means the port's// server answers (the proxy's own errors are 5xx).(Ok(r), None) => r.status < 500,@@ -3455,12 +3466,13 @@ impl Sandbox {(Ok(r), Some(None)) => (200..300).contains(&r.status),(Err(_), _) => false,};+ return passed.into();}- match (probe, self.port(probe_port(probe))) {+ let passed = match (probe, self.port(probe_port(probe))) {(Probe::Tcp(_), Ok(PortTarget::Addr { host, port })) => {- tokio::time::timeout(per_try, tcp_alive(&host, port))+ return tokio::time::timeout(per_try, tcp_try(&host, port)).await- .unwrap_or(false)+ .unwrap_or(ProbeTry::NotYet);}(Probe::Tcp(_), Ok(PortTarget::Url(url))) => self.http_get(&url, per_try)@@ -3481,7 +3493,8 @@ impl Sandbox {}}(_, Err(_)) => false,- }+ };+ passed.into()}async fn http_get(&self, url: &str, timeout: Duration) -> Result<HttpResponse> {@@ -3681,19 +3694,58 @@ async fn fleet_services(.collect()}+/// One readiness probe attempt ([`Sandbox::wait_ready`]).+#[derive(Debug)]+enum ProbeTry {+ Passed,+ /// Refused, timed out, closed at once, or a bad status.+ NotYet,+ /// No route to the guest ([`cua_vmm::probe::is_unreachable`]): on+ /// macOS, Local Network privacy blocks this process.+ Unreachable {+ addr: String,+ error: std::io::Error,+ },+}++impl From<bool> for ProbeTry {+ fn from(passed: bool) -> Self {+ if passed { Self::Passed } else { Self::NotYet }+ }+}++/// What a connect error says ([`ProbeTry::Unreachable`] or not yet).+fn connect_failed(addr: String, error: std::io::Error) -> ProbeTry {+ if cua_vmm::probe::is_unreachable(&error) {+ ProbeTry::Unreachable { addr, error }+ } else {+ ProbeTry::NotYet+ }+}++/// The error for a guest still unroutable from this process: the one a+/// create gives ([`cua_vmm::probe::unreachable_error`]), which names Local+/// Network access on macOS.+fn unreachable_failure(addr: &str, error: &std::io::Error) -> Error {+ Error::Runtime(crate::RuntimeError::Other(+ cua_vmm::probe::unreachable_error(addr, error).to_string(),+ ))+}+/// Connects, then requires the peer to send data or hold the connection/// open for 400 ms: a forwarder with nothing behind it accepts and then/// closes straight away.-async fn tcp_alive(host: &str, port: u16) -> bool {+async fn tcp_try(host: &str, port: u16) -> ProbeTry {use tokio::io::AsyncReadExt;- let Ok(mut s) = TcpStream::connect((host, port)).await else {- return false;+ let mut s = match TcpStream::connect((host, port)).await {+ Ok(s) => s,+ Err(e) => return connect_failed(host_port(host, port), e),};let mut buf = [0u8; 64];match tokio::time::timeout(Duration::from_millis(400), s.read(&mut buf)).await {- Err(_) => true,- Ok(Ok(n)) => n > 0,- Ok(Err(_)) => false,+ Err(_) => ProbeTry::Passed,+ Ok(Ok(n)) => (n > 0).into(),+ Ok(Err(_)) => ProbeTry::NotYet,}}@@ -4287,6 +4339,57 @@ fn local_env_token(o: &CreateOptions) -> Option<String> {given.or_else(|| (!o.os.eq_ignore_ascii_case("windows")).then(mint_env_token))}+#[cfg(test)]+mod readiness_tests {+ use super::*;+ use std::io::{Error as IoError, ErrorKind};++ #[test]+ fn no_route_to_the_guest_is_unreachable_not_not_yet() {+ let addr = || "192.168.64.5:3211".to_string();+ for kind in [ErrorKind::HostUnreachable, ErrorKind::NetworkUnreachable] {+ assert!(matches!(+ connect_failed(addr(), IoError::from(kind)),+ ProbeTry::Unreachable { .. }+ ));+ }+ for kind in [ErrorKind::ConnectionRefused, ErrorKind::TimedOut] {+ assert!(matches!(+ connect_failed(addr(), IoError::from(kind)),+ ProbeTry::NotYet+ ));+ }+ }++ #[test]+ fn an_unreachable_guest_fails_with_the_create_error() {+ let error = IoError::from(ErrorKind::HostUnreachable);+ let text = unreachable_failure("192.168.64.5:3211", &error).to_string();+ let want = if cfg!(target_os = "macos") {+ "Local Network access is not available"+ } else {+ "a network route to the guest is not available"+ };+ assert!(text.starts_with(want), "{text}");+ assert!(text.contains("192.168.64.5:3211"), "{text}");+ }++ #[tokio::test]+ async fn a_listener_that_holds_the_connection_passes_and_a_closed_port_does_not() {+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = listener.local_addr().unwrap().port();+ let hold = tokio::spawn(async move {+ let (s, _) = listener.accept().await.unwrap();+ tokio::time::sleep(Duration::from_secs(1)).await;+ drop(s);+ });+ assert!(matches!(tcp_try("127.0.0.1", port).await, ProbeTry::Passed));+ hold.await.unwrap();+ // Nothing listens there now: refused, which is "not yet".+ assert!(matches!(tcp_try("127.0.0.1", port).await, ProbeTry::NotYet));+ }+}+#[cfg(test)]mod placement_tests {use super::*;