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(telemetry): record agent runs from every entry point (#4497)
ddupont66e0b6652fc4
diff --git a/docs/content/docs/cua-sdk/concepts/telemetry-events.mdx b/docs/content/docs/cua-sdk/concepts/telemetry-events.mdxindex 767e755e24..f31d9b82b0 100644--- a/docs/content/docs/cua-sdk/concepts/telemetry-events.mdx+++ b/docs/content/docs/cua-sdk/concepts/telemetry-events.mdx@@ -27,7 +27,8 @@ Every event carries: `telemetry_schema_version`, `event_version`, `product`| `cua_spaces_feature_used` | `feature` (a fixed Spaces app feature) | Spaces app feature adoption. || `cua_stream_stats` | `transport`, `codec`, `decode` (`hw` or `sw`), `fps_bucket`, `latency_bucket`, `resolution`, `duration_bucket` | Streaming performance (50% sampled). || `cua_onboarding_step` | `step`, `outcome` | Install and onboarding funnel. |-| `cua_agent_run_completed` | `harness` (cua-agents id), `location`, `outcome`, `error_kind`, `duration_bucket` | Which agent harnesses run and how reliably. |+| `cua_agent_run_started` | `harness` (cua-agents id or `other`), `location`, `entry` (`spaces_tool`, `cli`, `sdk`, `persistent`, `routine`), `outcome`, `error_kind` | Agent runs started, and failed starts. |+| `cua_agent_run_completed` | `harness`, `location`, `entry`, `outcome`, `error_kind`, `duration_bucket` | First agent run, and how reliably runs finish. Once per run. || `cua_bench_run_completed` | `taskset` (cua-bench dataset or `custom`), `score_bucket`, `task_count`, `outcome` | Benchmark use and coarse scores. || `cua_daemon_started` | `mode`, `outcome` | Daemon startup reliability. || `cua_daemon_health` | `uptime_bucket`, `sandboxes` | Hourly aggregate health. |diff --git a/docs/content/docs/cua-sdk/concepts/telemetry.mdx b/docs/content/docs/cua-sdk/concepts/telemetry.mdxindex 6a7290773c..e705f35831 100644--- a/docs/content/docs/cua-sdk/concepts/telemetry.mdx+++ b/docs/content/docs/cua-sdk/concepts/telemetry.mdx@@ -85,7 +85,14 @@ app launched (`cua_onboarding_step` `app_launched`), first run completed(`onboarding_completed`), signed in (`signed_in`), first Space created(`first_space_created`), first Space ready (`first_space_ready`), firstteleport (`first_teleport`) and first agent run (`first_agent_run`). The-`first_*` steps are sent once per install. Retention counts installs with a+`first_*` steps are sent once per install.++An agent run is counted by the install that started it: once when it+starts, and once when any Cua program of that install first sees its first+turn end, fail or stop. Until then a marker with the same fixed words waits+in `~/.cua/telemetry/agent_runs/` (dropped after 7 days). Cua programs+inside an agent run (`CUA_AGENT_RUN_ID` set) record no agent runs, so a+Space never counts as an install. Retention counts installs with a`cua_app_active` event on day 1, 7 and 30 after their first one.## Never collecteddiff --git a/docs/content/docs/cua-sdk/reference/rust/cua-sandbox-core.mdx b/docs/content/docs/cua-sdk/reference/rust/cua-sandbox-core.mdxindex c296fb797f..09354863bd 100644--- a/docs/content/docs/cua-sdk/reference/rust/cua-sandbox-core.mdx+++ b/docs/content/docs/cua-sdk/reference/rust/cua-sandbox-core.mdx@@ -1453,7 +1453,7 @@ pub fn pool_image(image: &str) -> Option<&str>/// Pool `pool`'s template image as an ...pub async fn pool_image_info(fleet: &FleetClient, pool: &str, creds: Option<&RegistryCredentials>) -> Result<Option<ImageInfo>>/// Deletes the runtimes cua set up itself ...-pub fn remove_builtin_runtimes() -> Result<(), String>+pub async fn remove_builtin_runtimes() -> Result<(), String>// mod byoc/// The error a cloud word without a ...@@ -1612,7 +1612,7 @@ pub const DEFAULT_PATH: &str = "/mcp";// mod settings/// Every setting, in display order.-pub const KEYS: [Key; 8] = _;+pub const KEYS: [Key; 9] = _;```## Type aliasesdiff --git a/docs/content/docs/cua-sdk/reference/rust/cua-spaces-agents-mcp.mdx b/docs/content/docs/cua-sdk/reference/rust/cua-spaces-agents-mcp.mdxindex f512c1952f..501c961ce4 100644--- a/docs/content/docs/cua-sdk/reference/rust/cua-spaces-agents-mcp.mdx+++ b/docs/content/docs/cua-sdk/reference/rust/cua-spaces-agents-mcp.mdx@@ -17,6 +17,7 @@ More of this crate: [registry and primitives](/cua-sdk/reference/rust/cua-spaces## Modules- `agents`: Coding agents inside a Space: `cua_agents` over the ...+- `agents::telemetry`: Agent-run telemetry: the host install that starts a run ...- `mcp`: The Spaces MCP server: the contract's tools over ...- `mcp::codes`: JSON-RPC error codes.- `mcp::http`: MCP streamable HTTP: `POST /mcp` with a JSON-RPC body ...@@ -113,6 +114,22 @@ pub fn env_from_host(names: &[String]) -> Result<(BTreeMap<String, String>, Vec</// The provider key variables a host may ...pub fn forwardable_env() -> Vec<&'static str>+// mod agents::telemetry+/// Before stopping `run_id`: records an ...+pub async fn before_stop(agents: &Agents, run_id: &str)+/// The error variant of `e` (never its ...+pub fn error_variant(e: &Error) -> &'static str+/// A run's status was read: records its ...+pub fn observe(info: &RunInfo)+/// Starting a run failed.+pub fn start_failed(harness: &str, space: &str, entry: &str, e: &Error)+/// A run was started from `entry` in the ...+pub fn started(agents: &Agents, space: &str, entry: &str, s: &Started)+/// A run was stopped before its first turn ...+pub fn stopped(run_id: &str)+/// Follows `run_id` in the background ...+pub fn watch(agents: Agents, run_id: String)+// mod mcp/// Runs a Space-scoped contract tool ...pub async fn call_on(space: &Space, tool: &str, arguments: Value) -> ToolOutcome@@ -133,6 +150,10 @@ pub async fn serve_process_stdio(server: McpServer) -> Result<()>## Constants```rust+// mod agents::telemetry+/// How long a watcher follows a run before ...+pub const WATCH_FOR: Duration = _;+// mod mcp/// Server instructions sent in ...pub const INSTRUCTIONS: &str = /* ... */;diff --git a/libs/cua/crates/cua-agents/src/runs.rs b/libs/cua/crates/cua-agents/src/runs.rsindex 2bb30d0d77..93a859556b 100644--- a/libs/cua/crates/cua-agents/src/runs.rs+++ b/libs/cua/crates/cua-agents/src/runs.rs@@ -676,6 +676,7 @@ impl Agents {let mut s = format!("#!/bin/sh\n# cua agent run launcher (generated)\numask 077\ncd {q} || exit 1\n\export CUA_EVENTS_FILE={q}/events.jsonl\n\+ export CUA_AGENT_RUN_ID=\"$(basename {q})\"\n\cua_state() {{ printf '{{\"status\":\"%s\",\"error\":%s,\"turn\":0}}' \"$1\" \"$2\" > {q}/.state.tmp && mv {q}/.state.tmp {q}/state.json; }}\n\cua_event() {{ n=$(( $(wc -l < {q}/events.jsonl 2>/dev/null || echo 0) + 1 )); \printf '{{\"seq\":%s,\"ts\":%s000,\"turn\":0,\"type\":\"%s\",\"message\":\"%s\"}}\\n' \"$n\" \"$(date +%s)\" \"$1\" \"$2\" >> {q}/events.jsonl; }}\n\@@ -1402,6 +1403,32 @@ mod tests {assert!(r.usage.is_some());}+ /// Every run's environment names the run, so a Cua program inside it+ /// records no agent runs of its own (the host that started it does).+ #[test]+ fn launch_script_names_the_run() {+ let s = Agents::launch_script(+ "/root",+ &harness::HARNESSES[0],+ "/root/.cua/agents/run-1a2b3c4d",+ "/root/.cua/tools/cua-runner/x",+ false,+ None,+ &[],+ )+ .unwrap();+ let line = s+ .lines()+ .find(|l| l.starts_with("export CUA_AGENT_RUN_ID="))+ .expect("exported");+ let out = std::process::Command::new("/bin/sh")+ .arg("-c")+ .arg(format!("{line}; printf %s \"$CUA_AGENT_RUN_ID\""))+ .output()+ .unwrap();+ assert_eq!(String::from_utf8_lossy(&out.stdout), "run-1a2b3c4d");+ }+/// The launcher is valid shell and never embeds a secret.#[test]fn launch_scripts_parse() {diff --git a/libs/cua/crates/cua-sdk/src/native/agents.rs b/libs/cua/crates/cua-sdk/src/native/agents.rsindex 30defff534..a383f1fe44 100644--- a/libs/cua/crates/cua-sdk/src/native/agents.rs+++ b/libs/cua/crates/cua-sdk/src/native/agents.rs@@ -376,12 +376,44 @@ pub struct AgentArtifact {#[derive(uniffi::Object)]pub struct Agents {inner: ca::Agents,+ /// The sandbox's location word (`local`, `cloud`, ...), for telemetry.+ location: String,}impl Agents {- pub(crate) async fn over(guest: cua_spacesd_client::SpacesdClient) -> Result<Arc<Agents>> {+ pub(crate) async fn over(+ guest: cua_spacesd_client::SpacesdClient,+ location: &str,+ ) -> Result<Arc<Agents>> {let inner = run(async move { Ok(ca::Agents::new(guest).await?) }).await?;- Ok(Arc::new(Agents { inner }))+ Ok(Arc::new(Agents {+ inner,+ location: location.to_string(),+ }))+ }+}++// Agent-run telemetry (`cua_telemetry::agent_runs`): this install records+// the runs it starts, and the end of each once, when any status read here+// (or by another Cua program of this install) first sees it.++/// Where a run was started from: the `cua agent` CLI or an SDK.+fn entry() -> &'static str {+ if cua_telemetry::global().product() == "cli" {+ "cli"+ } else {+ "sdk"+ }+}++/// Records the end of `info` if this install started it and it ended.+fn observe(info: &ca::RunInfo) {+ if let Some((outcome, variant)) = cua_telemetry::events::agent_run_end(+ info.status.as_str(),+ info.stop_reason.as_deref(),+ info.error.is_some(),+ ) {+ cua_telemetry::global().agent_run_finished(&info.run_id, outcome, variant);}}@@ -480,14 +512,42 @@ impl Agents {options: Option<AgentRunOptions>,) -> Result<Arc<AgentRun>> {let inner = self.inner.clone();- let opts = run_options(options.unwrap_or_default())?;- let started = run(async move { Ok(inner.start(&harness, &prompt, opts).await?) }).await?;+ let opts = match run_options(options.unwrap_or_default()) {+ Ok(o) => o,+ Err(e) => {+ cua_telemetry::global().agent_run_start_failed(+ &harness,+ &self.location,+ entry(),+ Some(e.variant()),+ );+ return Err(e);+ }+ };+ let h = harness.clone();+ let started = run(async move { Ok(inner.start(&h, &prompt, opts).await?) }).await;+ let started = match started {+ Ok(s) => s,+ Err(e) => {+ cua_telemetry::global().agent_run_start_failed(+ &harness,+ &self.location,+ entry(),+ Some(e.variant()),+ );+ return Err(e);+ }+ };+ cua_telemetry::global().agent_run_started(+ &started.run_id,+ &started.harness,+ &self.location,+ entry(),+ );Ok(Arc::new(AgentRun {inner: self.inner.clone(),run_id: started.run_id,harness: started.harness,- started: std::time::Instant::now(),- recorded: Default::default(),}))}@@ -496,19 +556,23 @@ impl Agents {let inner = self.inner.clone();let id = run_id.clone();let info = run(async move { Ok(inner.status(&id).await?) }).await?;+ observe(&info);Ok(Arc::new(AgentRun {inner: self.inner.clone(),run_id,harness: info.harness.unwrap_or_default(),- started: std::time::Instant::now(),- recorded: Default::default(),}))}/// Every run in the sandbox, newest first.pub async fn list(&self) -> Result<Vec<AgentRunInfo>> {let inner = self.inner.clone();- run(async move { Ok(inner.list().await?.into_iter().map(Into::into).collect()) }).await+ run(async move {+ let runs = inner.list().await?;+ runs.iter().for_each(observe);+ Ok(runs.into_iter().map(Into::into).collect())+ })+ .await}/// Installs harnesses or apps (`["claude-code", "blender"]`: harness@@ -539,11 +603,6 @@ pub struct AgentRun {inner: ca::Agents,run_id: String,harness: String,- /// When this handle was made (the duration bucket of- /// `cua_agent_run_completed`).- started: std::time::Instant,- /// `cua_agent_run_completed` was recorded for this handle.- recorded: std::sync::atomic::AtomicBool,}#[uniffi::export]@@ -558,7 +617,12 @@ impl AgentRun {pub async fn status(&self) -> Result<AgentRunInfo> {let (a, id) = (self.inner.clone(), self.run_id.clone());- run(async move { Ok(a.status(&id).await?.into()) }).await+ run(async move {+ let info = a.status(&id).await?;+ observe(&info);+ Ok(info.into())+ })+ .await}/// Events after `cursor` (0: from the start), at most `max`.@@ -591,13 +655,37 @@ impl AgentRun {/// Stops the run and verifies its process is gone.pub async fn stop(&self) -> Result<AgentRunInfo> {let (a, id) = (self.inner.clone(), self.run_id.clone());- run(async move { Ok(a.stop(&id).await?.into()) }).await+ run(async move {+ // An end it already reached is not a cancel.+ if cua_telemetry::global().agent_run_pending(&id)+ && let Ok(info) = a.status(&id).await+ {+ observe(&info);+ }+ let info = a.stop(&id).await?;+ cua_telemetry::global().agent_run_finished(+ &id,+ cua_telemetry::Outcome::Cancelled,+ None,+ );+ Ok(info.into())+ })+ .await}/// The last turn's outcome.pub async fn result(&self) -> Result<AgentRunResult> {let (a, id) = (self.inner.clone(), self.run_id.clone());- run(async move { Ok(a.result(&id).await?.into()) }).await+ run(async move {+ let r = a.result(&id).await?;+ if r.status != ca::RunStatus::Running+ && let Ok(info) = a.status(&id).await+ {+ observe(&info);+ }+ Ok(r.into())+ })+ .await}/// Waits until no turn is running (at most `timeout_ms`), then returns@@ -605,32 +693,15 @@ impl AgentRun {pub async fn wait(&self, timeout_ms: Option<u64>) -> Result<AgentRunResult> {let (a, id) = (self.inner.clone(), self.run_id.clone());let t = Duration::from_millis(timeout_ms.unwrap_or(30 * 60 * 1000));- let r: Result<AgentRunResult> = run(async move { Ok(a.wait(&id, t).await?.into()) }).await;- // Once per handle: the harness id (cua-agents catalog, else- // `other`), outcome, error category and a duration bucket.- if !self- .recorded- .swap(true, std::sync::atomic::Ordering::SeqCst)- {- let (outcome, variant) = match &r {- Ok(res) if res.error.is_none() => (cua_telemetry::Outcome::Ok, None),- Ok(_) => (cua_telemetry::Outcome::Error, None),- Err(e) => (cua_telemetry::Outcome::Error, Some(e.variant())),- };- cua_telemetry::capture(cua_telemetry::events::agent_run_completed(- &self.harness,- "",- outcome,- variant,- self.started.elapsed(),- ));- // Activation: the first agent run that finished cleanly on- // this install.- if outcome == cua_telemetry::Outcome::Ok {- cua_telemetry::global().capture_step("first_agent_run", outcome);+ run(async move {+ let r = a.wait(&id, t).await?;+ // `wait` returns once the run is not running: read that status.+ if let Ok(info) = a.status(&id).await {+ observe(&info);}- }- r+ Ok(r.into())+ })+ .await}/// Files the run created or changed in its working directory.@@ -661,6 +732,6 @@ impl AgentRun {impl SpacesdClient {/// Coding agents in this guest.pub async fn agents(&self) -> Result<Arc<Agents>> {- Agents::over(self.client.clone()).await+ Agents::over(self.client.clone(), &self.location).await}}diff --git a/libs/cua/crates/cua-sdk/src/native/host.rs b/libs/cua/crates/cua-sdk/src/native/host.rsindex 2a4412b7e7..33a57ebe8a 100644--- a/libs/cua/crates/cua-sdk/src/native/host.rs+++ b/libs/cua/crates/cua-sdk/src/native/host.rs@@ -176,7 +176,7 @@ impl Relay {let o = cua_spacesd_client::ConnectOptions::parse(&url)?.fleet_gateway(Arc::new(cua_spacesd_client::StaticBearer(token)), None);let client = cua_spacesd_client::SpacesdClient::connect(o).await?;- Ok(Arc::new(SpacesdClient::new(client, vec![])))+ Ok(Arc::new(SpacesdClient::new(client, vec![]).at("relay")))}).await}diff --git a/libs/cua/crates/cua-sdk/src/native/sandbox.rs b/libs/cua/crates/cua-sdk/src/native/sandbox.rsindex 969546ac73..be9ded0b55 100644--- a/libs/cua/crates/cua-sdk/src/native/sandbox.rs+++ b/libs/cua/crates/cua-sdk/src/native/sandbox.rs@@ -1310,13 +1310,14 @@ impl Sandbox {pub async fn spacesd(&self, probe_timeout_ms: Option<u32>) -> Result<Arc<SpacesdClient>> {let backend = self.backend.clone();let name = self.info.id.clone();+ let location = self.info.location.clone();let timeout = probe_timeout_ms.map(super::millis);run(async move {match &backend {Backend::Embedded(rt) => {let a = rt.env(&name, timeout).await?;let fleet = !a.ws_headers.is_empty();- let client = SpacesdClient::new(a.client, a.ws_headers);+ let client = SpacesdClient::new(a.client, a.ws_headers).at(&location);if !fleet {return Ok(Arc::new(client));}@@ -1337,10 +1338,13 @@ impl Sandbox {.probe(false);o.token = Some(ep.token.clone());let client = cua_spacesd_client::SpacesdClient::connect(o).await?;- Ok(Arc::new(SpacesdClient::new(- client,- vec![("authorization".into(), format!("Bearer {}", ep.token))],- )))+ Ok(Arc::new(+ SpacesdClient::new(+ client,+ vec![("authorization".into(), format!("Bearer {}", ep.token))],+ )+ .at(&location),+ ))}}})@@ -1410,7 +1414,7 @@ impl Sandbox {/// results; runs outlive this handle.pub async fn agents(&self) -> Result<Arc<super::Agents>> {let guest = self.spacesd(None).await?;- super::Agents::over(guest.client.clone()).await+ super::Agents::over(guest.client.clone(), &self.info.location).await}/// A named service (for example `"server"` or `"env"`).diff --git a/libs/cua/crates/cua-sdk/src/native/spacesd.rs b/libs/cua/crates/cua-sdk/src/native/spacesd.rsindex 7ae374b88c..a56e5355a0 100644--- a/libs/cua/crates/cua-sdk/src/native/spacesd.rs+++ b/libs/cua/crates/cua-sdk/src/native/spacesd.rs@@ -383,6 +383,9 @@ pub struct SpacesdClient {/// Fresh headers at use (cloud Spaces); `None` when they never expire.#[cfg_attr(not(feature = "media"), allow(dead_code))]pub(crate) ws_refresh: Option<WsHeaderRefresh>,+ /// Where the spacesd runs (`local`, `cloud`, `direct`, `relay`), for+ /// agent-run telemetry. `direct` (reached by address) unless set.+ pub(crate) location: String,}impl SpacesdClient {@@ -394,9 +397,16 @@ impl SpacesdClient {client,ws_headers,ws_refresh: None,+ location: "direct".into(),}}+ /// The same client, recorded as running at `location`.+ pub(crate) fn at(mut self, location: &str) -> Self {+ self.location = location.to_string();+ self+ }+/// A client whose WebSocket headers are re-minted by `refresh` each time/// a socket is opened (a cloud Space's Fleet bearer).pub(crate) fn with_ws_refresh(mut self, refresh: WsHeaderRefresh) -> Self {diff --git a/libs/cua/crates/cua-spaces-ext/src/persistent/mod.rs b/libs/cua/crates/cua-spaces-ext/src/persistent/mod.rsindex 9882cdec9f..3f4bea976c 100644--- a/libs/cua/crates/cua-spaces-ext/src/persistent/mod.rs+++ b/libs/cua/crates/cua-spaces-ext/src/persistent/mod.rs@@ -520,6 +520,12 @@ impl Persistent {/// the home, and starts the harness with its memory in the home and/// the bridge attached.pub async fn start(&self, name: &str, prompt: &str) -> Result<Delivery> {+ self.start_from(name, prompt, "persistent").await+ }++ /// [`Self::start`], recording `entry` (`persistent` or `routine`) as+ /// where the run was started from.+ async fn start_from(&self, name: &str, prompt: &str, entry: &str) -> Result<Delivery> {let rec = self.get(name)?;if rec.paused {return Err(Error::Agent(format!(@@ -576,10 +582,15 @@ impl Persistent {).await;let started = match started {- Ok(s) => s,+ Ok(s) => {+ cua_spaces::agents::telemetry::started(&agents, &rec.space, entry, &s);+ s+ }Err(e) => {self.release_lease(name).await;- return Err(e.into());+ let e = Error::from(e);+ cua_spaces::agents::telemetry::start_failed(&rec.harness, &rec.space, entry, &e);+ return Err(e);}};self.update(name, |r| {@@ -599,6 +610,11 @@ impl Persistent {/// the home restored) when it has none. Refused while a turn runs or/// while paused.pub async fn send(&self, name: &str, text: &str) -> Result<Delivery> {+ self.send_from(name, text, "persistent").await+ }++ /// [`Self::send`], recording `entry` for a run it starts.+ async fn send_from(&self, name: &str, text: &str, entry: &str) -> Result<Delivery> {let rec = self.get(name)?;if rec.paused {return Err(Error::Agent(format!("{name} is paused")));@@ -627,7 +643,7 @@ impl Persistent {_ => {}}}- self.start(name, text).await+ self.start_from(name, text, entry).await}async fn stop_run(&self, rec: &AgentRecord) -> Result<Option<String>> {@@ -635,7 +651,9 @@ impl Persistent {return Ok(None);};let agents = self.agents_for(&rec.space).await?;+ cua_spaces::agents::telemetry::before_stop(&agents, run).await;agents.stop(run).await?;+ cua_spaces::agents::telemetry::stopped(run);Ok(Some(run.clone()))}@@ -1045,6 +1063,7 @@ impl Persistent {}self.update(&rec.name, |r| r.saved_turn = turn)?;}+ let run_failed = failed.is_some();if let Some(err) = failed&& page.cursor > rec.cursor&& rec.notify@@ -1059,6 +1078,13 @@ impl Persistent {)?;report.notified += 1;}+ // Agent-run telemetry: the end of a run this install started.+ if (!ended.is_empty() || run_failed)+ && cua_telemetry::global().agent_run_pending(&run)+ && let Ok(info) = agents.status(&run).await+ {+ cua_spaces::agents::telemetry::observe(&info);+ }if page.cursor != rec.cursor {let cursor = page.cursor;self.update(&rec.name, |r| r.cursor = cursor)?;@@ -1087,7 +1113,11 @@ impl RoutineRunner for Runner {};}}- match self.0.send(&routine.bot_id, &routine.turn_text()).await {+ match self+ .0+ .send_from(&routine.bot_id, &routine.turn_text(), "routine")+ .await+ {Ok(d) => RoutineFiring::Started { run_id: d.run_id },Err(Error::Agent(m)) if m.contains("middle of a turn") => {RoutineFiring::Refused { reason: m }diff --git a/libs/cua/crates/cua-spaces/src/agents/mod.rs b/libs/cua/crates/cua-spaces/src/agents/mod.rsindex ac93d2b261..c0d2aee238 100644--- a/libs/cua/crates/cua-spaces/src/agents/mod.rs+++ b/libs/cua/crates/cua-spaces/src/agents/mod.rs@@ -48,6 +48,116 @@ impl Space {}}+/// Agent-run telemetry: the host install that starts a run records it+/// (`cua_agent_run_started`, then `cua_agent_run_completed` once, and+/// `first_agent_run`); see [`cua_telemetry::agent_runs`]. Only fixed words+/// leave: the harness id, the location word of the Space id, the entry+/// point, an outcome and an error category.+pub mod telemetry {+ use super::{Agents, RunInfo, Started};+ use crate::error::Error;+ use cua_telemetry::Outcome;+ use std::time::Duration;++ /// How long a watcher follows a run before leaving its end to the next+ /// status read.+ pub const WATCH_FOR: Duration = Duration::from_secs(2 * 3600);++ /// The error variant of `e` (never its message).+ pub fn error_variant(e: &Error) -> &'static str {+ match e {+ Error::InvalidArgument(_) => "InvalidArgument",+ Error::NotFound(_) => "NotFound",+ Error::SpacesdNotAvailable { .. } => "SpacesdNotAvailable",+ Error::CapabilityMissing { .. } => "CapabilityMissing",+ Error::HostCapabilityMissing { .. } => "HostCapabilityMissing",+ Error::Agent(_) => "Agent",+ Error::Timeout(_) => "Timeout",+ Error::Env(_) => "Env",+ Error::Fleet(_) => "Fleet",+ Error::Cancelled(_) => "Cancelled",+ _ => "Other",+ }+ }++ /// A run was started from `entry` in the Space `space` (its id, such as+ /// `local:dev`; only the location word is kept). In a process with a+ /// Tokio runtime a watcher records its end.+ pub fn started(agents: &Agents, space: &str, entry: &str, s: &Started) {+ let t = cua_telemetry::global();+ t.agent_run_started(&s.run_id, &s.harness, space, entry);+ if t.agent_run_pending(&s.run_id) {+ watch(agents.clone(), s.run_id.clone());+ }+ }++ /// Starting a run failed.+ pub fn start_failed(harness: &str, space: &str, entry: &str, e: &Error) {+ cua_telemetry::global().agent_run_start_failed(+ harness,+ space,+ entry,+ Some(error_variant(e)),+ );+ }++ /// A run's status was read: records its end if this install started it+ /// and it has ended.+ pub fn observe(info: &RunInfo) {+ if let Some((outcome, variant)) = cua_telemetry::events::agent_run_end(+ info.status.as_str(),+ info.stop_reason.as_deref(),+ info.error.is_some(),+ ) {+ cua_telemetry::global().agent_run_finished(&info.run_id, outcome, variant);+ }+ }++ /// Before stopping `run_id`: records an end it already reached, so the+ /// stop is not taken for a cancel.+ pub async fn before_stop(agents: &Agents, run_id: &str) {+ if cua_telemetry::global().agent_run_pending(run_id)+ && let Ok(info) = agents.status(run_id).await+ {+ observe(&info);+ }+ }++ /// A run was stopped before its first turn ended (if it had ended, its+ /// end is already recorded and this does nothing).+ pub fn stopped(run_id: &str) {+ cua_telemetry::global().agent_run_finished(run_id, Outcome::Cancelled, None);+ }++ /// Follows `run_id` in the background until it ends (at most+ /// [`WATCH_FOR`]), polling gently. A no-op without a Tokio runtime or+ /// when nothing is pending; a process that exits first leaves the end+ /// to the next status read of this install.+ pub fn watch(agents: Agents, run_id: String) {+ let Ok(rt) = tokio::runtime::Handle::try_current() else {+ return;+ };+ rt.spawn(async move {+ let t = cua_telemetry::global();+ let deadline = tokio::time::Instant::now() + WATCH_FOR;+ let mut every = Duration::from_secs(3);+ while tokio::time::Instant::now() < deadline && t.agent_run_pending(&run_id) {+ tokio::time::sleep(every).await;+ every = (every * 2).min(Duration::from_secs(30));+ match agents.status(&run_id).await {+ Ok(info) => observe(&info),+ // The run directory is gone (removed): nothing to wait for.+ Err(cua_agents::Error::NotFound(_)) => {+ stopped(&run_id);+ return;+ }+ Err(_) => {}+ }+ }+ });+ }+}+/// `agent_capabilities`.#[derive(Clone, Debug, serde::Serialize)]pub struct CapabilitiesReport {diff --git a/libs/cua/crates/cua-spaces/src/mcp/tools.rs b/libs/cua/crates/cua-spaces/src/mcp/tools.rsindex 6a50df1244..e8a2748a8f 100644--- a/libs/cua/crates/cua-spaces/src/mcp/tools.rs+++ b/libs/cua/crates/cua-spaces/src/mcp/tools.rs@@ -719,7 +719,16 @@ async fn agents(spaces: &Spaces, tool: &str, a: Value) -> Result<ToolOutcome> {.ok_or_else(|| Error::invalid(format!("{tool}: `space` is required")))?.to_string();let s = space_for(spaces, tool, &space_arg).await?;- let agents = s.agents().await?;+ let agents = match s.agents().await {+ Ok(agents) => agents,+ Err(e) => {+ if tool == "agent_start" && a.get("home").is_none_or(Value::is_null) {+ let harness = a.get("agent").and_then(Value::as_str).unwrap_or_default();+ ag::telemetry::start_failed(harness, &s.id().to_string(), "spaces_tool", &e);+ }+ return Err(e);+ }+ };// Events without their raw ACP payload (the default for a model).let compact = |e: &ag::AgentEvent, raw: bool| {let mut v = serde_json::to_value(e).unwrap_or(Value::Null);@@ -786,7 +795,20 @@ async fn agents(spaces: &Spaces, tool: &str, a: Value) -> Result<ToolOutcome> {..Default::default()},)- .await?;+ .await;+ // The MCP `agent_start`, the SDKs' `Space.agent_start` and the+ // Spaces app all arrive here.+ let started = match started {+ Ok(started) => {+ ag::telemetry::started(&agents, &s.id().to_string(), "spaces_tool", &started);+ started+ }+ Err(e) => {+ let e = Error::from(e);+ ag::telemetry::start_failed(&a.agent, &s.id().to_string(), "spaces_tool", &e);+ return Err(e);+ }+ };if a.show.unwrap_or(false) {show(&s, &started.run_dir, &started.run_id).await;}@@ -824,6 +846,7 @@ async fn agents(spaces: &Spaces, tool: &str, a: Value) -> Result<ToolOutcome> {).await?;let st = agents.status(&a.run_id).await?;+ ag::telemetry::observe(&st);Ok(ToolOutcome::json(&json!({"run_id": a.run_id, "status": st.status, "phase": st.phase,"events": page.events.iter().map(|e| compact(e, raw)).collect::<Vec<_>>(),@@ -833,6 +856,7 @@ async fn agents(spaces: &Spaces, tool: &str, a: Value) -> Result<ToolOutcome> {"agent_status" => {let a: i::AgentStatus = args(tool, a)?;let st = agents.status(&a.run_id).await?;+ ag::telemetry::observe(&st);let result = agents.result(&a.run_id).await?;let tail = agents.events(&a.run_id, 0, 100_000).await?;Ok(ToolOutcome::json(&json!({@@ -855,7 +879,9 @@ async fn agents(spaces: &Spaces, tool: &str, a: Value) -> Result<ToolOutcome> {}"agent_stop" => {let a: i::AgentStop = args(tool, a)?;+ ag::telemetry::before_stop(&agents, &a.run_id).await;let st = agents.stop(&a.run_id).await?;+ ag::telemetry::stopped(&a.run_id);Ok(ToolOutcome::json(&json!({"run_id": a.run_id, "stopped": st.alive == Some(false), "alive": st.alive,"reason": match st.alive {@@ -867,7 +893,9 @@ async fn agents(spaces: &Spaces, tool: &str, a: Value) -> Result<ToolOutcome> {}_ => {let _: i::SpaceOnly = args(tool, a)?;- let runs: Vec<Value> = agents.list().await?.iter().map(list_row).collect();+ let runs = agents.list().await?;+ runs.iter().for_each(ag::telemetry::observe);+ let runs: Vec<Value> = runs.iter().map(list_row).collect();Ok(ToolOutcome::json(&json!({"space": s.id().to_string(), "runs": runs}),))diff --git a/libs/cua/crates/cua-telemetry/src/agent_runs.rs b/libs/cua/crates/cua-telemetry/src/agent_runs.rsnew file mode 100644index 0000000000..84c7612a04--- /dev/null+++ b/libs/cua/crates/cua-telemetry/src/agent_runs.rs@@ -0,0 +1,218 @@+//! Agent runs, recorded by the install that starts them.+//!+//! A run lives in a Space and outlives the process that started it, so its+//! end is seen later, by whichever process of this install next reads its+//! status (a watcher in the daemon or app, `agent_status`, `agent_list`,+//! `cua agent logs -f`, the SDK's `wait`). Starting a run leaves a small+//! marker in `$CUA_HOME/telemetry/agent_runs/<run id>` (harness id,+//! location word, entry point, start time: nothing else); the first process+//! to see the run end removes the marker and sends `cua_agent_run_completed`+//! once, and `first_agent_run` on this install's first run that ended+//! cleanly. Runs this install did not start have no marker and are never+//! counted here, so a run is counted once, by the host that started it.+//!+//! Inside an agent run (`CUA_AGENT_RUN_ID` set by the run's launcher) no+//! agent run is recorded: that environment is a Space, not an install.++use std::path::PathBuf;+use std::time::{Duration, SystemTime, UNIX_EPOCH};++use serde::{Deserialize, Serialize};++use crate::client::{Captured, Telemetry};+use crate::events::{self, Outcome};+use crate::{config, fsutil};++const DIR: &str = "agent_runs";+/// Markers of runs never seen ending are dropped after this long.+pub const MAX_PENDING_AGE: Duration = Duration::from_secs(7 * 24 * 3600);+/// Markers kept at most (the oldest go first).+pub const MAX_PENDING: usize = 200;++/// What a marker keeps: fixed words only, re-classified when read.+#[derive(Debug, Serialize, Deserialize)]+struct Pending {+ harness: String,+ location: String,+ entry: String,+ started_ms: u64,+}++fn now_ms() -> u64 {+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|d| d.as_millis() as u64)+ .unwrap_or(0)+}++/// A run id usable as a file name (`run-1a2b3c4d`).+fn valid_run_id(id: &str) -> bool {+ !id.is_empty()+ && id.len() <= 64+ && id+ .bytes()+ .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')+}++impl Telemetry {+ /// This process runs inside a Cua agent run (in a Space).+ pub fn in_agent_run(&self) -> bool {+ self.env(config::ENV_IN_AGENT_RUN)+ .is_some_and(|v| !v.trim().is_empty())+ }++ fn pending_path(&self, run_id: &str) -> Option<PathBuf> {+ valid_run_id(run_id).then_some(())?;+ Some(self.state_dir()?.join(DIR).join(run_id))+ }++ /// A run was started on this install: sends `cua_agent_run_started` and+ /// keeps the marker its end is recorded against. `on` is a location+ /// word or a Space id; `entry` one of [`crate::schema::AGENT_ENTRIES`].+ pub fn agent_run_started(+ &self,+ run_id: &str,+ harness: &str,+ on: &str,+ entry: &str,+ ) -> Captured {+ if self.in_agent_run() {+ return Captured::Disabled;+ }+ if self.is_enabled()+ && let Some(path) = self.pending_path(run_id)+ {+ self.prune_pending();+ let p = Pending {+ harness: events::harness(harness).into(),+ location: events::location(on).into(),+ entry: events::agent_entry(entry).into(),+ started_ms: now_ms(),+ };+ if let Ok(bytes) = serde_json::to_vec(&p) {+ let _ = fsutil::write_replace(&path, &bytes);+ }+ }+ self.capture(events::agent_run_started(+ harness,+ on,+ entry,+ Outcome::Ok,+ None,+ ))+ }++ /// Starting a run failed: sends `cua_agent_run_started` with the error+ /// variant (never the message).+ pub fn agent_run_start_failed(+ &self,+ harness: &str,+ on: &str,+ entry: &str,+ error_variant: Option<&str>,+ ) -> Captured {+ if self.in_agent_run() {+ return Captured::Disabled;+ }+ self.capture(events::agent_run_started(+ harness,+ on,+ entry,+ Outcome::Error,+ Some(error_variant.unwrap_or("Other")),+ ))+ }++ /// Whether this install started `run_id` and has not seen it end yet.+ pub fn agent_run_pending(&self, run_id: &str) -> bool {+ self.pending_path(run_id).is_some_and(|p| p.exists())+ }++ /// A run ended (its first turn finished, or it failed, crashed or was+ /// stopped): sends `cua_agent_run_completed` once for a run this+ /// install started, and `first_agent_run` the first time one ends+ /// cleanly. Any other run (not started here, or already recorded)+ /// answers [`Captured::AlreadyRecorded`].+ pub fn agent_run_finished(+ &self,+ run_id: &str,+ outcome: Outcome,+ error_variant: Option<&str>,+ ) -> Captured {+ if self.in_agent_run() {+ return Captured::Disabled;+ }+ let Some(path) = self.pending_path(run_id) else {+ return Captured::AlreadyRecorded;+ };+ let Ok(bytes) = std::fs::read(&path) else {+ return Captured::AlreadyRecorded;+ };+ // Whoever removes the marker records the end: once, across+ // processes.+ if std::fs::remove_file(&path).is_err() {+ return Captured::AlreadyRecorded;+ }+ let Ok(p) = serde_json::from_slice::<Pending>(&bytes) else {+ return Captured::Invalid("unreadable agent run marker".into());+ };+ let elapsed = Duration::from_millis(now_ms().saturating_sub(p.started_ms));+ let r = self.capture(events::agent_run_completed(+ &p.harness,+ &p.location,+ &p.entry,+ outcome,+ error_variant,+ elapsed,+ ));+ if outcome == Outcome::Ok {+ self.capture_step("first_agent_run", outcome);+ }+ r+ }++ /// Drops markers older than [`MAX_PENDING_AGE`], and the oldest beyond+ /// [`MAX_PENDING`].+ fn prune_pending(&self) {+ let Some(dir) = self.state_dir().map(|d| d.join(DIR)) else {+ return;+ };+ let Ok(rd) = std::fs::read_dir(&dir) else {+ return;+ };+ let now = SystemTime::now();+ let mut kept: Vec<(SystemTime, PathBuf)> = vec![];+ for e in rd.flatten() {+ let path = e.path();+ let modified = e+ .metadata()+ .and_then(|m| m.modified())+ .unwrap_or(UNIX_EPOCH);+ if now.duration_since(modified).unwrap_or_default() > MAX_PENDING_AGE {+ let _ = std::fs::remove_file(&path);+ } else {+ kept.push((modified, path));+ }+ }+ if kept.len() >= MAX_PENDING {+ kept.sort();+ for (_, path) in &kept[..=kept.len() - MAX_PENDING] {+ let _ = std::fs::remove_file(path);+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn run_ids_are_file_names_only() {+ assert!(valid_run_id("run-1a2b3c4d"));+ assert!(!valid_run_id(""));+ assert!(!valid_run_id("../x"));+ assert!(!valid_run_id("a/b"));+ assert!(!valid_run_id(&"a".repeat(65)));+ }+}diff --git a/libs/cua/crates/cua-telemetry/src/client.rs b/libs/cua/crates/cua-telemetry/src/client.rsindex 580cfeced3..3a0b8ee553 100644--- a/libs/cua/crates/cua-telemetry/src/client.rs+++ b/libs/cua/crates/cua-telemetry/src/client.rs@@ -250,7 +250,7 @@ impl Telemetry {}}- fn env(&self, name: &str) -> Option<String> {+ pub(crate) fn env(&self, name: &str) -> Option<String> {(self.inner.env)(name)}diff --git a/libs/cua/crates/cua-telemetry/src/config.rs b/libs/cua/crates/cua-telemetry/src/config.rsindex ae163acbb5..f5f724c615 100644--- a/libs/cua/crates/cua-telemetry/src/config.rs+++ b/libs/cua/crates/cua-telemetry/src/config.rs@@ -33,6 +33,11 @@ pub const ENV_DEBUG: &str = "CUA_TELEMETRY_DEBUG";pub const ENV_ENDPOINT: &str = "CUA_TELEMETRY_ENDPOINT";/// Refuse every non-loopback send (set for all test runs).pub const ENV_FORBID_NETWORK: &str = "CUA_TELEMETRY_FORBID_NETWORK";+/// Set (to the run id) in the environment of every Cua agent run, by the+/// run's launcher inside the Space. A Cua program running there is not the+/// install that started the run, so it records no agent runs of its own:+/// the host install that started the run records it.+pub const ENV_IN_AGENT_RUN: &str = "CUA_AGENT_RUN_ID";/// How Cua was installed (set by installers).pub const ENV_INSTALL_CHANNEL: &str = "CUA_INSTALL_CHANNEL";/// File in the telemetry state dir where install.sh / install.ps1 record thediff --git a/libs/cua/crates/cua-telemetry/src/events.rs b/libs/cua/crates/cua-telemetry/src/events.rsindex 27ead5f092..b99c7d4d7c 100644--- a/libs/cua/crates/cua-telemetry/src/events.rs+++ b/libs/cua/crates/cua-telemetry/src/events.rs@@ -640,10 +640,39 @@ pub fn onboarding_step(step: &str, outcome: Outcome) -> Option<Event> {})}-/// `cua_agent_run_completed`.+/// Where an agent run was started from ([`schema::AGENT_ENTRIES`]), else+/// `other`.+pub fn agent_entry(entry: &str) -> &'static str {+ pick(schema::AGENT_ENTRIES, entry, "other")+}++/// `cua_agent_run_started`: a run was started (`Outcome::Ok`) or its start+/// failed (`Outcome::Error` with the error variant). `on` is a location word+/// or a Space id (`local:dev`; only the location word before `:` is kept).+pub fn agent_run_started(+ harness_id: &str,+ on: &str,+ entry: &str,+ outcome: Outcome,+ error_variant: Option<&str>,+) -> Event {+ Event::new(event::AGENT_RUN_STARTED)+ .s("harness", harness(harness_id))+ .s("location", location(on))+ .s("entry", agent_entry(entry))+ .s("outcome", outcome.as_str())+ .s(+ "error_kind",+ error_variant.map(error_kind).unwrap_or("none"),+ )+}++/// `cua_agent_run_completed`: a run's first turn ended (or the run failed,+/// crashed or was stopped first).pub fn agent_run_completed(harness_id: &str,on: &str,+ entry: &str,outcome: Outcome,error_variant: Option<&str>,elapsed: Duration,@@ -651,6 +680,7 @@ pub fn agent_run_completed(Event::new(event::AGENT_RUN_COMPLETED).s("harness", harness(harness_id)).s("location", location(on))+ .s("entry", agent_entry(entry)).s("outcome", outcome.as_str()).s("error_kind",@@ -659,6 +689,26 @@ pub fn agent_run_completed(.s("duration_bucket", duration_bucket(elapsed))}+/// How an agent run ended, from its published status (`cua_agents`+/// `RunStatus::as_str`), the ACP stop reason of its last turn and whether+/// it recorded an error. None while it still runs (or cannot be read).+pub fn agent_run_end(+ status: &str,+ stop_reason: Option<&str>,+ recorded_error: bool,+) -> Option<(Outcome, Option<&'static str>)> {+ match status.trim() {+ "idle" if stop_reason.is_some_and(|r| r.trim() == "cancelled") => {+ Some((Outcome::Cancelled, None))+ }+ "idle" if recorded_error => Some((Outcome::Error, Some("AgentFailed"))),+ "idle" => Some((Outcome::Ok, None)),+ "failed" => Some((Outcome::Error, Some("AgentFailed"))),+ "crashed" => Some((Outcome::Error, Some("AgentCrashed"))),+ _ => None,+ }+}+/// `cua_bench_run_completed`.pub fn bench_run_completed(taskset_name: &str,diff --git a/libs/cua/crates/cua-telemetry/src/lib.rs b/libs/cua/crates/cua-telemetry/src/lib.rsindex d52e1c0377..795cd119ab 100644--- a/libs/cua/crates/cua-telemetry/src/lib.rs+++ b/libs/cua/crates/cua-telemetry/src/lib.rs@@ -13,6 +13,7 @@//! keystrokes, screenshots or prompts; identifiers are per-install salted//! hashes or absent; nothing from the Keyvault but counts.+pub mod agent_runs;pub mod client;pub mod config;pub mod events;diff --git a/libs/cua/crates/cua-telemetry/src/schema.rs b/libs/cua/crates/cua-telemetry/src/schema.rsindex bc049d5dec..bbb034d1fd 100644--- a/libs/cua/crates/cua-telemetry/src/schema.rs+++ b/libs/cua/crates/cua-telemetry/src/schema.rs@@ -153,6 +153,11 @@ pub const ERROR_KINDS: &[&str] = &["insufficient_disk","requires_cua_app","cancelled",+ // An agent run: cua_spaces `Error::Agent`, a run that recorded a+ // failure, a run whose process went away mid-turn.+ "agent",+ "agent_failed",+ "agent_crashed","other",];pub const DURATIONS: &[&str] = &[@@ -405,6 +410,30 @@ pub const HARNESSES: &[&str] = &["openclaw","other",];+/// Where an agent run was started from: a Spaces tool call (the MCP+/// `agent_start`, the SDKs' `Space.agent_start`, the Spaces app), the+/// `cua agent` CLI, the SDKs' sandbox `Agents.run`, a persistent agent's+/// turn, a routine firing.+pub const AGENT_ENTRIES: &[&str] = &[+ "spaces_tool",+ "cli",+ "sdk",+ "persistent",+ "routine",+ "other",+];+/// The products that start agent runs on a host install. Never `spacesd`:+/// a Space is not an install, so runs are counted where they are started.+pub const AGENT_PRODUCTS: &[&str] = &[+ "cli",+ "daemon",+ "sdk_rust",+ "sdk_python",+ "sdk_typescript",+ "sdk_swift",+ "sdk_kotlin",+ "spaces_app",+];/// cua-bench dataset names (`cua_bench/registry.json`) or `custom`.pub const TASKSETS: &[&str] = &["cua-bench-basic",@@ -492,6 +521,21 @@ const DURATION: Prop = p("Duration, bucketed.",);const LOCATION: Prop = p("location", Kind::Enum(LOCATIONS), "Where the sandbox runs.");+const AGENT_HARNESS: Prop = p(+ "harness",+ Kind::Enum(HARNESSES),+ "cua-agents harness id (claude-code, openai-codex, ...), else other.",+);+const AGENT_LOCATION: Prop = p(+ "location",+ Kind::Enum(LOCATIONS),+ "Where the Space runs: local, cloud, relay (a machine of the account) or direct (added by address).",+);+const AGENT_ENTRY: Prop = p(+ "entry",+ Kind::Enum(AGENT_ENTRIES),+ "Where the run was started from: spaces_tool, cli, sdk, persistent or routine.",+);const CALLER_KIND: Prop = p("caller_kind",Kind::Enum(CALLER_KINDS),@@ -535,6 +579,7 @@ pub mod event {pub const SPACES_FEATURE_USED: &str = "cua_spaces_feature_used";pub const STREAM_STATS: &str = "cua_stream_stats";pub const ONBOARDING_STEP: &str = "cua_onboarding_step";+ pub const AGENT_RUN_STARTED: &str = "cua_agent_run_started";pub const AGENT_RUN_COMPLETED: &str = "cua_agent_run_completed";pub const BENCH_RUN_COMPLETED: &str = "cua_bench_run_completed";pub const DAEMON_STARTED: &str = "cua_daemon_started";@@ -789,19 +834,35 @@ pub const EVENTS: &[EventSpec] = &[purpose: "Install and onboarding funnel: where people drop off.",},EventSpec {- name: event::AGENT_RUN_COMPLETED,+ name: event::AGENT_RUN_STARTED,version: 1,tier: Tier::Usage,sample_rate: 1.0,- products: CLIENTS,+ products: AGENT_PRODUCTS,props: &[- p("harness", Kind::Enum(HARNESSES), "cua-agents harness id."),- LOCATION,+ AGENT_HARNESS,+ AGENT_LOCATION,+ AGENT_ENTRY,+ OUTCOME,+ ERROR_KIND,+ ],+ purpose: "Agent runs started per harness, Space location and entry point, and how often a start fails.",+ },+ EventSpec {+ name: event::AGENT_RUN_COMPLETED,+ version: 2,+ tier: Tier::Usage,+ sample_rate: 1.0,+ products: AGENT_PRODUCTS,+ props: &[+ AGENT_HARNESS,+ AGENT_LOCATION,+ AGENT_ENTRY,OUTCOME,ERROR_KIND,DURATION,],- purpose: "Which coding-agent harnesses run in sandboxes and how reliably.",+ purpose: "Activation (first agent run) and which coding-agent harnesses finish their first turn, and how reliably. Sent once per run, by the install that started it.",},EventSpec {name: event::BENCH_RUN_COMPLETED,diff --git a/libs/cua/crates/cua-telemetry/tests/privacy.rs b/libs/cua/crates/cua-telemetry/tests/privacy.rsindex fc5bc6c664..90be6bc60e 100644--- a/libs/cua/crates/cua-telemetry/tests/privacy.rs+++ b/libs/cua/crates/cua-telemetry/tests/privacy.rs@@ -130,7 +130,8 @@ fn all_builders(s: &str) -> Vec<Event> {height: 1080,duration: d,}),- events::agent_run_completed(s, s, Outcome::Ok, Some(s), d),+ events::agent_run_started(s, s, s, Outcome::Error, Some(s)),+ events::agent_run_completed(s, s, s, Outcome::Ok, Some(s), d),events::bench_run_completed(s, Some(0.42), 12, Outcome::Ok),events::daemon_started(s, Outcome::Ok),events::daemon_health(d, 3),@@ -1167,3 +1168,172 @@ fn stream_summary_is_bucketed_and_needs_video() {events::stream_summary("websocket", "h264", None, 5, 720, None, Duration::ZERO).is_none());}++/// Agent runs: one `cua_agent_run_started`, one `cua_agent_run_completed`+/// per run (whichever process sees it end first), `first_agent_run` once+/// per install, and only fixed words in any of them.+#[test]+fn agent_runs_are_recorded_once_by_the_install_that_started_them() {+ let h = tempfile::tempdir().unwrap();+ let (t, sink) = ready(h.path(), &[]);+ assert_eq!(+ t.agent_run_started(+ "run-0000abcd",+ "claude-code",+ "local:my-private-sandbox-name",+ "spaces_tool"+ ),+ Captured::Queued+ );+ assert!(t.agent_run_pending("run-0000abcd"));+ // The marker keeps fixed words only.+ let marker =+ std::fs::read_to_string(h.path().join("telemetry/agent_runs/run-0000abcd")).unwrap();+ assert!(!marker.contains("private"), "{marker}");+ // A run this install did not start is never counted here.+ assert_eq!(+ t.agent_run_finished("run-ffffffff", Outcome::Ok, None),+ Captured::AlreadyRecorded+ );+ // Another process of the same install sees it end: recorded once.+ let (t2, sink2) = ready(h.path(), &[]);+ assert_eq!(+ t2.agent_run_finished("run-0000abcd", Outcome::Ok, None),+ Captured::Queued+ );+ assert_eq!(+ t.agent_run_finished("run-0000abcd", Outcome::Ok, None),+ Captured::AlreadyRecorded+ );+ assert!(!t.agent_run_pending("run-0000abcd"));+ // A second run: completed again, but first_agent_run never again.+ t.agent_run_started("run-0000abce", "openai-codex", "cloud", "cli");+ t.agent_run_finished("run-0000abce", Outcome::Error, Some("AgentCrashed"));+ t.agent_run_start_failed("goose", "relay", "routine", Some("Timeout"));+ t.agent_run_started("run-0000abcf", "pi", "direct", "persistent");+ t2.agent_run_started("run-0000abd0", "goose", "local", "sdk");+ t2.agent_run_finished("run-0000abd0", Outcome::Ok, None);+ t.flush(Duration::from_secs(1));+ t2.flush(Duration::from_secs(1));+ let mut all = sink.events();+ all.extend(sink2.events());+ let id = std::fs::read_to_string(h.path().join("telemetry/install_id")).unwrap();+ for e in &all {+ assert_eq!(e["distinct_id"], id.trim(), "one install");+ let text = e.to_string().to_lowercase();+ assert!(!text.contains("private"), "{text}");+ }+ let named = |n: &str| -> Vec<&Value> { all.iter().filter(|e| e["event"] == n).collect() };+ let started = named("cua_agent_run_started");+ assert_eq!(started.len(), 5);+ assert!(started.iter().any(|e| e["properties"]["outcome"] == "error"+ && e["properties"]["error_kind"] == "timeout"+ && e["properties"]["entry"] == "routine"+ && e["properties"]["location"] == "relay"));+ let completed = named("cua_agent_run_completed");+ assert_eq!(completed.len(), 3);+ let first = completed+ .iter()+ .find(|e| e["properties"]["harness"] == "claude-code")+ .unwrap();+ let p = &first["properties"];+ assert_eq!(p["location"], "local");+ assert_eq!(p["entry"], "spaces_tool");+ assert_eq!(p["outcome"], "ok");+ assert_eq!(p["error_kind"], "none");+ assert!(schema::DURATIONS.contains(&p["duration_bucket"].as_str().unwrap()));+ assert_eq!(p["event_version"], 2);+ assert!(+ completed+ .iter()+ .any(|e| e["properties"]["error_kind"] == "agent_crashed")+ );+ let steps: Vec<&Value> = named("cua_onboarding_step")+ .into_iter()+ .filter(|e| e["properties"]["step"] == "first_agent_run")+ .collect();+ assert_eq!(steps.len(), 1, "first_agent_run once per install");+}++#[test]+fn agent_runs_respect_every_opt_out_and_never_count_inside_a_run() {+ for env in [+ &[("CUA_TELEMETRY", "0")][..],+ &[("DO_NOT_TRACK", "1")][..],+ &[("CI", "true")][..],+ ] {+ let h = tempfile::tempdir().unwrap();+ let (t, sink) = ready(h.path(), env);+ assert_eq!(+ t.agent_run_started("run-00000001", "claude-code", "local", "cli"),+ Captured::Disabled+ );+ assert!(!t.agent_run_pending("run-00000001"), "no marker while off");+ t.flush(Duration::from_secs(1));+ assert!(sink.events().is_empty());+ }+ // The config switch (`cua telemetry off`, the app's Settings).+ let h = tempfile::tempdir().unwrap();+ let (t, sink) = ready(h.path(), &[]);+ t.agent_run_started("run-00000002", "claude-code", "local", "cli");+ std::fs::write(+ h.path().join("config.toml"),+ "[telemetry]\nenabled = \"off\"\n",+ )+ .unwrap();+ t.refresh();+ assert_eq!(+ t.agent_run_finished("run-00000002", Outcome::Ok, None),+ Captured::Disabled+ );+ assert!(!t.agent_run_pending("run-00000002"));+ t.flush(Duration::from_secs(1));+ assert!(+ !sink+ .events()+ .iter()+ .any(|e| e["event"] == "cua_agent_run_completed")+ );+ // Inside an agent run (a Space): nothing, so the guest never counts as+ // an install that ran an agent.+ let h = tempfile::tempdir().unwrap();+ let (t, sink) = ready(h.path(), &[("CUA_AGENT_RUN_ID", "run-1a2b3c4d")]);+ assert_eq!(+ t.agent_run_started("run-00000003", "claude-code", "local", "cli"),+ Captured::Disabled+ );+ assert_eq!(+ t.agent_run_finished("run-00000003", Outcome::Ok, None),+ Captured::Disabled+ );+ t.flush(Duration::from_secs(1));+ assert!(+ sink.events()+ .iter()+ .all(|e| !e["event"].as_str().unwrap().starts_with("cua_agent_run"))+ );+}++#[test]+fn agent_run_end_follows_the_published_status() {+ assert_eq!(events::agent_run_end("running", None, false), None);+ assert_eq!(events::agent_run_end("unknown", None, false), None);+ assert_eq!(+ events::agent_run_end("idle", Some("end_turn"), false),+ Some((Outcome::Ok, None))+ );+ assert_eq!(+ events::agent_run_end("idle", Some("cancelled"), false),+ Some((Outcome::Cancelled, None))+ );+ assert_eq!(+ events::agent_run_end("failed", None, true),+ Some((Outcome::Error, Some("AgentFailed")))+ );+ assert_eq!(+ events::agent_run_end("crashed", None, false),+ Some((Outcome::Error, Some("AgentCrashed")))+ );+ assert_eq!(events::error_kind("AgentFailed"), "agent_failed");+ assert_eq!(events::error_kind("Agent"), "agent");+}