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
feat(spaces): relay counts connection outcomes (CUA-2231) (#5900)
cua-agents[bot]1ef93e74cf6b
diff --git a/libs/cua-spacesd/crates/cua-relay/README.md b/libs/cua-spacesd/crates/cua-relay/README.mdindex a49ea5a34a..19c9e2183e 100644--- a/libs/cua-spacesd/crates/cua-relay/README.md+++ b/libs/cua-spacesd/crates/cua-relay/README.md@@ -523,6 +523,14 @@ jobs), snapshots up to 64 MiB, keyrings 4 MiB, the rest 64 KiB.`cua_relay_pool_writes_refused_total{reason}`,`cua_relay_state_volume_bytes`, `cua_relay_state_volume_available_bytes`,`cua_relay_state_pool_reserve_bytes`.+ `cua_relay_connections_total{kind,outcome}` counts connection attempts+ for an availability SLO: `kind="machine"` (a computer opening its tunnel;+ `outcome` is `ok`, `rejected` for a caller-side refusal or `error` for a+ relay-side failure) and `kind="client"` (a request or stream forwarded to+ a computer; `outcome` is `ok`, including the computer's own 4xx and 5xx+ answers, `rejected`, `offline` when the computer is not connected, or+ `error` for a relay-side failure). No other label values exist, and all+ seven series are present from process start.- `GET /v1/info` keeps `state_writable` (false while a store is failing).**Log lines to alert on** (stable message and `alert` field):diff --git a/libs/cua-spacesd/crates/cua-relay/src/conn_metrics.rs b/libs/cua-spacesd/crates/cua-relay/src/conn_metrics.rsnew file mode 100644index 0000000000..fb780a519f--- /dev/null+++ b/libs/cua-spacesd/crates/cua-relay/src/conn_metrics.rs@@ -0,0 +1,214 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++//! Connection outcome counters for `/metrics` (`cua_relay_connections_total`).+//!+//! The only labels are the fixed `kind` and `outcome` sets below: never an+//! account, computer id, address, path or user agent. One middleware+//! classifies the final response of the two connection routes (a computer+//! opening its tunnel, and a request forwarded to a computer), so the exit+//! points of those handlers stay untouched. Responses the relay itself+//! produced carry a [`RelayStatus`] extension; anything else (a 101, or+//! the computer's own response) is a success for the relay.++use std::sync::atomic::{AtomicU64, Ordering};++use axum::http::StatusCode;+use axum::response::Response;++/// Which connection route handled the request. Set on the response by the+/// route's handler; other routes (health, API, share web) stay uncounted.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum Kind {+ Machine,+ Client,+}++/// The status of a response the relay generated itself (a refusal or an+/// internal failure), also when it is sent as a gRPC status over HTTP 200.+#[derive(Clone, Copy, Debug)]+pub(crate) struct RelayStatus(pub(crate) StatusCode);++/// A response of a connection route that is not a connection attempt+/// (an unrouted path, the share sign-in redirect and session exchange).+#[derive(Clone, Copy, Debug)]+pub(crate) struct Uncounted;++/// The target computer is not connected (a sleeping Mac, not a relay fault).+#[derive(Clone, Copy, Debug)]+pub(crate) struct Offline;++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum Outcome {+ Ok,+ Rejected,+ Offline,+ Error,+}++/// Classifies a finished response, or `None` when it is not a connection.+pub(crate) fn classify(response: &Response) -> Option<(Kind, Outcome)> {+ let ext = response.extensions();+ let kind = *ext.get::<Kind>()?;+ if ext.get::<Uncounted>().is_some() {+ return None;+ }+ let outcome = if ext.get::<Offline>().is_some() {+ Outcome::Offline+ } else {+ match ext.get::<RelayStatus>() {+ Some(RelayStatus(s)) if s.is_server_error() => Outcome::Error,+ Some(RelayStatus(s)) if s.is_client_error() => Outcome::Rejected,+ _ => Outcome::Ok,+ }+ };+ // A computer cannot be offline when it opens its own tunnel.+ let outcome = match (kind, outcome) {+ (Kind::Machine, Outcome::Offline) => Outcome::Error,+ (_, o) => o,+ };+ Some((kind, outcome))+}++/// Process-lifetime counters.+#[derive(Default)]+pub(crate) struct ConnMetrics {+ machine: [AtomicU64; 3],+ client: [AtomicU64; 4],+}++/// A label value and the outcome it stands for.+type Series = (&'static str, Outcome);++const MACHINE: [Series; 3] = [+ ("ok", Outcome::Ok),+ ("rejected", Outcome::Rejected),+ ("error", Outcome::Error),+];+const CLIENT: [Series; 4] = [+ ("ok", Outcome::Ok),+ ("rejected", Outcome::Rejected),+ ("offline", Outcome::Offline),+ ("error", Outcome::Error),+];++impl ConnMetrics {+ pub(crate) fn record(&self, kind: Kind, outcome: Outcome) {+ let (slots, table): (&[AtomicU64], &[Series]) = match kind {+ Kind::Machine => (&self.machine, &MACHINE),+ Kind::Client => (&self.client, &CLIENT),+ };+ if let Some(i) = table.iter().position(|(_, o)| *o == outcome) {+ slots[i].fetch_add(1, Ordering::Relaxed);+ }+ }++ /// Prometheus text, every series present from process start.+ pub(crate) fn render(&self) -> String {+ let mut out = String::from(+ "# HELP cua_relay_connections_total Connection attempts handled by the relay, by kind and outcome.\n\+ # TYPE cua_relay_connections_total counter\n",+ );+ let groups: [(&str, &[AtomicU64], &[Series]); 2] = [+ ("machine", &self.machine, &MACHINE),+ ("client", &self.client, &CLIENT),+ ];+ for (kind, slots, table) in groups {+ for (i, (name, _)) in table.iter().enumerate() {+ let n = slots[i].load(Ordering::Relaxed);+ out.push_str(&format!(+ "cua_relay_connections_total{{kind=\"{kind}\",outcome=\"{name}\"}} {n}\n"+ ));+ }+ }+ out+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use axum::body::Body;++ fn response(kind: Option<Kind>, status: Option<u16>, offline: bool, http: u16) -> Response {+ let mut r = Response::new(Body::empty());+ *r.status_mut() = StatusCode::from_u16(http).unwrap();+ if let Some(k) = kind {+ r.extensions_mut().insert(k);+ }+ if let Some(s) = status {+ r.extensions_mut()+ .insert(RelayStatus(StatusCode::from_u16(s).unwrap()));+ }+ if offline {+ r.extensions_mut().insert(Offline);+ }+ r+ }++ #[test]+ fn classifies_machine_connects() {+ let c = |s, h| classify(&response(Some(Kind::Machine), s, false, h));+ assert_eq!(c(None, 101), Some((Kind::Machine, Outcome::Ok)));+ for s in [400, 401, 403, 409, 429] {+ assert_eq!(c(Some(s), s), Some((Kind::Machine, Outcome::Rejected)));+ }+ assert_eq!(c(Some(500), 500), Some((Kind::Machine, Outcome::Error)));+ assert_eq!(c(Some(503), 503), Some((Kind::Machine, Outcome::Error)));+ }++ #[test]+ fn classifies_client_requests() {+ let c = |s, off, h| classify(&response(Some(Kind::Client), s, off, h));+ // The computer's own answers pass through and are not the relay's fault.+ assert_eq!(c(None, false, 200), Some((Kind::Client, Outcome::Ok)));+ assert_eq!(c(None, false, 404), Some((Kind::Client, Outcome::Ok)));+ assert_eq!(c(None, false, 500), Some((Kind::Client, Outcome::Ok)));+ for s in [400, 401, 403, 404, 429] {+ assert_eq!(+ c(Some(s), false, s),+ Some((Kind::Client, Outcome::Rejected))+ );+ }+ // gRPC refusals ride on HTTP 200 but keep the relay's own status.+ assert_eq!(+ c(Some(401), false, 200),+ Some((Kind::Client, Outcome::Rejected))+ );+ assert_eq!(+ c(Some(502), true, 502),+ Some((Kind::Client, Outcome::Offline))+ );+ for s in [500, 502, 503, 504] {+ assert_eq!(c(Some(s), false, s), Some((Kind::Client, Outcome::Error)));+ }+ }++ #[test]+ fn other_routes_are_not_counted() {+ let mut r = response(Some(Kind::Client), Some(404), false, 404);+ r.extensions_mut().insert(Uncounted);+ assert_eq!(classify(&r), None);+ assert_eq!(classify(&response(None, Some(401), false, 401)), None);+ assert_eq!(classify(&response(None, None, false, 200)), None);+ }++ #[test]+ fn renders_every_series_at_zero_and_counts() {+ let m = ConnMetrics::default();+ let text = m.render();+ assert_eq!(text.matches("cua_relay_connections_total{").count(), 7);+ assert!(text+ .lines()+ .filter(|l| !l.starts_with('#'))+ .all(|l| l.ends_with(" 0")));+ m.record(Kind::Client, Outcome::Offline);+ m.record(Kind::Machine, Outcome::Offline);+ let text = m.render();+ assert!(+ text.contains("{kind=\"client\",outcome=\"offline\"} 1"),+ "{text}"+ );+ assert!(!text.contains("machine\",outcome=\"offline"), "{text}");+ }+}diff --git a/libs/cua-spacesd/crates/cua-relay/src/lib.rs b/libs/cua-spacesd/crates/cua-relay/src/lib.rsindex 65d28c62b8..49eb03fbc4 100644--- a/libs/cua-spacesd/crates/cua-relay/src/lib.rs+++ b/libs/cua-spacesd/crates/cua-relay/src/lib.rs@@ -34,6 +34,7 @@ pub mod assertion;pub mod auth_log;pub mod client;pub mod clock;+mod conn_metrics;pub mod device_api;pub mod devices;pub mod directory;diff --git a/libs/cua-spacesd/crates/cua-relay/src/server.rs b/libs/cua-spacesd/crates/cua-relay/src/server.rsindex 841ca6c924..182dc5ba95 100644--- a/libs/cua-spacesd/crates/cua-relay/src/server.rs+++ b/libs/cua-spacesd/crates/cua-relay/src/server.rs@@ -375,6 +375,8 @@ pub struct Relay {pub(crate) storage: Arc<crate::storage::Storage>,/// Allowance metering.pub(crate) meter: Arc<Meter>,+ /// Connection outcome counters (`cua_relay_connections_total`).+ pub(crate) conns: Arc<crate::conn_metrics::ConnMetrics>,/// When this relay started (the reconnect grace counts from it).started: Instant,/// Share links: browser sign-in state and public-link rate limits.@@ -511,6 +513,7 @@ impl Relay {pool,storage,meter,+ conns: Arc::default(),started: Instant::now(),share: Arc::default(),};@@ -562,6 +565,10 @@ impl Relay {self.clone(),share_hosts,))+ .layer(axum::middleware::from_fn_with_state(+ self.clone(),+ count_connections,+ )).with_state(self.clone())}@@ -971,7 +978,11 @@ pub(crate) fn account_token(headers: &HeaderMap) -> Option<&str> {}pub(crate) fn text(status: StatusCode, message: impl Into<String>) -> Response {- (status, message.into()).into_response()+ let mut response = (status, message.into()).into_response();+ response+ .extensions_mut()+ .insert(crate::conn_metrics::RelayStatus(status));+ response}/// gRPC status codes the relay produces itself.@@ -1023,6 +1034,13 @@ fn refuse(let Some(content_type) = content_type else {return text(status, message);};+ // gRPC callers see HTTP 200; connection metrics keep the relay's status.+ let mark = |mut response: Response| {+ response+ .extensions_mut()+ .insert(crate::conn_metrics::RelayStatus(status));+ response+ };let encoded = percent_encode_grpc(&message);let details = {use base64::Engine as _;@@ -1035,6 +1053,7 @@ fn refuse(.header("grpc-message", encoded).header("grpc-status-details-bin", details).body(Body::empty())+ .map(mark).unwrap_or_else(|_| text(status, message))}@@ -1099,6 +1118,29 @@ fn percent_encode_grpc(message: &str) -> String {}async fn machine_connect(+ state: State<Relay>,+ headers: HeaderMap,+ upgrade: Result<WebSocketUpgrade, axum::extract::ws::rejection::WebSocketUpgradeRejection>,+) -> Response {+ let mut response = match upgrade {+ Ok(upgrade) => machine_connect_inner(state, headers, upgrade).await,+ // Not a WebSocket handshake: refused before the relay looks at it.+ Err(rejection) => {+ let mut response = rejection.into_response();+ let status = response.status();+ response+ .extensions_mut()+ .insert(crate::conn_metrics::RelayStatus(status));+ response+ }+ };+ response+ .extensions_mut()+ .insert(crate::conn_metrics::Kind::Machine);+ response+}++async fn machine_connect_inner(State(relay): State<Relay>,headers: HeaderMap,upgrade: WebSocketUpgrade,@@ -1305,6 +1347,7 @@ async fn metrics(State(relay): State<Relay>) -> Response {let mut text = tokio::task::spawn_blocking(move || storage.metrics()).await.unwrap_or_default();+ text.push_str(&relay.conns.render());#[cfg(feature = "hosted")]{text.push_str(&relay.org.metrics());@@ -1475,6 +1518,19 @@ fn client_ip(trusted: &crate::proxies::TrustedProxies, request: &Request) -> Strtrusted.client_ip(peer, xff).to_string()}+/// Counts each connection route's outcome (see `conn_metrics`).+async fn count_connections(+ State(relay): State<Relay>,+ request: Request,+ next: axum::middleware::Next,+) -> Response {+ let response = next.run(request).await;+ if let Some((kind, outcome)) = crate::conn_metrics::classify(&response) {+ relay.conns.record(kind, outcome);+ }+ response+}+/// Share origins never fall through to the relay's own routes: every path/// on `s<id>-<machine>.<domain>` belongs to the shared app.async fn share_hosts(@@ -1833,7 +1889,15 @@ async fn authorize_account_client(})}-async fn proxy(State(relay): State<Relay>, mut request: Request) -> Response {+async fn proxy(state: State<Relay>, request: Request) -> Response {+ let mut response = proxy_inner(state, request).await;+ response+ .extensions_mut()+ .insert(crate::conn_metrics::Kind::Client);+ response+}++async fn proxy_inner(State(relay): State<Relay>, mut request: Request) -> Response {let Some(Routed {id,forwarded,@@ -1845,12 +1909,17 @@ async fn proxy(State(relay): State<Relay>, mut request: Request) -> Response {Some(domain) => format!("use <computer-id>.{domain}/…"),None => "use /m/<computer-id>/…".to_owned(),};- return refuse(+ // Not a computer route (stray paths, scanners): not a connection.+ let mut response = refuse(request.headers(),StatusCode::NOT_FOUND,GrpcCode::NotFound,message,);+ response+ .extensions_mut()+ .insert(crate::conn_metrics::Uncounted);+ return response;};use crate::share_web::{Cookie, ShareKind};// The session endpoint of a private share origin: trades a login code@@ -1860,7 +1929,11 @@ async fn proxy(State(relay): State<Relay>, mut request: Request) -> Response {&& sh.kind == ShareKind::Private&& request.uri().path() == crate::share_web::SESSION_PATH{- return crate::share_web::session(&relay, &request);+ let mut response = crate::share_web::session(&relay, &request);+ response+ .extensions_mut()+ .insert(crate::conn_metrics::Uncounted);+ return response;}}// Only the relay mints assertions; device sessions are for the relay@@ -1956,7 +2029,11 @@ async fn proxy(State(relay): State<Relay>, mut request: Request) -> Response {.map(|p| p.as_str()).unwrap_or("/"));- return relay.share_login_redirect(&original);+ let mut response = relay.share_login_redirect(&original);+ response+ .extensions_mut()+ .insert(crate::conn_metrics::Uncounted);+ return response;}}},@@ -2011,12 +2088,16 @@ async fn proxy(State(relay): State<Relay>, mut request: Request) -> Response {None => relay.await_reconnect(&id).await,};let Some(machine) = machine else {- return refuse(+ let mut response = refuse(request.headers(),StatusCode::BAD_GATEWAY,GrpcCode::Unavailable,format!("computer {id:?} is not connected"),);+ response+ .extensions_mut()+ .insert(crate::conn_metrics::Offline);+ return response;};if machine.active.fetch_add(1, Ordering::SeqCst) >= relay.config.max_streams_per_machine {machine.active.fetch_sub(1, Ordering::SeqCst);diff --git a/libs/cua-spacesd/crates/cua-relay/tests/conn_metrics.rs b/libs/cua-spacesd/crates/cua-relay/tests/conn_metrics.rsnew file mode 100644index 0000000000..5016d287f2--- /dev/null+++ b/libs/cua-spacesd/crates/cua-relay/tests/conn_metrics.rs@@ -0,0 +1,183 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++//! `cua_relay_connections_total` on `/metrics` (CUA-2231): outcomes of+//! machine connects and forwarded client requests, with fixed labels only.++use std::time::Duration;++use cua_relay::{+ client::JoinConfig,+ server::{Relay, RelayConfig},+};+use tokio::net::TcpListener;+use tokio_util::sync::CancellationToken;++const TOKEN: &str = "machine-secret-canary";+const ID: &str = "metrics-machine";++async fn metrics(base: &str) -> String {+ reqwest::get(format!("{base}/metrics"))+ .await+ .unwrap()+ .text()+ .await+ .unwrap()+}++fn series(text: &str, kind: &str, outcome: &str) -> u64 {+ let key = format!("cua_relay_connections_total{{kind=\"{kind}\",outcome=\"{outcome}\"}} ");+ text.lines()+ .find_map(|l| l.strip_prefix(&key))+ .unwrap_or_else(|| panic!("missing {key}\n{text}"))+ .parse()+ .unwrap()+}++async fn start() -> (Relay, String, std::net::SocketAddr) {+ let relay = Relay::new(RelayConfig {+ tokens: vec![TOKEN.into()],+ ..RelayConfig::default()+ });+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let serving = relay.clone();+ tokio::spawn(async move { serving.serve(listener, std::future::pending()).await });+ (relay, format!("http://{addr}"), addr)+}++#[tokio::test]+async fn a_fresh_relay_renders_all_series_at_zero_with_fixed_labels() {+ let (_relay, base, _) = start().await;+ let text = metrics(&base).await;+ let lines: Vec<&str> = text+ .lines()+ .filter(|l| l.starts_with("cua_relay_connections_total{"))+ .collect();+ assert_eq!(lines.len(), 7, "{text}");+ assert!(text.contains("# TYPE cua_relay_connections_total counter"));+ for (kind, outcomes) in [+ ("machine", &["ok", "rejected", "error"][..]),+ ("client", &["ok", "rejected", "offline", "error"][..]),+ ] {+ for outcome in outcomes {+ assert_eq!(series(&text, kind, outcome), 0, "{text}");+ }+ }+ // Scraping /metrics itself is not a connection.+ assert_eq!(series(&metrics(&base).await, "client", "ok"), 0);+}++#[tokio::test]+async fn outcomes_are_counted_by_kind() {+ let (relay, base, addr) = start().await;+ let http = reqwest::Client::builder().no_proxy().build().unwrap();++ // Machine rejected: wrong token.+ let bad = tokio_tungstenite::connect_async(+ tokio_tungstenite::tungstenite::client::IntoClientRequest::into_client_request(format!(+ "ws://{addr}{}",+ cua_relay::CONNECT_PATH+ ))+ .map(|mut r| {+ r.headers_mut()+ .insert("authorization", "Bearer wrong-token".parse().unwrap());+ r.headers_mut()+ .insert(cua_relay::MACHINE_ID_HEADER, ID.parse().unwrap());+ r+ })+ .unwrap(),+ )+ .await;+ assert!(bad.is_err());++ // Machine rejected: not a WebSocket handshake. Unrouted paths are not counted.+ let r = http+ .get(format!("{base}{}", cua_relay::CONNECT_PATH))+ .header(cua_relay::MACHINE_ID_HEADER, ID)+ .bearer_auth(TOKEN)+ .send()+ .await+ .unwrap();+ assert!(r.status().is_client_error());+ assert_eq!(+ http.get(format!("{base}/favicon.ico"))+ .send()+ .await+ .unwrap()+ .status(),+ 404+ );++ let text = metrics(&base).await;+ assert_eq!(series(&text, "machine", "rejected"), 2, "{text}");+ assert_eq!(series(&text, "client", "rejected"), 0, "{text}");+ assert_eq!(series(&text, "client", "ok"), 0, "{text}");++ // Machine ok and client ok (the computer's own 404 passes through as ok).+ let local = TcpListener::bind("127.0.0.1:0").await.unwrap();+ let local_addr = local.local_addr().unwrap();+ let local_task = tokio::spawn(async move {+ axum::serve(+ local,+ axum::Router::new().route("/health", axum::routing::get(|| async { "fine" })),+ )+ .await+ .unwrap();+ });+ let config = JoinConfig::new(+ base.replace("http://", "ws://"),+ TOKEN.into(),+ ID.into(),+ local_addr,+ );+ let stop = CancellationToken::new();+ let stopped = stop.clone();+ let join = tokio::spawn(async move { cua_relay::client::session(&config, &stopped).await });+ tokio::time::timeout(Duration::from_secs(5), async {+ while !relay.machine_ids().contains(&ID.to_string()) {+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ })+ .await+ .expect("machine never came online");+ // Client rejected: no credential. Client offline: nobody is connected as this id.+ let r = http+ .get(format!("{base}/m/{ID}/data"))+ .send()+ .await+ .unwrap();+ assert_eq!(r.status(), 401);+ let r = http+ .get(format!("{base}/m/other-machine/health"))+ .bearer_auth(TOKEN)+ .send()+ .await+ .unwrap();+ assert_eq!(r.status(), 502);+ for (path, status) in [("health", 200), ("missing", 404)] {+ let r = http+ .get(format!("{base}/m/{ID}/{path}"))+ .bearer_auth(TOKEN)+ .send()+ .await+ .unwrap();+ assert_eq!(r.status(), status);+ }++ let text = metrics(&base).await;+ assert_eq!(series(&text, "machine", "ok"), 1, "{text}");+ assert_eq!(series(&text, "client", "ok"), 2, "{text}");+ assert_eq!(series(&text, "client", "rejected"), 1, "{text}");+ assert_eq!(series(&text, "client", "offline"), 1, "{text}");+ assert_eq!(series(&text, "client", "error"), 0, "{text}");+ for line in text+ .lines()+ .filter(|l| l.starts_with("cua_relay_connections_total{"))+ {+ assert!(!line.contains(ID) && !line.contains("127.0.0.1"), "{line}");+ }+ stop.cancel();+ let _ = join.await;+ local_task.abort();+}