Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(cua-driver): complete telemetry lifecycle coverage

Francesco Bonacci7ac5836714e9
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs
index 9f19f25bc5..17b317321a 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs
@@ -11,9 +11,9 @@ use crate::tool::ToolRegistry;
/// Receives privacy-bounded observations from the stdio MCP transport.
///
/// The observer never receives tool arguments, text/image content, response
-/// bodies, arbitrary MCP metadata, or raw errors. HTTP dispatch deliberately
-/// bypasses this seam and remains unobserved until HTTP session semantics are
-/// defined.
+/// bodies, arbitrary MCP metadata, or raw errors. HTTP dispatch reuses the
+/// bounded tool timer directly; HTTP session-start telemetry remains deferred
+/// until the transport has explicit session semantics.
pub trait StdioObserver: Send + Sync + 'static {
fn on_session_started(&self, metadata: InitializeMetadata);
fn on_tool_completed(&self, outcome: ToolCompletionObservation);
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
index 2f69bdcac2..11e3c7d764 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs
@@ -156,9 +156,10 @@ const VALUE_FLAGS: &[&str] = &[
/// parser exits are still observed as completed failures.
pub fn finite_command_name_from_argv() -> Option<&'static str> {
let args: Vec<String> = std::env::args().skip(1).collect();
- if args.iter().any(|arg| matches!(arg.as_str(), "--help" | "-h" | "--version" | "-V")) {
- return None;
- }
+ finite_command_name_from_args(&args)
+}
+
+fn positional_args(args: &[String]) -> Vec<&str> {
let mut positionals = Vec::new();
let mut index = 0;
while index < args.len() {
@@ -172,6 +173,14 @@ pub fn finite_command_name_from_argv() -> Option<&'static str> {
index += 1;
}
}
+ positionals
+}
+
+fn finite_command_name_from_args(args: &[String]) -> Option<&'static str> {
+ if args.iter().any(|arg| matches!(arg.as_str(), "--help" | "-h" | "--version" | "-V")) {
+ return None;
+ }
+ let positionals = positional_args(args);
match positionals.first().copied() {
None | Some("mcp" | "serve" | "telemetry") => None,
Some("list-tools") => Some("list_tools"),
@@ -195,6 +204,25 @@ pub fn finite_command_name_from_argv() -> Option<&'static str> {
}
}
+/// Return the candidate tool for a finite `call` command. The telemetry layer
+/// maps this through its fixed registry allowlist before anything is emitted.
+pub fn finite_tool_name_from_argv() -> Option<String> {
+ let args: Vec<String> = std::env::args().skip(1).collect();
+ finite_tool_name_from_args(&args)
+}
+
+fn finite_tool_name_from_args(args: &[String]) -> Option<String> {
+ if finite_command_name_from_args(args) != Some("call") {
+ return None;
+ }
+ let positionals = positional_args(args);
+ match positionals.as_slice() {
+ ["call", tool, ..] => Some((*tool).to_owned()),
+ [tool, ..] => Some((*tool).to_owned()),
+ _ => None,
+ }
+}
+
/// Parse the first non-flag positional argument from argv to determine which
/// subcommand to run. Cursor-overlay flags are consumed by `CursorConfig`
/// independently; we only care about the first non-`--` arg here.
@@ -707,12 +735,36 @@ pub fn should_use_daemon_proxy(no_daemon_relaunch: bool) -> bool {
/// Mirror of Swift `MCPCommand.launchDaemonViaOpen` +
/// `waitForDaemon`. Split into one Rust function because we don't
/// need the post-launch probe separation Swift has.
+#[cfg(target_os = "macos")]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum LaunchDaemonErrorKind {
+ Failed,
+ Timeout,
+}
+
+#[cfg(target_os = "macos")]
+#[derive(Debug)]
+pub struct LaunchDaemonError {
+ pub kind: LaunchDaemonErrorKind,
+ message: String,
+}
+
+#[cfg(target_os = "macos")]
+impl std::fmt::Display for LaunchDaemonError {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter.write_str(&self.message)
+ }
+}
+
+#[cfg(target_os = "macos")]
+impl std::error::Error for LaunchDaemonError {}
+
#[cfg(target_os = "macos")]
pub fn launch_daemon_and_wait(
socket_path: &str,
timeout_secs: u64,
claude_code_compat: bool,
-) -> anyhow::Result<()> {
+) -> Result<(), LaunchDaemonError> {
use std::process::{Command as Cmd, Stdio};
use std::time::{Duration, Instant};
@@ -756,20 +808,24 @@ pub fn launch_daemon_and_wait(
.stderr(Stdio::null())
.status();
- let status = status.map_err(|e| {
- anyhow::anyhow!(
- "failed to exec `/usr/bin/open`: {e}. Pass --no-daemon-relaunch to bypass."
- )
+ let status = status.map_err(|error| LaunchDaemonError {
+ kind: LaunchDaemonErrorKind::Failed,
+ message: format!(
+ "failed to exec `/usr/bin/open`: {error}. Pass --no-daemon-relaunch to bypass."
+ ),
})?;
if !status.success() {
- anyhow::bail!(
- "`open -n -g -a CuaDriver --args serve{}` exited {:?}. \
+ return Err(LaunchDaemonError {
+ kind: LaunchDaemonErrorKind::Failed,
+ message: format!(
+ "`open -n -g -a CuaDriver --args serve{}` exited {:?}. \
Check that `/Applications/CuaDriver.app` is installed, or \
pass --no-daemon-relaunch to bypass.",
- if pass_socket { format!(" --socket {socket_path}") } else { String::new() },
+ if pass_socket { format!(" --socket {socket_path}") } else { String::new() },
status.code()
- );
+ ),
+ });
}
// Poll the UDS until the daemon answers a probe or we time out.
@@ -782,22 +838,54 @@ pub fn launch_daemon_and_wait(
std::thread::sleep(Duration::from_millis(100));
}
- anyhow::bail!(
- "daemon did not appear on {socket_path} within {timeout_secs}s. If this \
+ Err(LaunchDaemonError {
+ kind: LaunchDaemonErrorKind::Timeout,
+ message: format!(
+ "daemon did not appear on {socket_path} within {timeout_secs}s. If this \
is the first launch, grant Accessibility + Screen Recording to \
CuaDriver.app in System Settings and retry. Pass --no-daemon-relaunch \
to stay in-process."
- );
+ ),
+ })
}
/// Run the MCP proxy path: ensure a daemon is up (spawning via
/// `open` if needed), then `crate::proxy::run_proxy` against its
/// socket. Builds its own tokio runtime — same shape as the other
/// `run_*` helpers in this file that own their event loop.
-pub fn run_mcp_via_daemon_proxy(
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[allow(dead_code)] // Some outcomes are platform-specific.
+pub enum McpDaemonStartup {
+ AlreadyRunning,
+ Launched,
+ LaunchFailed,
+ LaunchTimeout,
+ Unreachable,
+ UnsupportedRelaunch,
+}
+
+impl McpDaemonStartup {
+ pub const fn telemetry_value(self) -> &'static str {
+ match self {
+ Self::AlreadyRunning => "already_running",
+ Self::Launched => "launched",
+ Self::LaunchFailed => "launch_failed",
+ Self::LaunchTimeout => "launch_timeout",
+ Self::Unreachable => "unreachable",
+ Self::UnsupportedRelaunch => "unsupported_relaunch",
+ }
+ }
+}
+
+pub fn run_mcp_via_daemon_proxy<F>(
socket: Option<String>,
claude_code_compat: bool,
-) -> anyhow::Result<()> {
+ on_startup: F,
+) -> anyhow::Result<()>
+where
+ F: FnOnce(McpDaemonStartup, bool),
+{
+ let mut on_startup = Some(on_startup);
// Windows: prefer the uiAccess'd worker pipe over the regular daemon pipe
// when both are running, so MCP tool calls land in a process that can
// bypass UIPI for UWP apps. The protocol on both pipes is identical so
@@ -820,13 +908,18 @@ pub fn run_mcp_via_daemon_proxy(
}
};
- if !crate::serve::is_daemon_listening(&socket_path) {
+ let already_running = crate::serve::is_daemon_listening(&socket_path);
+ let mut daemon = McpDaemonStartup::AlreadyRunning;
+ if !already_running {
// CUA_DRIVER_RS_MCP_FORCE_PROXY callers (test harness, custom
// bundle setups) supply their own daemon — skip the auto-
// launch step, since they don't have an installed
// CuaDriver.app to relaunch into. Fail fast if no daemon is
// up at this point.
if crate::bundle::is_env_truthy("CUA_DRIVER_RS_MCP_FORCE_PROXY") {
+ if let Some(on_startup) = on_startup.take() {
+ on_startup(McpDaemonStartup::Unreachable, false);
+ }
anyhow::bail!(
"CUA_DRIVER_RS_MCP_FORCE_PROXY=1 but no daemon listening on \
{socket_path}. Start one with `cua-driver serve --socket {socket_path}` \
@@ -845,7 +938,20 @@ pub fn run_mcp_via_daemon_proxy(
auto-launching the daemon via `open -n -g -a CuaDriver --args serve{socket_suffix}` \
and proxying MCP requests through it. Pass --no-daemon-relaunch to stay in-process."
);
- launch_daemon_and_wait(&socket_path, 10, claude_code_compat)?;
+ if let Err(error) = launch_daemon_and_wait(&socket_path, 10, claude_code_compat) {
+ if let Some(on_startup) = on_startup.take() {
+ on_startup(
+ if error.kind == LaunchDaemonErrorKind::Timeout {
+ McpDaemonStartup::LaunchTimeout
+ } else {
+ McpDaemonStartup::LaunchFailed
+ },
+ false,
+ );
+ }
+ return Err(error.into());
+ }
+ daemon = McpDaemonStartup::Launched;
}
#[cfg(not(target_os = "macos"))]
let _ = claude_code_compat;
@@ -859,6 +965,9 @@ pub fn run_mcp_via_daemon_proxy(
// Session 0 over SSH).
#[cfg(not(target_os = "macos"))]
{
+ if let Some(on_startup) = on_startup.take() {
+ on_startup(McpDaemonStartup::UnsupportedRelaunch, false);
+ }
anyhow::bail!(
"no Cua Driver daemon listening on {socket_path}. Start one in \
your interactive session — on Windows run \
@@ -871,6 +980,10 @@ pub fn run_mcp_via_daemon_proxy(
}
}
+ if let Some(on_startup) = on_startup.take() {
+ on_startup(daemon, true);
+ }
+
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
@@ -2984,6 +3097,31 @@ fn sanitize_tool_name(name: &str) -> String {
mod tests {
use super::*;
+ fn args(values: &[&str]) -> Vec<String> {
+ values.iter().map(|value| (*value).to_owned()).collect()
+ }
+
+ #[test]
+ fn finite_call_tool_extraction_supports_subcommand_and_legacy_forms() {
+ assert_eq!(
+ finite_tool_name_from_args(&args(&["call", "click", r#"{\"x\":1}"#])),
+ Some("click".into())
+ );
+ assert_eq!(
+ finite_tool_name_from_args(&args(&["--socket", "/tmp/test", "click", "{}"])),
+ Some("click".into())
+ );
+ }
+
+ #[test]
+ fn finite_call_tool_extraction_ignores_non_call_commands() {
+ assert_eq!(
+ finite_tool_name_from_args(&args(&["describe", "click"])),
+ None
+ );
+ assert_eq!(finite_tool_name_from_args(&args(&["mcp"])), None);
+ }
+
#[test]
fn sanitize_tool_name_passes_through_canonical_names() {
assert_eq!(sanitize_tool_name("click"), "click");
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/main.rs b/libs/cua-driver/rust/crates/cua-driver/src/main.rs
index 564cc54ecd..594a0e03f0 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/main.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/main.rs
@@ -61,22 +61,6 @@ fn init_logging() {
telemetry::register_stdio_observer();
}
-/// Keep entry events only for long-running process starts. Supported finite
-/// command paths emit a bounded event only after their outcome is known.
-fn emit_entry_telemetry(command: &cli::Command) {
- match command {
- cli::Command::Mcp { .. } => telemetry::capture_start(
- telemetry::event::MCP_START_LEGACY,
- telemetry::Transport::McpStdio,
- ),
- cli::Command::Serve { .. } => telemetry::capture_start(
- telemetry::event::SERVE_START_LEGACY,
- telemetry::Transport::Cli,
- ),
- _ => {}
- }
-}
-
/// Execute finite commands in a child so the parent can observe every exit,
/// including validation failures and legacy `process::exit` paths. Delivery is
/// delegated to a detached, no-output worker after the child exits, so network
@@ -86,6 +70,7 @@ fn maybe_wrap_finite_command() {
return;
}
let Some(command_name) = cli::finite_command_name_from_argv() else { return; };
+ let tool_name = cli::finite_tool_name_from_argv();
telemetry::spawn_first_run_registration_worker();
let Ok(executable) = std::env::current_exe() else { return; };
let started_at = std::time::Instant::now();
@@ -95,7 +80,12 @@ fn maybe_wrap_finite_command() {
.status();
let Ok(status) = status else { return; };
let exit_code = status.code().unwrap_or(1);
- telemetry::spawn_cli_completion_worker(command_name, exit_code, started_at.elapsed());
+ telemetry::spawn_cli_completion_worker(
+ command_name,
+ tool_name.as_deref(),
+ exit_code,
+ started_at.elapsed(),
+ );
std::process::exit(exit_code);
}
@@ -251,7 +241,6 @@ fn main() {
if !telemetry::is_wrapped_cli_child() && !matches!(&command, cli::Command::Telemetry(_)) {
telemetry::spawn_first_run_registration_worker();
}
- emit_entry_telemetry(&command);
match command {
cli::Command::Telemetry(command) => {
run_telemetry_command(command);
@@ -308,13 +297,29 @@ fn main() {
}
cli::Command::Serve { socket, no_permissions_gate, claude_code_compat } => {
responsibility::reexec_disclaimed_if_needed();
+ let gate_opts = platform_macos::permissions::GateOpts::from_env_and_flag(
+ no_permissions_gate,
+ );
+ if let Some((progress, context)) =
+ platform_macos::permissions::gate::prepare_telemetry_context(gate_opts.opt_out)
+ {
+ if progress == platform_macos::permissions::GateProgress::Started {
+ telemetry::capture_permissions_gate_started(
+ context.missing_accessibility,
+ context.missing_screen_recording,
+ );
+ }
+ }
+ if !platform_macos::permissions::gate::is_gate_reexec() {
+ telemetry::capture_start(
+ telemetry::event::SERVE_START_LEGACY,
+ telemetry::Transport::Daemon,
+ );
+ }
// Long-running daemon — kick off the background update check
// before any blocking work so the banner can land on stderr
// early in the serve lifecycle.
version_check::maybe_announce_update();
- let gate_opts = platform_macos::permissions::GateOpts::from_env_and_flag(
- no_permissions_gate,
- );
cua_driver_core::recording::set_screenshot_fn(|window_id, pid| {
if let Some(wid) = window_id {
platform_macos::capture::screenshot_window_bytes(wid as u32).ok()
@@ -407,7 +412,39 @@ fn main() {
// and the daemon continues to serve — individual tool calls
// will then fail with the underlying TCC error, mirroring
// Swift's "user closed the panel" fallback.
- if let Err(e) = platform_macos::permissions::run_if_needed(gate_opts) {
+ let gate_result = platform_macos::permissions::run_if_needed_with_observer(
+ gate_opts,
+ |progress, context| match progress {
+ platform_macos::permissions::GateProgress::Started => {
+ telemetry::capture_permissions_gate_started(
+ context.missing_accessibility,
+ context.missing_screen_recording,
+ );
+ }
+ platform_macos::permissions::GateProgress::Dismissed => {
+ telemetry::capture_permissions_gate_dismissed(
+ context.missing_accessibility,
+ context.missing_screen_recording,
+ context.elapsed,
+ );
+ }
+ },
+ );
+ let gate_context = platform_macos::permissions::gate::telemetry_context();
+ if gate_context.engaged {
+ telemetry::capture_permissions_gate_completed(
+ gate_context.missing_accessibility,
+ gate_context.missing_screen_recording,
+ gate_context.panel_shown,
+ gate_context.dismissed,
+ telemetry::permissions_gate_resolution(
+ gate_result.is_err(),
+ gate_context.dismissed,
+ ),
+ gate_context.elapsed,
+ );
+ }
+ if let Err(e) = gate_result {
eprintln!("[cua-driver] permissions gate: {e}");
eprintln!("[cua-driver] continuing — tool calls touching AX or \
Screen Recording fail until you grant the missing TCC \
@@ -501,6 +538,7 @@ fn main() {
return;
}
cli::Command::Mcp { no_daemon_relaunch, socket, claude_code_compat } => {
+ let startup_started = std::time::Instant::now();
CLAUDE_CODE_COMPAT.store(claude_code_compat, Ordering::SeqCst);
// Long-running MCP server — kick off the background update
// check before any TCC / daemon-proxy decisions so the
@@ -513,7 +551,16 @@ fn main() {
// attribution and forwards stdio MCP through its socket.
// Issue #1525 / mirror of Swift PR #1479.
if cli::should_use_daemon_proxy(no_daemon_relaunch) {
- if let Err(e) = cli::run_mcp_via_daemon_proxy(socket, claude_code_compat) {
+ if let Err(e) = cli::run_mcp_via_daemon_proxy(
+ socket,
+ claude_code_compat,
+ |daemon, success| telemetry::capture_mcp_startup_completed(
+ "daemon_proxy",
+ daemon.telemetry_value(),
+ success,
+ startup_started.elapsed(),
+ ),
+ ) {
eprintln!("cua-driver-rs: {e}");
telemetry::flush_pending(std::time::Duration::from_millis(750));
std::process::exit(1);
@@ -525,6 +572,12 @@ fn main() {
// `socket` flag is daemon-proxy-only; it has no meaning
// in the in-process path, so we drop it on the floor.
let _ = socket;
+ telemetry::capture_mcp_startup_completed(
+ "in_process",
+ "not_applicable",
+ true,
+ startup_started.elapsed(),
+ );
}
}
@@ -631,7 +684,6 @@ fn main() -> anyhow::Result<()> {
if !telemetry::is_wrapped_cli_child() && !matches!(&command, cli::Command::Telemetry(_)) {
telemetry::spawn_first_run_registration_worker();
}
- emit_entry_telemetry(&command);
match command {
cli::Command::Telemetry(command) => {
run_telemetry_command(command);
@@ -668,6 +720,10 @@ fn main() -> anyhow::Result<()> {
}
cli::Command::Serve { socket, no_permissions_gate, claude_code_compat } => {
responsibility::reexec_disclaimed_if_needed();
+ telemetry::capture_start(
+ telemetry::event::SERVE_START_LEGACY,
+ telemetry::Transport::Daemon,
+ );
// Long-running daemon — kick off the background update check
// before any blocking work so the banner can land on stderr.
version_check::maybe_announce_update();
@@ -756,6 +812,7 @@ fn main() -> anyhow::Result<()> {
return Ok(());
}
cli::Command::Mcp { no_daemon_relaunch, socket, claude_code_compat } => {
+ let startup_started = std::time::Instant::now();
CLAUDE_CODE_COMPAT.store(claude_code_compat, Ordering::SeqCst);
// Long-running MCP server — kick off the background update
// check before any daemon-proxy decisions.
@@ -771,7 +828,16 @@ fn main() -> anyhow::Result<()> {
// Code over SSH lands in Session 0 and every desktop
// tool returns empty. See `cli::should_use_daemon_proxy`.
if cli::should_use_daemon_proxy(no_daemon_relaunch) {
- if let Err(e) = cli::run_mcp_via_daemon_proxy(socket, claude_code_compat) {
+ if let Err(e) = cli::run_mcp_via_daemon_proxy(
+ socket,
+ claude_code_compat,
+ |daemon, success| telemetry::capture_mcp_startup_completed(
+ "daemon_proxy",
+ daemon.telemetry_value(),
+ success,
+ startup_started.elapsed(),
+ ),
+ ) {
eprintln!("cua-driver-rs: {e}");
telemetry::flush_pending(std::time::Duration::from_millis(750));
std::process::exit(1);
@@ -784,6 +850,12 @@ fn main() -> anyhow::Result<()> {
// in-process path (mirrors the macOS arm's drop-on-floor
// behaviour).
let _ = socket;
+ telemetry::capture_mcp_startup_completed(
+ "in_process",
+ "not_applicable",
+ true,
+ startup_started.elapsed(),
+ );
}
}
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs b/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs
index e6f04bd30f..99ae1d232b 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/mcp_http.rs
@@ -22,7 +22,7 @@ use std::net::SocketAddr;
use std::sync::Arc;
use cua_driver_core::protocol::{Request, Response};
-use cua_driver_core::server::handle_request;
+use cua_driver_core::server::{handle_request, tool_observation_timer, StdioExecutionPath};
use cua_driver_core::tool::ToolRegistry;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream};
@@ -114,7 +114,26 @@ async fn dispatch(body: &[u8], registry: &Arc<ToolRegistry>) -> Option<String> {
}
let id = req.id.clone().unwrap_or(serde_json::Value::Null);
apply_session_identity(&mut req);
- Some(serialize(&handle_request(req, id, registry).await))
+ let timer = http_tool_observation_timer(&req, registry);
+ let response = handle_request(req, id, registry).await;
+ if let Some(timer) = timer {
+ crate::telemetry::capture_tool_completed(
+ timer.finish(&response),
+ crate::telemetry::Transport::McpHttp,
+ );
+ }
+ Some(serialize(&response))
+}
+
+fn http_tool_observation_timer(
+ req: &Request,
+ registry: &ToolRegistry,
+) -> Option<cua_driver_core::server::ToolObservationTimer> {
+ tool_observation_timer(
+ &req,
+ |name| name == "type_text_chars" || registry.get_def(name).is_some(),
+ StdioExecutionPath::InProcess,
+ )
}
fn serialize(resp: &Response) -> String {
@@ -261,6 +280,23 @@ mod tests {
assert!(args.get("arguments").unwrap().get("_session_id").is_none());
}
+ #[test]
+ fn http_observes_tool_calls_but_not_initialize_requests() {
+ let registry = ToolRegistry::new();
+ let tool_call: Request = serde_json::from_value(json!({
+ "jsonrpc": "2.0", "id": 1, "method": "tools/call",
+ "params": { "name": "unknown", "arguments": {} }
+ }))
+ .unwrap();
+ assert!(http_tool_observation_timer(&tool_call, &registry).is_some());
+
+ let initialize: Request = serde_json::from_value(json!({
+ "jsonrpc": "2.0", "id": 2, "method": "initialize", "params": {}
+ }))
+ .unwrap();
+ assert!(http_tool_observation_timer(&initialize, &registry).is_none());
+ }
+
#[test]
fn configured_port_parses_env() {
// Default (unset) → None is environment-dependent; just assert the parse
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs b/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs
index 992e095997..8b03aee0a9 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs
@@ -45,6 +45,7 @@ const ENV_TELEMETRY_HOME: &str = "CUA_DRIVER_TELEMETRY_HOME";
const ENV_CLI_WRAPPED_CHILD: &str = "CUA_DRIVER_CLI_TELEMETRY_CHILD";
const ENV_CLI_COMPLETION_WORKER: &str = "CUA_DRIVER_CLI_TELEMETRY_WORKER";
const ENV_CLI_COMPLETION_COMMAND: &str = "CUA_DRIVER_CLI_TELEMETRY_COMMAND";
+const ENV_CLI_COMPLETION_TOOL: &str = "CUA_DRIVER_CLI_TELEMETRY_TOOL";
const ENV_CLI_COMPLETION_EXIT_CODE: &str = "CUA_DRIVER_CLI_TELEMETRY_EXIT_CODE";
const ENV_CLI_COMPLETION_DURATION_MS: &str = "CUA_DRIVER_CLI_TELEMETRY_DURATION_MS";
const ENV_LIFECYCLE_WORKER: &str = "CUA_DRIVER_LIFECYCLE_TELEMETRY_WORKER";
@@ -54,39 +55,44 @@ pub const ENV_RELEASE_VERSION: &str = "CUA_DRIVER_RELEASE_VERSION";
pub mod event {
pub const INSTALLATION_REGISTERED: &str = "cua_driver_installation_registered";
pub const RELEASE_INSTALLED: &str = "cua_driver_release_installed";
- pub const MCP_START_LEGACY: &str = "cua_driver_mcp";
pub const SERVE_START_LEGACY: &str = "cua_driver_serve";
pub const CLI_COMPLETED: &str = "cua_driver_cli_completed";
pub const MCP_SESSION_STARTED: &str = "cua_driver_mcp_session_started";
pub const MCP_TOOL_COMPLETED: &str = "cua_driver_mcp_tool_completed";
+ pub const MCP_STARTUP_COMPLETED: &str = "cua_driver_mcp_startup_completed";
+ pub const PERMISSIONS_GATE_STARTED: &str = "cua_driver_permissions_gate_started";
+ pub const PERMISSIONS_GATE_DISMISSED: &str = "cua_driver_permissions_gate_dismissed";
+ pub const PERMISSIONS_GATE_COMPLETED: &str = "cua_driver_permissions_gate_completed";
}
const INSPECTABLE_EVENTS: &[&str] = &[
event::INSTALLATION_REGISTERED,
event::RELEASE_INSTALLED,
- event::MCP_START_LEGACY,
event::SERVE_START_LEGACY,
event::CLI_COMPLETED,
event::MCP_SESSION_STARTED,
event::MCP_TOOL_COMPLETED,
+ event::MCP_STARTUP_COMPLETED,
+ event::PERMISSIONS_GATE_STARTED,
+ event::PERMISSIONS_GATE_DISMISSED,
+ event::PERMISSIONS_GATE_COMPLETED,
];
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-#[allow(dead_code)] // HTTP is intentionally deferred until session semantics are defined.
pub enum Transport {
Cli,
+ Daemon,
McpStdio,
McpHttp,
- Unknown,
}
impl Transport {
fn as_str(self) -> &'static str {
match self {
Self::Cli => "cli",
+ Self::Daemon => "daemon",
Self::McpStdio => "mcp_stdio",
Self::McpHttp => "mcp_http",
- Self::Unknown => "unknown",
}
}
}
@@ -210,6 +216,7 @@ pub fn inspect_event(event_name: &str) -> Result<Value, String> {
}
event::CLI_COMPLETED => bounded_properties(&[
("command", Value::String("other".into())),
+ ("tool_name", Value::String("not_applicable".into())),
("success", Value::Bool(true)),
("exit_class", Value::String("success".into())),
("duration_bucket", Value::String("lt_100ms".into())),
@@ -237,10 +244,39 @@ pub fn inspect_event(event_name: &str) -> Result<Value, String> {
("output_type", Value::String("empty".into())),
("output_size_bucket", Value::String("0".into())),
]),
+ event::MCP_STARTUP_COMPLETED => bounded_properties(&[
+ ("path", Value::String("in_process".into())),
+ ("daemon", Value::String("not_applicable".into())),
+ ("success", Value::Bool(true)),
+ ("duration_bucket", Value::String("lt_100ms".into())),
+ ]),
+ event::PERMISSIONS_GATE_STARTED => bounded_properties(&[
+ ("missing_accessibility", Value::Bool(true)),
+ ("missing_screen_recording", Value::Bool(true)),
+ ]),
+ event::PERMISSIONS_GATE_DISMISSED => bounded_properties(&[
+ ("missing_accessibility", Value::Bool(true)),
+ ("missing_screen_recording", Value::Bool(true)),
+ ("duration_bucket", Value::String("2s_9_999ms".into())),
+ ]),
+ event::PERMISSIONS_GATE_COMPLETED => bounded_properties(&[
+ ("missing_accessibility", Value::Bool(true)),
+ ("missing_screen_recording", Value::Bool(true)),
+ ("panel_shown", Value::Bool(true)),
+ ("dismissed", Value::Bool(false)),
+ ("resolution", Value::String("granted".into())),
+ ("duration_bucket", Value::String("2s_9_999ms".into())),
+ ]),
_ => Map::new(),
};
let transport = match event_name {
- event::MCP_START_LEGACY | event::MCP_SESSION_STARTED | event::MCP_TOOL_COMPLETED => Transport::McpStdio,
+ event::MCP_SESSION_STARTED | event::MCP_TOOL_COMPLETED | event::MCP_STARTUP_COMPLETED => {
+ Transport::McpStdio
+ }
+ event::SERVE_START_LEGACY
+ | event::PERMISSIONS_GATE_STARTED
+ | event::PERMISSIONS_GATE_DISMISSED
+ | event::PERMISSIONS_GATE_COMPLETED => Transport::Daemon,
_ => Transport::Cli,
};
Ok(build_payload(event_name, &properties, &identity, transport))
@@ -248,7 +284,7 @@ pub fn inspect_event(event_name: &str) -> Result<Value, String> {
/// Transitional fixed start events for long-running processes only.
pub fn capture_start(event_name: &'static str, transport: Transport) {
- if !matches!(event_name, event::MCP_START_LEGACY | event::SERVE_START_LEGACY) {
+ if event_name != event::SERVE_START_LEGACY {
return;
}
capture_bounded(event_name, Map::new(), transport);
@@ -290,61 +326,181 @@ impl cua_driver_core::server::StdioObserver for TelemetryObserver {
}
fn on_tool_completed(&self, outcome: cua_driver_core::server::ToolCompletionObservation) {
- use cua_driver_core::server::{DurationBucket, OutputSizeBucket, OutputType, ToolErrorClass};
- let tool_name = if matches!(outcome.error_class, ToolErrorClass::UnknownTool | ToolErrorClass::InvalidParams) {
- "other".to_owned()
- } else if outcome.tool_name == "type_text_chars" {
- "type_text".to_owned()
- } else {
- outcome.tool_name
- };
- let error_class = match outcome.error_class {
- ToolErrorClass::None => "none",
- ToolErrorClass::InvalidParams => "invalid_params",
- ToolErrorClass::UnknownTool => "unknown_tool",
- ToolErrorClass::PermissionDenied => "permission_denied",
- ToolErrorClass::BackgroundUnavailable => "background_unavailable",
- ToolErrorClass::TransportError => "transport_error",
- ToolErrorClass::InternalError => "internal_error",
- };
- let duration_bucket = match outcome.duration_bucket {
- DurationBucket::Under10Ms => "lt_10ms",
- DurationBucket::Ms10To49 => "10_49ms",
- DurationBucket::Ms50To249 => "50_249ms",
- DurationBucket::Ms250To999 => "250_999ms",
- DurationBucket::Ms1000To4999 => "1_4s",
- DurationBucket::Ms5000OrMore => "gte_5s",
- };
- let output_type = match outcome.output_type {
- OutputType::Empty => "empty",
- OutputType::Text => "text",
- OutputType::Image => "image",
- OutputType::Mixed => "mixed",
- OutputType::Unknown => "unknown",
- };
- let output_size_bucket = match outcome.output_size_bucket {
- OutputSizeBucket::Empty => "0",
- OutputSizeBucket::Under1KiB => "lt_1kib",
- OutputSizeBucket::KiB1To9 => "1_9kib",
- OutputSizeBucket::KiB10To99 => "10_99kib",
- OutputSizeBucket::KiB100To1023 => "100_1023kib",
- OutputSizeBucket::MiB1OrMore => "gte_1mib",
- };
- capture_bounded(
- event::MCP_TOOL_COMPLETED,
- bounded_properties(&[
- ("tool_name", Value::String(tool_name)),
- ("success", Value::Bool(outcome.success)),
- ("error_class", Value::String(error_class.into())),
- ("duration_bucket", Value::String(duration_bucket.into())),
- ("output_type", Value::String(output_type.into())),
- ("output_size_bucket", Value::String(output_size_bucket.into())),
- ]),
- Transport::McpStdio,
- );
+ capture_tool_completed(outcome, Transport::McpStdio);
+ }
+}
+
+pub(crate) fn capture_tool_completed(
+ outcome: cua_driver_core::server::ToolCompletionObservation,
+ transport: Transport,
+) {
+ capture_bounded(
+ event::MCP_TOOL_COMPLETED,
+ tool_completion_properties(outcome),
+ transport,
+ );
+}
+
+fn tool_completion_properties(
+ outcome: cua_driver_core::server::ToolCompletionObservation,
+) -> Map<String, Value> {
+ use cua_driver_core::server::{DurationBucket, OutputSizeBucket, OutputType, ToolErrorClass};
+ let tool_name = if matches!(
+ outcome.error_class,
+ ToolErrorClass::UnknownTool | ToolErrorClass::InvalidParams
+ ) {
+ "other".to_owned()
+ } else if outcome.tool_name == "type_text_chars" {
+ "type_text".to_owned()
+ } else {
+ outcome.tool_name
+ };
+ let error_class = match outcome.error_class {
+ ToolErrorClass::None => "none",
+ ToolErrorClass::InvalidParams => "invalid_params",
+ ToolErrorClass::UnknownTool => "unknown_tool",
+ ToolErrorClass::PermissionDenied => "permission_denied",
+ ToolErrorClass::BackgroundUnavailable => "background_unavailable",
+ ToolErrorClass::TransportError => "transport_error",
+ ToolErrorClass::InternalError => "internal_error",
+ };
+ let duration_bucket = match outcome.duration_bucket {
+ DurationBucket::Under10Ms => "lt_10ms",
+ DurationBucket::Ms10To49 => "10_49ms",
+ DurationBucket::Ms50To249 => "50_249ms",
+ DurationBucket::Ms250To999 => "250_999ms",
+ DurationBucket::Ms1000To4999 => "1_4s",
+ DurationBucket::Ms5000OrMore => "gte_5s",
+ };
+ let output_type = match outcome.output_type {
+ OutputType::Empty => "empty",
+ OutputType::Text => "text",
+ OutputType::Image => "image",
+ OutputType::Mixed => "mixed",
+ OutputType::Unknown => "unknown",
+ };
+ let output_size_bucket = match outcome.output_size_bucket {
+ OutputSizeBucket::Empty => "0",
+ OutputSizeBucket::Under1KiB => "lt_1kib",
+ OutputSizeBucket::KiB1To9 => "1_9kib",
+ OutputSizeBucket::KiB10To99 => "10_99kib",
+ OutputSizeBucket::KiB100To1023 => "100_1023kib",
+ OutputSizeBucket::MiB1OrMore => "gte_1mib",
+ };
+ bounded_properties(&[
+ ("tool_name", Value::String(tool_name)),
+ ("success", Value::Bool(outcome.success)),
+ ("error_class", Value::String(error_class.into())),
+ ("duration_bucket", Value::String(duration_bucket.into())),
+ ("output_type", Value::String(output_type.into())),
+ ("output_size_bucket", Value::String(output_size_bucket.into())),
+ ])
+}
+
+pub(crate) fn capture_mcp_startup_completed(
+ path: &'static str,
+ daemon: &'static str,
+ success: bool,
+ elapsed: Duration,
+) {
+ let path = match path {
+ "in_process" => "in_process",
+ "daemon_proxy" => "daemon_proxy",
+ _ => "unknown",
+ };
+ let daemon = match daemon {
+ "not_applicable" => "not_applicable",
+ "already_running" => "already_running",
+ "launched" => "launched",
+ "launch_failed" => "launch_failed",
+ "launch_timeout" => "launch_timeout",
+ "unreachable" => "unreachable",
+ "unsupported_relaunch" => "unsupported_relaunch",
+ _ => "unknown",
+ };
+ capture_bounded(
+ event::MCP_STARTUP_COMPLETED,
+ bounded_properties(&[
+ ("path", Value::String(path.into())),
+ ("daemon", Value::String(daemon.into())),
+ ("success", Value::Bool(success)),
+ ("duration_bucket", Value::String(duration_bucket(elapsed).into())),
+ ]),
+ Transport::McpStdio,
+ );
+}
+
+pub(crate) fn capture_permissions_gate_completed(
+ missing_accessibility: bool,
+ missing_screen_recording: bool,
+ panel_shown: bool,
+ dismissed: bool,
+ resolution: &'static str,
+ elapsed: Duration,
+) {
+ let resolution = match resolution {
+ "granted" => "granted",
+ "dismissed_then_granted" => "dismissed_then_granted",
+ "timeout" => "timeout",
+ _ => "unknown",
+ };
+ capture_bounded(
+ event::PERMISSIONS_GATE_COMPLETED,
+ bounded_properties(&[
+ ("missing_accessibility", Value::Bool(missing_accessibility)),
+ ("missing_screen_recording", Value::Bool(missing_screen_recording)),
+ ("panel_shown", Value::Bool(panel_shown)),
+ ("dismissed", Value::Bool(dismissed)),
+ ("resolution", Value::String(resolution.into())),
+ ("duration_bucket", Value::String(duration_bucket(elapsed).into())),
+ ]),
+ Transport::Daemon,
+ );
+}
+
+pub(crate) const fn permissions_gate_resolution(
+ gate_failed: bool,
+ dismissed: bool,
+) -> &'static str {
+ if gate_failed {
+ "timeout"
+ } else if dismissed {
+ "dismissed_then_granted"
+ } else {
+ "granted"
}
}
+pub(crate) fn capture_permissions_gate_started(
+ missing_accessibility: bool,
+ missing_screen_recording: bool,
+) {
+ capture_bounded(
+ event::PERMISSIONS_GATE_STARTED,
+ bounded_properties(&[
+ ("missing_accessibility", Value::Bool(missing_accessibility)),
+ ("missing_screen_recording", Value::Bool(missing_screen_recording)),
+ ]),
+ Transport::Daemon,
+ );
+}
+
+pub(crate) fn capture_permissions_gate_dismissed(
+ missing_accessibility: bool,
+ missing_screen_recording: bool,
+ elapsed: Duration,
+) {
+ capture_bounded(
+ event::PERMISSIONS_GATE_DISMISSED,
+ bounded_properties(&[
+ ("missing_accessibility", Value::Bool(missing_accessibility)),
+ ("missing_screen_recording", Value::Bool(missing_screen_recording)),
+ ("duration_bucket", Value::String(duration_bucket(elapsed).into())),
+ ]),
+ Transport::Daemon,
+ );
+}
+
fn normalize_client(value: Option<&str>) -> String {
let normalized = value.unwrap_or("").trim().to_ascii_lowercase();
for (needle, canonical) in [
@@ -621,6 +777,7 @@ pub(crate) fn capture_bounded(
/// a detached request is delivered.
pub(crate) fn capture_cli_completed(
command: &'static str,
+ tool_name: Option<&str>,
exit_code: i32,
elapsed: Duration,
) {
@@ -648,6 +805,11 @@ pub(crate) fn capture_cli_completed(
_ => "other",
};
let success = exit_code == 0;
+ let tool_name = if command == "call" {
+ fixed_tool_name(tool_name.unwrap_or(""))
+ } else {
+ "not_applicable".into()
+ };
let exit_class = match exit_code {
0 => "success",
1 => "tool_error",
@@ -661,6 +823,7 @@ pub(crate) fn capture_cli_completed(
event::CLI_COMPLETED,
&bounded_properties(&[
("command", Value::String(command.into())),
+ ("tool_name", Value::String(tool_name.into())),
("success", Value::Bool(success)),
("exit_class", Value::String(exit_class.into())),
("duration_bucket", Value::String(duration_bucket(elapsed).into())),
@@ -699,12 +862,14 @@ pub(crate) fn run_cli_completion_worker_if_requested() -> bool {
.map(Duration::from_millis)
.unwrap_or_default();
let command = fixed_cli_command(&command);
- capture_cli_completed(command, exit_code, elapsed);
+ let tool_name = std::env::var(ENV_CLI_COMPLETION_TOOL).ok();
+ capture_cli_completed(command, tool_name.as_deref(), exit_code, elapsed);
true
}
pub(crate) fn spawn_cli_completion_worker(
command: &'static str,
+ tool_name: Option<&str>,
exit_code: i32,
elapsed: Duration,
) {
@@ -712,11 +877,16 @@ pub(crate) fn spawn_cli_completion_worker(
return;
}
let Ok(executable) = std::env::current_exe() else { return; };
- let _ = std::process::Command::new(executable)
+ let mut worker = std::process::Command::new(executable);
+ worker
.env(ENV_CLI_COMPLETION_WORKER, "1")
.env(ENV_CLI_COMPLETION_COMMAND, fixed_cli_command(command))
.env(ENV_CLI_COMPLETION_EXIT_CODE, exit_code.to_string())
- .env(ENV_CLI_COMPLETION_DURATION_MS, elapsed.as_millis().to_string())
+ .env(ENV_CLI_COMPLETION_DURATION_MS, elapsed.as_millis().to_string());
+ if let Some(tool_name) = tool_name {
+ worker.env(ENV_CLI_COMPLETION_TOOL, fixed_tool_name(tool_name));
+ }
+ let _ = worker
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
@@ -746,6 +916,21 @@ fn fixed_cli_command(command: &str) -> &'static str {
}
}
+fn fixed_tool_name(tool_name: &str) -> String {
+ if tool_name == "type_text_chars" {
+ return "type_text".into();
+ }
+ if cua_driver_core::tool::default_capabilities_for(tool_name).is_empty() {
+ "other".into()
+ } else {
+ // Every canonical tool is asserted by cua-driver-core tests to have a
+ // capability entry. Returning the original value is therefore safe:
+ // arbitrary argv can reach this branch only when it matches that
+ // compile-time registry vocabulary exactly.
+ tool_name.to_owned()
+ }
+}
+
pub(crate) fn bounded_properties(entries: &[(&str, Value)]) -> Map<String, Value> {
entries
.iter()
@@ -1509,6 +1694,36 @@ mod tests {
});
}
+ #[test]
+ fn disabled_permissions_events_do_not_create_an_installation_id() {
+ let _guard = ENV_LOCK.lock().unwrap();
+ with_isolated_home(|_| {
+ set_enabled(false).unwrap();
+ capture_permissions_gate_started(true, false);
+ capture_permissions_gate_dismissed(true, false, Duration::from_secs(3));
+ capture_permissions_gate_completed(
+ true,
+ false,
+ true,
+ true,
+ "dismissed_then_granted",
+ Duration::from_secs(3),
+ );
+ assert!(read_install_id().is_none());
+ });
+ }
+
+ #[test]
+ fn permissions_resolution_covers_grant_dismissal_recovery_and_timeout() {
+ assert_eq!(permissions_gate_resolution(false, false), "granted");
+ assert_eq!(
+ permissions_gate_resolution(false, true),
+ "dismissed_then_granted"
+ );
+ assert_eq!(permissions_gate_resolution(true, false), "timeout");
+ assert_eq!(permissions_gate_resolution(true, true), "timeout");
+ }
+
#[test]
fn lifecycle_markers_are_written_only_after_each_2xx() {
let _guard = ENV_LOCK.lock().unwrap();
@@ -1635,10 +1850,98 @@ mod tests {
let tool = inspect_event(event::MCP_TOOL_COMPLETED).unwrap();
assert_eq!(tool["properties"]["duration_bucket"], "lt_10ms");
- let mcp_start = inspect_event(event::MCP_START_LEGACY).unwrap();
+ let mcp_start = inspect_event(event::MCP_STARTUP_COMPLETED).unwrap();
assert_eq!(mcp_start["properties"]["transport"], "mcp_stdio");
+ assert_eq!(mcp_start["properties"]["path"], "in_process");
+ let permissions_started = inspect_event(event::PERMISSIONS_GATE_STARTED).unwrap();
+ assert_eq!(permissions_started["properties"]["transport"], "daemon");
+ assert_eq!(
+ permissions_started["properties"]["missing_accessibility"],
+ true
+ );
+ assert_eq!(
+ permissions_started["properties"]["missing_screen_recording"],
+ true
+ );
+ assert!(permissions_started["properties"]
+ .get("duration_bucket")
+ .is_none());
+ let permissions_dismissed = inspect_event(event::PERMISSIONS_GATE_DISMISSED).unwrap();
+ assert_eq!(permissions_dismissed["properties"]["transport"], "daemon");
+ assert_eq!(permissions_dismissed["properties"]["duration_bucket"], "2s_9_999ms");
+ let permissions = inspect_event(event::PERMISSIONS_GATE_COMPLETED).unwrap();
+ assert_eq!(permissions["properties"]["resolution"], "granted");
+ for payload in [
+ permissions_started,
+ permissions_dismissed,
+ permissions,
+ ] {
+ assert_eq!(payload["properties"]["telemetry_schema_version"], 3);
+ assert!(payload.get("timestamp").is_none());
+ let serialized = serde_json::to_string(&payload)
+ .unwrap()
+ .to_ascii_lowercase();
+ for forbidden in [
+ "prompt",
+ "arguments",
+ "result_text",
+ "typed_text",
+ "screenshot",
+ "accessibility_tree",
+ "window_title",
+ "application_name",
+ "file_path",
+ "socket",
+ "raw_error",
+ "stack_trace",
+ "$ip",
+ ] {
+ assert!(
+ !serialized.contains(forbidden),
+ "permissions payload contains {forbidden}: {serialized}"
+ );
+ }
+ }
let serve_start = inspect_event(event::SERVE_START_LEGACY).unwrap();
- assert_eq!(serve_start["properties"]["transport"], "cli");
+ assert_eq!(serve_start["properties"]["transport"], "daemon");
+ }
+
+ #[test]
+ fn http_tool_completion_reaches_the_final_payload_as_mcp_http() {
+ use cua_driver_core::server::{
+ DurationBucket, OutputSizeBucket, OutputType, ToolCompletionObservation,
+ ToolErrorClass,
+ };
+
+ let properties = tool_completion_properties(ToolCompletionObservation {
+ tool_name: "click".into(),
+ success: true,
+ error_class: ToolErrorClass::None,
+ duration_bucket: DurationBucket::Under10Ms,
+ output_type: OutputType::Text,
+ output_size_bucket: OutputSizeBucket::Under1KiB,
+ });
+ let payload = build_payload(
+ event::MCP_TOOL_COMPLETED,
+ &properties,
+ &InstallationIdentity {
+ id: "test-id".into(),
+ persisted: true,
+ },
+ Transport::McpHttp,
+ );
+
+ assert_eq!(payload["properties"]["transport"], "mcp_http");
+ assert_eq!(payload["properties"]["tool_name"], "click");
+ assert_eq!(payload["properties"]["success"], true);
+ }
+
+ #[test]
+ fn cli_tool_names_are_fixed_and_content_free() {
+ assert_eq!(fixed_tool_name("click"), "click");
+ assert_eq!(fixed_tool_name("type_text_chars"), "type_text");
+ assert_eq!(fixed_tool_name("../../private/secret"), "other");
+ assert_eq!(fixed_tool_name("https://example.com/private"), "other");
}
#[test]
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/permissions/gate.rs b/libs/cua-driver/rust/crates/platform-macos/src/permissions/gate.rs
index 6c27f72324..523385b29a 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/permissions/gate.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/permissions/gate.rs
@@ -32,6 +32,7 @@
//! more polished look — left as a follow-up; CLI is the MVP.
use std::io::Write;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use anyhow::Result;
@@ -199,6 +200,115 @@ const GATE_REEXEC_ENV: &str = "CUA_DRIVER_RS_GATE_REEXEC";
/// `start`, and since a re-exec fires (~25s) well before the deadline
/// (~10min) the deadline never triggers and the daemon re-execs forever.
const GATE_START_ENV: &str = "CUA_DRIVER_RS_GATE_START_UNIX";
+const GATE_TELEMETRY_START_MILLIS_ENV: &str = "CUA_DRIVER_RS_GATE_TELEMETRY_START_MILLIS";
+const GATE_ENGAGED_ARG: &str = "--cua-internal-gate-engaged";
+const GATE_MISSING_ACCESSIBILITY_ARG: &str = "--cua-internal-gate-missing-accessibility";
+const GATE_MISSING_SCREEN_RECORDING_ARG: &str = "--cua-internal-gate-missing-screen-recording";
+const GATE_PANEL_SHOWN_ARG: &str = "--cua-internal-gate-panel-shown";
+const GATE_PANEL_DISMISSED_ARG: &str = "--cua-internal-gate-panel-dismissed";
+
+static GATE_ENGAGED: AtomicBool = AtomicBool::new(false);
+static GATE_MISSING_ACCESSIBILITY: AtomicBool = AtomicBool::new(false);
+static GATE_MISSING_SCREEN_RECORDING: AtomicBool = AtomicBool::new(false);
+static GATE_PANEL_SHOWN: AtomicBool = AtomicBool::new(false);
+static GATE_PANEL_DISMISSED: AtomicBool = AtomicBool::new(false);
+static GATE_STARTED_REPORTED: AtomicBool = AtomicBool::new(false);
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct GateTelemetryContext {
+ pub engaged: bool,
+ pub missing_accessibility: bool,
+ pub missing_screen_recording: bool,
+ pub panel_shown: bool,
+ pub dismissed: bool,
+ pub elapsed: Duration,
+}
+
+/// Bounded progress signals emitted while an interactive permissions-gate
+/// episode is in flight. The binary owns telemetry delivery; this platform
+/// module reports only content-free state transitions plus the existing
+/// bounded gate context.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum GateProgress {
+ Started,
+ Dismissed,
+}
+
+pub fn is_gate_reexec() -> bool {
+ std::env::var_os(GATE_REEXEC_ENV).is_some()
+}
+
+fn has_internal_arg(value: &str) -> bool {
+ std::env::args_os().any(|arg| arg == value)
+}
+
+/// Return only the bounded state needed by the binary's telemetry layer. The
+/// start time plus bounded hidden argv flags survive the TCC cache-clearing
+/// re-exec loop, allowing one terminal event for the whole gate episode.
+pub fn telemetry_context() -> GateTelemetryContext {
+ let engaged = GATE_ENGAGED.load(Ordering::Relaxed) || has_internal_arg(GATE_ENGAGED_ARG);
+ let missing_accessibility = GATE_MISSING_ACCESSIBILITY.load(Ordering::Relaxed)
+ || has_internal_arg(GATE_MISSING_ACCESSIBILITY_ARG);
+ let missing_screen_recording = GATE_MISSING_SCREEN_RECORDING.load(Ordering::Relaxed)
+ || has_internal_arg(GATE_MISSING_SCREEN_RECORDING_ARG);
+ let started = std::env::var(GATE_START_ENV)
+ .ok()
+ .and_then(|value| value.parse::<u64>().ok());
+ let telemetry_started = std::env::var(GATE_TELEMETRY_START_MILLIS_ENV)
+ .ok()
+ .and_then(|value| value.parse::<u128>().ok());
+ let elapsed = telemetry_started
+ .and_then(|started| {
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .ok()
+ .map(|now| Duration::from_millis(now.as_millis().saturating_sub(started) as u64))
+ })
+ .unwrap_or_default();
+ GateTelemetryContext {
+ engaged: started.is_some() && engaged && (missing_accessibility || missing_screen_recording),
+ missing_accessibility,
+ missing_screen_recording,
+ panel_shown: GATE_PANEL_SHOWN.load(Ordering::Relaxed) || has_internal_arg(GATE_PANEL_SHOWN_ARG),
+ dismissed: GATE_PANEL_DISMISSED.load(Ordering::Relaxed) || has_internal_arg(GATE_PANEL_DISMISSED_ARG),
+ elapsed,
+ }
+}
+
+fn begin_gate_episode(initial: PermissionsStatus) {
+ let already_engaged = GATE_ENGAGED.swap(true, Ordering::Relaxed)
+ || has_internal_arg(GATE_ENGAGED_ARG);
+ if !already_engaged {
+ GATE_MISSING_ACCESSIBILITY.store(!initial.accessibility, Ordering::Relaxed);
+ GATE_MISSING_SCREEN_RECORDING.store(!initial.screen_recording, Ordering::Relaxed);
+ }
+ if std::env::var_os(GATE_START_ENV).is_none() {
+ if let Ok(now) = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
+ std::env::set_var(GATE_START_ENV, now.as_secs().to_string());
+ std::env::set_var(GATE_TELEMETRY_START_MILLIS_ENV, now.as_millis().to_string());
+ }
+ }
+}
+
+/// Initialize the environment-backed gate timestamps before the daemon starts
+/// any background threads. Later panel state is held in atomics and copied to
+/// bounded hidden argv flags only at re-exec time. A returned `Started`
+/// transition belongs to this first probe and should be delivered before the
+/// caller performs other startup work.
+pub fn prepare_telemetry_context(
+ opt_out: bool,
+) -> Option<(GateProgress, GateTelemetryContext)> {
+ if opt_out || is_gate_reexec() || std::env::var_os(GATE_START_ENV).is_some() {
+ return None;
+ }
+ let initial = current_status();
+ if !initial.all_granted() {
+ begin_gate_episode(initial);
+ GATE_STARTED_REPORTED.store(true, Ordering::Relaxed);
+ return Some((GateProgress::Started, telemetry_context()));
+ }
+ None
+}
/// Run the gate if needed. When called and the process already has both
/// grants, this returns immediately without printing anything — the
@@ -217,6 +327,16 @@ const GATE_START_ENV: &str = "CUA_DRIVER_RS_GATE_START_UNIX";
/// with their existing error messages, mirroring Swift's "user closes
/// the panel" path.
pub fn run_if_needed(opts: GateOpts) -> Result<()> {
+ run_if_needed_with_observer(opts, |_, _| {})
+}
+
+/// Run the gate while reporting bounded progress transitions to `observer`.
+/// The first process reports `Started`; TCC cache-refresh re-execs skip it.
+/// `Dismissed` is reported as soon as the native panel returns that outcome.
+pub fn run_if_needed_with_observer<F>(opts: GateOpts, mut observer: F) -> Result<()>
+where
+ F: FnMut(GateProgress, GateTelemetryContext),
+{
if opts.opt_out {
tracing::debug!("permissions gate skipped (opt_out=true)");
return Ok(());
@@ -228,6 +348,17 @@ pub fn run_if_needed(opts: GateOpts) -> Result<()> {
// the user sees nothing different from before this gate existed.
return Ok(());
}
+ begin_gate_episode(initial);
+
+ let gate_reexec = is_gate_reexec();
+ if should_report_started(
+ initial,
+ gate_reexec,
+ GATE_STARTED_REPORTED.load(Ordering::Relaxed),
+ ) {
+ GATE_STARTED_REPORTED.store(true, Ordering::Relaxed);
+ observer(GateProgress::Started, telemetry_context());
+ }
// A gate re-exec (`wait_for_grants` restarts the daemon ~every 25s to
// refresh the per-process TCC trust cache) re-runs this function. The
@@ -236,7 +367,7 @@ pub fn run_if_needed(opts: GateOpts) -> Result<()> {
// user (forever, since a stale/never-granted state keeps re-execing). A
// re-exec'd process polls SILENTLY instead — skip the prompts + panel and
// go straight to the wait loop, which re-checks the grant and re-execs.
- if std::env::var(GATE_REEXEC_ENV).is_ok() {
+ if gate_reexec {
return wait_for_grants(&opts);
}
@@ -285,6 +416,13 @@ pub fn run_if_needed(opts: GateOpts) -> Result<()> {
// * `ShownAllGranted` — the panel's poll loop saw both grants
// flip green; skip the wait loop entirely.
let presentation = present_panel_if_available(initial);
+ if presentation != PanelPresentation::NotShown {
+ GATE_PANEL_SHOWN.store(true, Ordering::Relaxed);
+ }
+ if progress_for_presentation(presentation) == Some(GateProgress::Dismissed) {
+ GATE_PANEL_DISMISSED.store(true, Ordering::Relaxed);
+ observer(GateProgress::Dismissed, telemetry_context());
+ }
let should_auto_open_settings;
let skip_wait_loop;
match presentation {
@@ -321,6 +459,23 @@ pub fn run_if_needed(opts: GateOpts) -> Result<()> {
wait_for_grants(&opts)
}
+fn should_report_started(
+ initial: PermissionsStatus,
+ gate_reexec: bool,
+ already_reported: bool,
+) -> bool {
+ !initial.all_granted() && !gate_reexec && !already_reported
+}
+
+fn progress_for_presentation(presentation: PanelPresentation) -> Option<GateProgress> {
+ match presentation {
+ PanelPresentation::ShownDismissed => Some(GateProgress::Dismissed),
+ PanelPresentation::NotShown
+ | PanelPresentation::ShownOpenSettings
+ | PanelPresentation::ShownAllGranted => None,
+ }
+}
+
/// Outcome of a panel-present attempt. Drives the subsequent flow in
/// [`run_if_needed`] — see comments at the call site.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -511,7 +666,20 @@ fn reexec_self() {
eprintln!("[cua-driver] re-exec failed: cannot resolve current_exe");
return;
};
- let argv: Vec<CString> = std::env::args_os()
+ let mut raw_argv: Vec<std::ffi::OsString> = std::env::args_os().collect();
+ for (enabled, flag) in [
+ (GATE_ENGAGED.load(Ordering::Relaxed), GATE_ENGAGED_ARG),
+ (GATE_MISSING_ACCESSIBILITY.load(Ordering::Relaxed), GATE_MISSING_ACCESSIBILITY_ARG),
+ (GATE_MISSING_SCREEN_RECORDING.load(Ordering::Relaxed), GATE_MISSING_SCREEN_RECORDING_ARG),
+ (GATE_PANEL_SHOWN.load(Ordering::Relaxed), GATE_PANEL_SHOWN_ARG),
+ (GATE_PANEL_DISMISSED.load(Ordering::Relaxed), GATE_PANEL_DISMISSED_ARG),
+ ] {
+ if enabled && !raw_argv.iter().any(|arg| arg == flag) {
+ raw_argv.push(flag.into());
+ }
+ }
+ let argv: Vec<CString> = raw_argv
+ .into_iter()
.filter_map(|a| CString::new(a.into_vec()).ok())
.collect();
if argv.is_empty() {
@@ -604,6 +772,44 @@ mod tests {
crate::permissions::test_env_lock()
}
+ fn clear_telemetry_env() {
+ for name in [
+ GATE_REEXEC_ENV,
+ GATE_START_ENV,
+ GATE_TELEMETRY_START_MILLIS_ENV,
+ ] {
+ std::env::remove_var(name);
+ }
+ GATE_ENGAGED.store(false, Ordering::Relaxed);
+ GATE_MISSING_ACCESSIBILITY.store(false, Ordering::Relaxed);
+ GATE_MISSING_SCREEN_RECORDING.store(false, Ordering::Relaxed);
+ GATE_PANEL_SHOWN.store(false, Ordering::Relaxed);
+ GATE_PANEL_DISMISSED.store(false, Ordering::Relaxed);
+ GATE_STARTED_REPORTED.store(false, Ordering::Relaxed);
+ }
+
+ #[test]
+ fn telemetry_context_is_bounded_and_survives_reexec_state() {
+ let _guard = env_lock();
+ clear_telemetry_env();
+ std::env::set_var(GATE_START_ENV, "1");
+ std::env::set_var(GATE_TELEMETRY_START_MILLIS_ENV, "1");
+ GATE_ENGAGED.store(true, Ordering::Relaxed);
+ GATE_MISSING_ACCESSIBILITY.store(true, Ordering::Relaxed);
+ GATE_PANEL_SHOWN.store(true, Ordering::Relaxed);
+ GATE_PANEL_DISMISSED.store(true, Ordering::Relaxed);
+ std::env::set_var(GATE_REEXEC_ENV, "1");
+
+ let context = telemetry_context();
+ assert!(context.engaged);
+ assert!(context.missing_accessibility);
+ assert!(!context.missing_screen_recording);
+ assert!(context.panel_shown);
+ assert!(context.dismissed);
+ assert!(is_gate_reexec());
+ clear_telemetry_env();
+ }
+
#[test]
fn opt_out_short_circuits_run_if_needed() {
// With opt_out=true the gate must return Ok(()) without touching
@@ -619,7 +825,82 @@ mod tests {
also_raise_prompts: false,
open_settings: false,
};
- assert!(run_if_needed(opts).is_ok());
+ let mut observed = Vec::new();
+ assert!(run_if_needed_with_observer(opts, |progress, _| {
+ observed.push(progress);
+ })
+ .is_ok());
+ assert!(observed.is_empty());
+ }
+
+ #[test]
+ fn started_progress_covers_each_missing_permission_combination_once() {
+ for initial in [
+ PermissionsStatus {
+ accessibility: false,
+ screen_recording: true,
+ },
+ PermissionsStatus {
+ accessibility: true,
+ screen_recording: false,
+ },
+ PermissionsStatus {
+ accessibility: false,
+ screen_recording: false,
+ },
+ ] {
+ assert!(should_report_started(initial, false, false));
+ assert!(
+ !should_report_started(initial, true, false),
+ "re-exec must not repeat start"
+ );
+ assert!(
+ !should_report_started(initial, false, true),
+ "an already reported episode must not repeat start"
+ );
+ }
+ assert!(!should_report_started(
+ PermissionsStatus {
+ accessibility: true,
+ screen_recording: true,
+ },
+ false,
+ false,
+ ));
+ }
+
+ #[test]
+ fn gate_episode_keeps_the_first_missing_permission_snapshot() {
+ let _guard = env_lock();
+ clear_telemetry_env();
+ begin_gate_episode(PermissionsStatus {
+ accessibility: false,
+ screen_recording: false,
+ });
+ begin_gate_episode(PermissionsStatus {
+ accessibility: true,
+ screen_recording: false,
+ });
+
+ let context = telemetry_context();
+ assert!(context.missing_accessibility);
+ assert!(context.missing_screen_recording);
+ clear_telemetry_env();
+ }
+
+ #[test]
+ fn dismissed_progress_is_only_reported_for_explicit_panel_exit() {
+ assert_eq!(
+ progress_for_presentation(PanelPresentation::ShownDismissed),
+ Some(GateProgress::Dismissed)
+ );
+ for presentation in [
+ PanelPresentation::NotShown,
+ PanelPresentation::ShownOpenSettings,
+ PanelPresentation::ShownAllGranted,
+ ] {
+ assert_eq!(progress_for_presentation(presentation), None);
+ }
}
#[test]
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/permissions/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/permissions/mod.rs
index c5061e689c..ae054b3a56 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/permissions/mod.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/permissions/mod.rs
@@ -23,7 +23,9 @@ pub mod status;
pub mod panel;
pub use status::{PermissionsStatus, current_status};
-pub use gate::{GateOpts, MissingPermission, run_if_needed};
+pub use gate::{
+ GateOpts, GateProgress, MissingPermission, run_if_needed, run_if_needed_with_observer,
+};
/// Crate-wide lock serializing tests that mutate process-global env vars.
/// Per-module locks are not enough: `gate` and `check_permissions` tests