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(cua-spaces): a brief relay outage no longer flashes "Could not refresh Spaces" (CUA-1770) (#5315)
ddupont84a55c29d483
diff --git a/libs/cua/crates/cua-host/src/host.rs b/libs/cua/crates/cua-host/src/host.rsindex 71f1eb430f..f393662fc7 100644--- a/libs/cua/crates/cua-host/src/host.rs+++ b/libs/cua/crates/cua-host/src/host.rs@@ -1316,7 +1316,7 @@ impl Host {}status.paused_signed_out = config.paused_signed_out;if let (Some(url), Some(id)) = (&config.relay_url, &config.machine_id) {- match self.relay_machine(url, id).await {+ match recall_relay_view(url, id, self.relay_machine(url, id).await) {Ok(m) => {status.online = Some(m.online);// Paused: nobody can reach it, whatever the relay's@@ -1689,6 +1689,41 @@ impl Host {}}+/// How long [`Host::status`] keeps the relay's last answer about this+/// machine while the relay is briefly unreachable, before it shows the+/// failure ("Needs attention"). A relay deploy replaces its one pod, and+/// the proxy in front of it answers 503 for about 20 s meanwhile; the+/// host service reconnects on its own.+pub const RELAY_HICCUP_GRACE: std::time::Duration = std::time::Duration::from_secs(120);++/// The relay's last answer about each machine (relay URL, machine id),+/// and when it came.+type RelayViews = std::collections::HashMap<(String, String), (std::time::Instant, crate::Machine)>;+static RELAY_VIEWS: std::sync::Mutex<Option<RelayViews>> = std::sync::Mutex::new(None);++/// `read` (the relay's answer about machine `id`), remembered when it+/// worked; a transient failure ([`Error::is_transient`]) within+/// [`RELAY_HICCUP_GRACE`] of the last answer gets that answer instead.+fn recall_relay_view(url: &str, id: &str, read: Result<crate::Machine>) -> Result<crate::Machine> {+ let key = (url.to_string(), id.to_string());+ let mut views = RELAY_VIEWS.lock().unwrap_or_else(|e| e.into_inner());+ let views = views.get_or_insert_with(Default::default);+ match read {+ Ok(m) => {+ views.insert(key, (std::time::Instant::now(), m.clone()));+ Ok(m)+ }+ Err(e) if e.is_transient() => match views.get(&key) {+ Some((at, m)) if at.elapsed() < RELAY_HICCUP_GRACE => {+ tracing::debug!("relay status read failed; showing its last answer: {e}");+ Ok(m.clone())+ }+ _ => Err(e),+ },+ Err(e) => Err(e),+ }+}+/// `account` (an id, or an email) is the policy's owner. An empty/// `account` or owner says nothing, and is taken as the owner.pub fn owned_by(policy: &HostPolicy, account: &str) -> bool {diff --git a/libs/cua/crates/cua-host/src/lib.rs b/libs/cua/crates/cua-host/src/lib.rsindex 4f40778075..70394af081 100644--- a/libs/cua/crates/cua-host/src/lib.rs+++ b/libs/cua/crates/cua-host/src/lib.rs@@ -54,8 +54,8 @@ pub use device::{DeviceAuth, DeviceKey, FileKeySlot, KeySlot, MemoryKeySlot, Penpub use host::SetupStage;pub use host::{DirectHosting, Host, HostConfig, HostMode, HostPaths, HostPolicy, HostSettingsChange,- HostStatus, META_ARCH, META_OS, META_PROVIDES_SPACES, PermissionHint, SetupOptions,- SpacesDaemon, local_network_hint, permission_hints,+ HostStatus, META_ARCH, META_OS, META_PROVIDES_SPACES, PermissionHint, RELAY_HICCUP_GRACE,+ SetupOptions, SpacesDaemon, local_network_hint, permission_hints,};pub use machine::machine_id;pub use pairing::{@@ -166,6 +166,21 @@ impl Error {_ => None,}}++ /// A relay failure that may pass on its own: the relay (or the proxy in+ /// front of it, which answers 503 "no available server" while the+ /// relay's one pod is replaced) answered 429, 502, 503 or 504, or it+ /// was not reached at all (offline, DNS, a timeout). Not a refusal, a+ /// missing machine or an answer that could not be read.+ pub fn is_transient(&self) -> bool {+ match self {+ Error::Relay(m) => match status_in(m) {+ Some(code) => matches!(code, 429 | 502 | 503 | 504),+ None => !m.starts_with("bad relay response"),+ },+ _ => false,+ }+ }}/// The status in an "HTTP 503: ..." / "<url>: HTTP 404 Not Found" message.diff --git a/libs/cua/crates/cua-host/src/relay.rs b/libs/cua/crates/cua-host/src/relay.rsindex 20e4f4dc84..67eef3df26 100644--- a/libs/cua/crates/cua-host/src/relay.rs+++ b/libs/cua/crates/cua-host/src/relay.rs@@ -471,6 +471,16 @@ const REGISTER_RETRY_BASE: Duration = Duration::from_secs(1);#[cfg(test)]const REGISTER_RETRY_BASE: Duration = Duration::from_millis(5);+/// Times a read (a GET, which changes nothing) is tried again when the+/// relay was not reached or answered 429, 502 or 503, before the caller+/// sees the failure.+const READ_RETRIES: u32 = 2;+/// The first wait before reading again (tripled each time).+#[cfg(not(test))]+const READ_RETRY_BASE: Duration = Duration::from_millis(250);+#[cfg(test)]+const READ_RETRY_BASE: Duration = Duration::from_millis(5);+/// HTTP client for one relay.#[derive(Clone, Debug)]pub struct RelayClient {@@ -558,6 +568,26 @@ impl RelayClient {.map_err(|e| (Error::Relay(format!("bad relay response: {e}")), false))}+ /// `GET path`, tried again (twice, about a second in all) when the+ /// relay is briefly unreachable or overloaded. A read changes nothing,+ /// so sending it again is always safe.+ async fn get<T: serde::de::DeserializeOwned>(&self, path: &str, bearer: &str) -> Result<T> {+ let mut delay = READ_RETRY_BASE;+ let mut attempt = 0;+ loop {+ match self.send_once(self.http.get(self.url(path)), bearer).await {+ // Not a timeout: one that hung would hang again.+ Err((e, true)) if attempt < READ_RETRIES => {+ attempt += 1;+ tracing::debug!(attempt, path, "relay read failed, retrying: {e}");+ tokio::time::sleep(delay).await;+ delay *= 3;+ }+ r => return r.map_err(|(e, _)| e),+ }+ }+ }+/// One call with an optional JSON body (see [`RelayClient::send`]).pub(crate) async fn send_json<B: Serialize, T: serde::de::DeserializeOwned>(&self,@@ -775,19 +805,13 @@ impl RelayClient {/// Machines the account owns or that are shared with it.pub async fn machines(&self, account_token: &str) -> Result<Vec<Machine>> {- let list: MachineList = self- .send(self.http.get(self.url("/v1/machines")), account_token)- .await?;+ let list: MachineList = self.get("/v1/machines", account_token).await?;Ok(list.machines)}/// One machine (`credential` = account token or the machine token).pub async fn machine(&self, credential: &str, id: &str) -> Result<Machine> {- self.send(- self.http.get(self.url(&format!("/v1/machines/{id}"))),- credential,- )- .await+ self.get(&format!("/v1/machines/{id}"), credential).await}/// Renames / changes the allowlist / toggles sharing (owner).diff --git a/libs/cua/crates/cua-host/src/setup_tests.rs b/libs/cua/crates/cua-host/src/setup_tests.rsindex cdb839c7fb..381daeed6b 100644--- a/libs/cua/crates/cua-host/src/setup_tests.rs+++ b/libs/cua/crates/cua-host/src/setup_tests.rs@@ -93,6 +93,70 @@ async fn a_relay_briefly_unavailable_is_retried_until_it_registers() {assert_eq!(relay.register_calls(), 4);}+#[tokio::test]+async fn a_relay_hiccup_does_not_make_the_host_need_attention() {+ let relay = FakeRelay::start().await;+ relay.add_account("good", "user-1", None);+ let f = fixture();+ f.host()+ .setup(f.opts(&relay.url), &StaticToken("good".into()))+ .await+ .unwrap();+ // One or two 503s from the proxy in front of the relay: read again.+ relay.fail_reads(&[503, 503]);+ let status = f.host().status().await.unwrap();+ assert_eq!(status.error, None);+ assert!(status.sharing);+ // A deploy (every read 503 for a while): the relay's last answer.+ relay.set_reads_down(true);+ let status = f.host().status().await.unwrap();+ assert_eq!(status.error, None);+ assert!(status.sharing);+ // A refusal is not a hiccup: it shows at once.+ relay.set_reads_down(false);+ relay.fail_reads(&[500]);+ let status = f.host().status().await.unwrap();+ assert!(status.error.unwrap().contains("HTTP 500"));+}++#[tokio::test]+async fn a_relay_down_with_no_answer_to_fall_back_on_needs_attention() {+ let relay = FakeRelay::start().await;+ relay.add_account("good", "user-1", None);+ relay.set_reads_down(true);+ let f = fixture();+ // Setup registers (a POST); the status read after it has no answer yet.+ let status = f+ .host()+ .setup(f.opts(&relay.url), &StaticToken("good".into()))+ .await+ .unwrap();+ assert_eq!(+ status.error.as_deref(),+ Some("relay: HTTP 503: no available server")+ );+}++#[test]+fn relay_failures_that_pass_on_their_own_are_transient() {+ for (e, transient) in [+ (Error::Relay("HTTP 503: no available server".into()), true),+ (Error::Relay("HTTP 502: bad gateway".into()), true),+ (Error::Relay("HTTP 504: timeout".into()), true),+ (Error::Relay("HTTP 429: slow down".into()), true),+ (+ Error::Relay("http://127.0.0.1:1: error sending request".into()),+ true,+ ),+ (Error::Relay("HTTP 500: boom".into()), false),+ (Error::Relay("bad relay response: EOF".into()), false),+ (Error::Unauthenticated("relay: no".into()), false),+ (Error::NotFound("relay: no such machine".into()), false),+ ] {+ assert_eq!(e.is_transient(), transient, "{e}");+ }+}+#[tokio::test]async fn a_relay_that_stays_down_fails_at_register_with_its_status() {let relay = FakeRelay::start().await;diff --git a/libs/cua/crates/cua-host/src/testing.rs b/libs/cua/crates/cua-host/src/testing.rsindex d6e13703be..be8098c7f3 100644--- a/libs/cua/crates/cua-host/src/testing.rs+++ b/libs/cua/crates/cua-host/src/testing.rs@@ -73,6 +73,11 @@ struct State_ {/// Statuses the next machine registrations answer with, in order/// (a relay mid-deploy, a proxy in front of it).fail_register: std::collections::VecDeque<u16>,+ /// Statuses the next machine reads (GET) answer with, in order.+ fail_reads: std::collections::VecDeque<u16>,+ /// Every machine read answers 503, as the proxy in front of the+ /// relay does while it has no backend.+ reads_down: bool,/// Machine registrations received (including refused ones).register_calls: usize,/// machine id → `(path prefix, base URL)` its `/m/<id>/…` gRPC-Web@@ -475,8 +480,19 @@ async fn pairing_revoke(}}+/// A machine read the fake relay was told to fail (`fail_reads`,+/// `set_reads_down`), as the proxy in front of a relay answers.+fn failed_read(st: &mut State_) -> Option<Response> {+ let code = st.fail_reads.pop_front().or(st.reads_down.then_some(503))?;+ let status = StatusCode::from_u16(code).unwrap_or(StatusCode::SERVICE_UNAVAILABLE);+ Some((status, "no available server").into_response())+}+async fn list(State(s): State<S>, headers: HeaderMap) -> Response {- let st = s.lock().unwrap();+ let mut st = s.lock().unwrap();+ if let Some(r) = failed_read(&mut st) {+ return r;+ }if let Err(r) = st.gate(&headers) {return r;}@@ -520,7 +536,10 @@ fn fake_jwks() -> serde_json::Value {}async fn get_one(State(s): State<S>, headers: HeaderMap, Path(id): Path<String>) -> Response {- let st = s.lock().unwrap();+ let mut st = s.lock().unwrap();+ if let Some(r) = failed_read(&mut st) {+ return r;+ }match authorize(&st, &headers, &id, false) {Ok((m, _)) => Json(m).into_response(),Err(r) => r,@@ -1175,6 +1194,22 @@ impl FakeRelay {.extend(statuses.iter().copied());}+ /// The next machine reads (the list, or one machine) answer with+ /// `statuses`, in order, before the relay answers normally again.+ pub fn fail_reads(&self, statuses: &[u16]) {+ self.state+ .lock()+ .unwrap()+ .fail_reads+ .extend(statuses.iter().copied());+ }++ /// While `down`, every machine read answers 503 "no available server"+ /// (a relay deploy, as its proxy answers).+ pub fn set_reads_down(&self, down: bool) {+ self.state.lock().unwrap().reads_down = down;+ }+/// Machine registrations received so far (refused ones too).pub fn register_calls(&self) -> usize {self.state.lock().unwrap().register_callsdiff --git a/libs/cua/crates/cua-spaces/src/spaces.rs b/libs/cua/crates/cua-spaces/src/spaces.rsindex 4fd9e23b38..ca750e1c58 100644--- a/libs/cua/crates/cua-spaces/src/spaces.rs+++ b/libs/cua/crates/cua-spaces/src/spaces.rs@@ -818,7 +818,9 @@ impl Spaces {/// Refreshes the relay directory when an account is configured, then/// lists every Space. A failed refresh is an error, not an empty or- /// current directory, except when no account is signed in at all: that+ /// current directory (a brief relay hiccup lists the last directory+ /// for a while, see `relay_directory`), except when no account is+ /// signed in at all: that/// is the normal state of many hosts, so this machine's own Spaces are/// listed without the account's machines (and any listed before the/// sign-out are dropped). [`Self::list`] remains the cached, local read.@@ -969,6 +971,18 @@ impl Spaces {let machines = match read.await {Ok(m) => m,Err(_) if listed => return Ok(cached),+ // The relay briefly unreachable (a deploy, a moment with no+ // backend behind its proxy): the machines it listed a moment+ // ago stand, each with its own state, instead of failing the+ // whole Space list. Past the grace the failure shows.+ Err(Error::Relay(e))+ if e.is_transient()+ && !cached.is_empty()+ && read_at.is_some_and(|at| at.elapsed() < cua_host::RELAY_HICCUP_GRACE) =>+ {+ tracing::debug!("relay directory read failed; listing its last answer: {e}");+ return Ok(cached);+ }Err(e) => {return Err(Error::Relay(match e.tag() {"unauthenticated" => cua_host::Error::Unauthenticated(diff --git a/libs/cua/crates/cua-spaces/tests/relay.rs b/libs/cua/crates/cua-spaces/tests/relay.rsindex 739e12341b..161b3ef9c3 100644--- a/libs/cua/crates/cua-spaces/tests/relay.rs+++ b/libs/cua/crates/cua-spaces/tests/relay.rs@@ -586,3 +586,55 @@ async fn signed_out_lists_this_machines_spaces() {*tokens.token.lock().unwrap() = Some("owner".into());assert_eq!(spaces.list_all().await.unwrap().len(), 2);}++/// A relay deploy (the proxy in front of it answers 503 "no available+/// server" for a while) keeps the machines it listed a moment ago instead+/// of failing the whole Space list; with nothing listed before, or a+/// failure that is not a hiccup, the list fails as before.+#[tokio::test]+async fn a_relay_hiccup_lists_the_last_directory() {+ let relay = FakeRelay::start().await;+ relay.add_account("owner-token", "user-1", Some("[email protected]"));+ cua_host::RelayClient::new(&relay.url)+ .unwrap()+ .register(+ "owner-token",+ &cua_host::relay::RegisterRequest {+ id: MACHINE.into(),+ name: "studio-mac".into(),+ allow: vec![],+ host: None,+ meta: Default::default(),+ },+ )+ .await+ .unwrap();+ let account = || RelayAccount::new(&relay.url, Arc::new(StaticToken("owner-token".into())));+ let home = tempfile::tempdir().unwrap();+ let spaces = Spaces::builder().home(home.path()).relay(account()).build();+ assert_eq!(spaces.list_all().await.unwrap().len(), 1);++ relay.set_reads_down(true);+ let all = spaces.list_all().await.unwrap();+ assert_eq!(all.len(), 1);+ assert_eq!(all[0].id, format!("relay:{MACHINE}"));++ // Nothing listed before: the failure shows.+ let other = tempfile::tempdir().unwrap();+ let fresh = Spaces::builder()+ .home(other.path())+ .relay(account())+ .build();+ let err = fresh.list_all().await.unwrap_err();+ assert!(+ err.to_string()+ .contains("Could not refresh relay machines."),+ "{err}"+ );++ // Not a hiccup (a 500): the failure shows.+ relay.set_reads_down(false);+ relay.fail_reads(&[500]);+ assert!(spaces.list_all().await.is_err());+ assert_eq!(spaces.list_all().await.unwrap().len(), 1);+}