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 browser mutations

trycua-release[bot]b4007a8442d3
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/cdp_ws.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/cdp_ws.rs
index c36d2ae2a6..793a173feb 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/cdp_ws.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/cdp_ws.rs
@@ -67,6 +67,7 @@ pub struct CdpEvent {
pub struct CdpDialogState {
pub generation: u64,
pub kind: String,
+ pub session_id: String,
}
/// What the reader routed back for one in-flight call.
@@ -79,6 +80,7 @@ enum CallOutcome {
struct Demux {
pending: StdMutex<HashMap<u64, oneshot::Sender<CallOutcome>>>,
subscribers: StdMutex<Vec<mpsc::UnboundedSender<CdpEvent>>>,
+ session_targets: StdMutex<HashMap<String, String>>,
dialogs: StdMutex<HashMap<String, CdpDialogState>>,
next_dialog_generation: AtomicU64,
closed: AtomicBool,
@@ -91,6 +93,7 @@ impl Demux {
// error, which `call` reports as a closed socket.
self.pending.lock().unwrap().clear();
self.subscribers.lock().unwrap().clear();
+ self.session_targets.lock().unwrap().clear();
self.dialogs.lock().unwrap().clear();
}
}
@@ -138,6 +141,12 @@ async fn read_loop(mut read: SplitStream<WsStream>, demux: Arc<Demux>) {
params: v.get("params").cloned().unwrap_or(Value::Null),
};
if let Some(session_id) = event.session_id.as_deref() {
+ let target_id = demux
+ .session_targets
+ .lock()
+ .unwrap()
+ .get(session_id)
+ .cloned();
match event.method.as_str() {
"Page.javascriptDialogOpening" => {
let kind = match event.params.get("type").and_then(Value::as_str) {
@@ -149,16 +158,21 @@ async fn read_loop(mut read: SplitStream<WsStream>, demux: Arc<Demux>) {
};
let generation =
demux.next_dialog_generation.fetch_add(1, Ordering::Relaxed);
- demux.dialogs.lock().unwrap().insert(
- session_id.to_owned(),
- CdpDialogState {
- generation,
- kind: kind.to_owned(),
- },
- );
+ if let Some(target_id) = target_id {
+ demux.dialogs.lock().unwrap().insert(
+ target_id,
+ CdpDialogState {
+ generation,
+ kind: kind.to_owned(),
+ session_id: session_id.to_owned(),
+ },
+ );
+ }
}
"Page.javascriptDialogClosed" => {
- demux.dialogs.lock().unwrap().remove(session_id);
+ if let Some(target_id) = target_id {
+ demux.dialogs.lock().unwrap().remove(&target_id);
+ }
}
_ => {}
}
@@ -199,6 +213,7 @@ impl CdpConnection {
let demux = Arc::new(Demux {
pending: StdMutex::new(HashMap::new()),
subscribers: StdMutex::new(Vec::new()),
+ session_targets: StdMutex::new(HashMap::new()),
dialogs: StdMutex::new(HashMap::new()),
next_dialog_generation: AtomicU64::new(1),
closed: AtomicBool::new(false),
@@ -229,14 +244,39 @@ impl CdpConnection {
rx
}
- pub fn dialog_state(&self, session_id: &str) -> Option<CdpDialogState> {
- self.demux.dialogs.lock().unwrap().get(session_id).cloned()
+ /// Associate the one Page-enabled dialog session with its exact target.
+ /// Later calls may use fresh attachment sessions, but dialog events keep
+ /// arriving on this bounded, persistent event session.
+ pub fn register_dialog_session(&self, session_id: &str, target_id: &str) {
+ let mut sessions = self.demux.session_targets.lock().unwrap();
+ sessions.retain(|_, mapped_target| mapped_target != target_id);
+ sessions.insert(session_id.to_owned(), target_id.to_owned());
}
- pub fn clear_dialog_state(&self, session_id: &str, generation: u64) {
+ pub fn unregister_dialog_session(&self, session_id: &str, target_id: &str) {
+ let mut sessions = self.demux.session_targets.lock().unwrap();
+ if sessions.get(session_id).map(String::as_str) == Some(target_id) {
+ sessions.remove(session_id);
+ }
+ }
+
+ pub fn has_dialog_session(&self, target_id: &str) -> bool {
+ self.demux
+ .session_targets
+ .lock()
+ .unwrap()
+ .values()
+ .any(|mapped_target| mapped_target == target_id)
+ }
+
+ pub fn dialog_state(&self, target_id: &str) -> Option<CdpDialogState> {
+ self.demux.dialogs.lock().unwrap().get(target_id).cloned()
+ }
+
+ pub fn clear_dialog_state(&self, target_id: &str, generation: u64) {
let mut dialogs = self.demux.dialogs.lock().unwrap();
- if dialogs.get(session_id).map(|state| state.generation) == Some(generation) {
- dialogs.remove(session_id);
+ if dialogs.get(target_id).map(|state| state.generation) == Some(generation) {
+ dialogs.remove(target_id);
}
}
@@ -644,7 +684,7 @@ mod tests {
let server = MockCdpServer::start(StdArc::new(|call| match call.method.as_str() {
"Dialog.open" => MockReply::ok(json!({})).with_events(vec![MockEvent {
method: "Page.javascriptDialogOpening".into(),
- session_id: Some("tab-session".into()),
+ session_id: call.session_id.clone(),
params: json!({
"type": "prompt",
"message": "private dialog text",
@@ -653,23 +693,25 @@ mod tests {
}]),
"Dialog.close" => MockReply::ok(json!({})).with_events(vec![MockEvent {
method: "Page.javascriptDialogClosed".into(),
- session_id: Some("tab-session".into()),
+ session_id: call.session_id.clone(),
params: json!({}),
}]),
_ => MockReply::ok(json!({})),
}))
.await;
let conn = CdpConnection::connect(&server.ws_url()).await.unwrap();
- conn.call(Some("tab-session"), "Dialog.open", json!({}))
+ conn.register_dialog_session("tab-session-a", "page-target");
+ conn.call(Some("tab-session-a"), "Dialog.open", json!({}))
.await
.unwrap();
- let dialog = conn.dialog_state("tab-session").expect("dialog journaled");
+ let dialog = conn.dialog_state("page-target").expect("dialog journaled");
assert_eq!(dialog.kind, "prompt");
+ assert_eq!(dialog.session_id, "tab-session-a");
assert!(!format!("{dialog:?}").contains("private"));
- conn.call(Some("tab-session"), "Dialog.close", json!({}))
+ conn.call(Some("tab-session-a"), "Dialog.close", json!({}))
.await
.unwrap();
- assert!(conn.dialog_state("tab-session").is_none());
+ assert!(conn.dialog_state("page-target").is_none());
}
#[tokio::test]
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/download.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/download.rs
new file mode 100644
index 0000000000..ae33e93d3d
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/download.rs
@@ -0,0 +1,557 @@
+//! Approval-gated downloads for exact browser tab and element capabilities.
+//!
+//! Chromium's download behavior is browser-wide, so this tool enables it only
+//! for the bounded interval around one exact ref mutation and restores the
+//! default before returning. Output deliberately omits URLs, filenames, and
+//! local paths.
+
+use std::path::{Component, Path, PathBuf};
+use std::sync::{Arc, OnceLock};
+use std::time::Duration;
+
+use async_trait::async_trait;
+use serde_json::{json, Value};
+
+use crate::protocol::ToolResult;
+use crate::tool::{Tool, ToolDef};
+use crate::tool_args::ArgsExt;
+
+use super::cdp_ws::CdpConnection;
+use super::engine::BrowserEngine;
+use super::refusal::{BrowserRefusal, BrowserRefusalCode};
+use super::store::BrowserActionKind;
+
+/// Injected by an MCP host only after its destructive-tool approval flow.
+/// It is intentionally absent from the public input schema.
+pub const MCP_HOST_DOWNLOAD_APPROVAL_ARG: &str = "_cua_browser_download_mcp_host_approved";
+
+const DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(30);
+
+fn browser_download_gate() -> &'static tokio::sync::Mutex<()> {
+ static GATE: OnceLock<tokio::sync::Mutex<()>> = OnceLock::new();
+ GATE.get_or_init(|| tokio::sync::Mutex::new(()))
+}
+
+pub struct BrowserDownloadTool {
+ def: ToolDef,
+ engine: Arc<BrowserEngine>,
+}
+
+impl BrowserDownloadTool {
+ pub fn new(engine: Arc<BrowserEngine>) -> Self {
+ Self {
+ def: ToolDef {
+ name: "browser_download".into(),
+ description: "Trigger one download through an exact live browser ref and save it inside an explicitly approved directory. Requires MCP-host destructive-tool approval, refuses ambiguous or stale capabilities, and never returns the source URL, filename, or destination path.".into(),
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "session": {
+ "type": "string",
+ "description": "Explicit caller session owning the browser capabilities."
+ },
+ "target_id": {
+ "type": "string",
+ "description": "Opaque exact browser target id from get_browser_state."
+ },
+ "tab_id": {
+ "type": "string",
+ "description": "Opaque exact tab id from get_browser_state."
+ },
+ "ref": {
+ "type": "string",
+ "description": "Live page ref whose activation initiates the download."
+ },
+ "destination_root": {
+ "type": "string",
+ "description": "Absolute, existing, canonical directory approved to receive the download."
+ }
+ },
+ "required": ["session", "target_id", "tab_id", "ref", "destination_root"],
+ "additionalProperties": true
+ }),
+ read_only: false,
+ destructive: true,
+ idempotent: false,
+ open_world: true,
+ },
+ engine,
+ }
+ }
+}
+
+fn consent_required() -> ToolResult {
+ BrowserRefusal::new(
+ BrowserRefusalCode::BrowserConsentRequired,
+ "browser_download requires approval through the MCP host's destructive-tool confirmation flow",
+ )
+ .to_tool_result()
+}
+
+fn explicit_session(args: &Value) -> Result<String, ToolResult> {
+ let session = args.require_str("session")?;
+ if session.trim().is_empty() || session == "default" {
+ return Err(ToolResult::error(
+ "browser_download requires an explicit non-default session",
+ ));
+ }
+ Ok(session)
+}
+
+fn validate_destination_root(raw: &str) -> Result<PathBuf, ToolResult> {
+ let path = Path::new(raw);
+ if !path.is_absolute() {
+ return Err(ToolResult::error("destination_root must be absolute"));
+ }
+
+ let metadata = std::fs::symlink_metadata(path)
+ .map_err(|_| ToolResult::error("destination_root must be an existing directory"))?;
+ if metadata.file_type().is_symlink() {
+ return Err(ToolResult::error(
+ "destination_root must name the directory directly, not a symlink",
+ ));
+ }
+ if !metadata.is_dir() {
+ return Err(ToolResult::error(
+ "destination_root must be an existing directory",
+ ));
+ }
+
+ let canonical = std::fs::canonicalize(path)
+ .map_err(|_| ToolResult::error("destination_root could not be canonicalized"))?;
+ if canonical != path {
+ return Err(ToolResult::error(
+ "destination_root must already be in canonical form",
+ ));
+ }
+ Ok(canonical)
+}
+
+fn main_frame_id(frame_tree: &Value) -> Option<&str> {
+ frame_tree
+ .get("frameTree")?
+ .get("frame")?
+ .get("id")?
+ .as_str()
+}
+
+fn is_safe_guid(guid: &str) -> bool {
+ let mut components = Path::new(guid).components();
+ matches!(components.next(), Some(Component::Normal(_))) && components.next().is_none()
+}
+
+fn completed_download_size(root: &Path, guid: &str) -> Result<u64, BrowserRefusal> {
+ if !is_safe_guid(guid) {
+ return Err(BrowserRefusal::new(
+ BrowserRefusalCode::BrowserActionUnavailable,
+ "the browser returned an invalid opaque download id",
+ ));
+ }
+ let file = root.join(guid);
+ let metadata = std::fs::symlink_metadata(&file).map_err(|_| {
+ BrowserRefusal::new(
+ BrowserRefusalCode::BrowserActionUnavailable,
+ "the completed download could not be proven inside the approved directory",
+ )
+ })?;
+ if metadata.file_type().is_symlink() || !metadata.is_file() {
+ return Err(BrowserRefusal::new(
+ BrowserRefusalCode::BrowserActionUnavailable,
+ "the completed download is not a direct regular file",
+ ));
+ }
+ let canonical = std::fs::canonicalize(&file).map_err(|_| {
+ BrowserRefusal::new(
+ BrowserRefusalCode::BrowserActionUnavailable,
+ "the completed download could not be canonicalized",
+ )
+ })?;
+ if canonical.parent() != Some(root) {
+ return Err(BrowserRefusal::new(
+ BrowserRefusalCode::BrowserActionUnavailable,
+ "the completed download escaped the approved directory",
+ ));
+ }
+ Ok(metadata.len())
+}
+
+async fn reset_download_behavior(conn: &CdpConnection) {
+ let _ = conn
+ .call(
+ None,
+ "Browser.setDownloadBehavior",
+ json!({ "behavior": "default", "eventsEnabled": false }),
+ )
+ .await;
+}
+
+enum DownloadEventOutcome {
+ Completed { guid: String },
+ Canceled { guid: String },
+ EventStreamClosed,
+}
+
+async fn await_download(
+ events: &mut tokio::sync::mpsc::UnboundedReceiver<super::cdp_ws::CdpEvent>,
+ expected_frame_id: &str,
+ observed_guid: &mut Option<String>,
+) -> DownloadEventOutcome {
+ while let Some(event) = events.recv().await {
+ match event.method.as_str() {
+ "Browser.downloadWillBegin" if observed_guid.is_none() => {
+ if event.params.get("frameId").and_then(Value::as_str) != Some(expected_frame_id) {
+ continue;
+ }
+ *observed_guid = event
+ .params
+ .get("guid")
+ .and_then(Value::as_str)
+ .map(str::to_owned);
+ }
+ "Browser.downloadProgress" => {
+ let Some(guid) = observed_guid.as_deref() else {
+ continue;
+ };
+ if event.params.get("guid").and_then(Value::as_str) != Some(guid) {
+ continue;
+ }
+ match event.params.get("state").and_then(Value::as_str) {
+ Some("completed") => {
+ return DownloadEventOutcome::Completed {
+ guid: guid.to_owned(),
+ }
+ }
+ Some("canceled") => {
+ return DownloadEventOutcome::Canceled {
+ guid: guid.to_owned(),
+ }
+ }
+ _ => {}
+ }
+ }
+ _ => {}
+ }
+ }
+ DownloadEventOutcome::EventStreamClosed
+}
+
+fn remove_proven_partial(root: &Path, guid: Option<&str>) {
+ let Some(guid) = guid.filter(|guid| is_safe_guid(guid)) else {
+ return;
+ };
+ let path = root.join(guid);
+ let Ok(metadata) = std::fs::symlink_metadata(&path) else {
+ return;
+ };
+ if metadata.file_type().is_symlink() || !metadata.is_file() {
+ return;
+ }
+ let Ok(canonical) = std::fs::canonicalize(&path) else {
+ return;
+ };
+ if canonical.parent() == Some(root) {
+ let _ = std::fs::remove_file(canonical);
+ }
+}
+
+#[async_trait]
+impl Tool for BrowserDownloadTool {
+ fn def(&self) -> &ToolDef {
+ &self.def
+ }
+
+ async fn invoke(&self, args: Value) -> ToolResult {
+ let (session, target_id, tab_id, ext_ref, destination_raw) = match (
+ explicit_session(&args),
+ args.require_str("target_id"),
+ args.require_str("tab_id"),
+ args.require_str("ref"),
+ args.require_str("destination_root"),
+ ) {
+ (Ok(session), Ok(target), Ok(tab), Ok(ext_ref), Ok(destination)) => {
+ (session, target, tab, ext_ref, destination)
+ }
+ (Err(error), _, _, _, _)
+ | (_, Err(error), _, _, _)
+ | (_, _, Err(error), _, _)
+ | (_, _, _, Err(error), _)
+ | (_, _, _, _, Err(error)) => return error,
+ };
+
+ if args
+ .get(MCP_HOST_DOWNLOAD_APPROVAL_ARG)
+ .and_then(Value::as_bool)
+ != Some(true)
+ {
+ return consent_required();
+ }
+ let destination_root = match validate_destination_root(&destination_raw) {
+ Ok(root) => root,
+ Err(error) => return error,
+ };
+
+ let _mutation = match self
+ .engine
+ .lock_mutation(&session, &target_id, &tab_id)
+ .await
+ {
+ Ok(guard) => guard,
+ Err(refusal) => return refusal.to_tool_result(),
+ };
+ // Download routing is browser-wide rather than tab-scoped. Serialize
+ // these bounded mutations process-wide so two exact tabs cannot race
+ // to replace each other's approved destination.
+ let _download_mutation = browser_download_gate().lock().await;
+ let validated = match self
+ .engine
+ .revalidate_for_mutation(&session, &target_id, Some(&tab_id))
+ .await
+ {
+ Ok(validated) => validated,
+ Err(refusal) => return refusal.to_tool_result(),
+ };
+ let entry = match self
+ .engine
+ .store
+ .resolve_ref(&session, &target_id, &tab_id, &ext_ref)
+ {
+ Ok(entry) => entry,
+ Err(refusal) => return refusal.to_tool_result(),
+ };
+ if entry.semantic && !entry.actions.contains(&BrowserActionKind::Click) {
+ return BrowserRefusal::new(
+ BrowserRefusalCode::BrowserActionUnavailable,
+ "the semantic ref does not declare an activation action",
+ )
+ .to_tool_result();
+ }
+ let ref_session = match self
+ .engine
+ .frame_session_for_mutation(&session, &target_id, &tab_id, &validated, &entry.frame)
+ .await
+ {
+ Ok(session) => session,
+ Err(refusal) => return refusal.to_tool_result(),
+ };
+
+ let frame_tree = match validated
+ .conn
+ .call(Some(&validated.cdp_session), "Page.getFrameTree", json!({}))
+ .await
+ {
+ Ok(tree) => tree,
+ Err(_) => {
+ return BrowserRefusal::new(
+ BrowserRefusalCode::BrowserRouteUnavailable,
+ "the exact tab's main frame could not be proven",
+ )
+ .to_tool_result()
+ }
+ };
+ let Some(main_frame_id) = main_frame_id(&frame_tree).map(str::to_owned) else {
+ return BrowserRefusal::new(
+ BrowserRefusalCode::BrowserRouteUnavailable,
+ "Page.getFrameTree did not identify the exact tab's main frame",
+ )
+ .to_tool_result();
+ };
+ let expected_frame_id = entry
+ .frame
+ .identity
+ .as_ref()
+ .map(|identity| identity.frame_id.clone())
+ .unwrap_or(main_frame_id);
+
+ let resolved = match validated
+ .conn
+ .call(
+ Some(&ref_session),
+ "DOM.resolveNode",
+ json!({ "backendNodeId": entry.backend_node_id }),
+ )
+ .await
+ {
+ Ok(resolved) => resolved,
+ Err(_) => {
+ return BrowserRefusal::new(
+ BrowserRefusalCode::BrowserRefStale,
+ "the download ref no longer resolves in the live page",
+ )
+ .to_tool_result()
+ }
+ };
+ let Some(object_id) = resolved
+ .get("object")
+ .and_then(|object| object.get("objectId"))
+ .and_then(Value::as_str)
+ .map(str::to_owned)
+ else {
+ return BrowserRefusal::new(
+ BrowserRefusalCode::BrowserRefStale,
+ "the download ref has no live page object",
+ )
+ .to_tool_result();
+ };
+
+ // Browser events are endpoint-wide. Subscribe before enabling and
+ // triggering so no matching event can be lost between command replies.
+ let mut events = validated.conn.subscribe();
+ if validated
+ .conn
+ .call(
+ None,
+ "Browser.setDownloadBehavior",
+ json!({
+ "behavior": "allowAndName",
+ "downloadPath": destination_root.to_string_lossy(),
+ "eventsEnabled": true
+ }),
+ )
+ .await
+ .is_err()
+ {
+ reset_download_behavior(&validated.conn).await;
+ return BrowserRefusal::new(
+ BrowserRefusalCode::BrowserActionUnavailable,
+ "the browser could not configure the approved download",
+ )
+ .to_tool_result();
+ }
+
+ let trigger = validated
+ .conn
+ .call(
+ Some(&ref_session),
+ "Runtime.callFunctionOn",
+ json!({
+ "objectId": object_id,
+ "functionDeclaration": "function() { this.click(); }",
+ "userGesture": true,
+ "awaitPromise": false
+ }),
+ )
+ .await;
+ let trigger_failed = trigger
+ .as_ref()
+ .map_or(true, |result| result.get("exceptionDetails").is_some());
+ if trigger_failed {
+ reset_download_behavior(&validated.conn).await;
+ return BrowserRefusal::new(
+ BrowserRefusalCode::BrowserRefStale,
+ "the exact download ref could not be activated",
+ )
+ .to_tool_result();
+ }
+
+ let mut observed_guid = None;
+ let outcome = tokio::time::timeout(
+ DOWNLOAD_TIMEOUT,
+ await_download(&mut events, &expected_frame_id, &mut observed_guid),
+ )
+ .await;
+ reset_download_behavior(&validated.conn).await;
+
+ match outcome {
+ Ok(DownloadEventOutcome::Completed { guid }) => {
+ match completed_download_size(&destination_root, &guid) {
+ Ok(bytes) => ToolResult::text("browser download completed").with_structured(
+ json!({ "status": "completed", "download_id": guid, "bytes": bytes }),
+ ),
+ Err(refusal) => refusal.to_tool_result(),
+ }
+ }
+ Ok(DownloadEventOutcome::Canceled { guid }) => {
+ remove_proven_partial(&destination_root, Some(&guid));
+ BrowserRefusal::new(
+ BrowserRefusalCode::BrowserActionUnavailable,
+ "the approved browser download was canceled",
+ )
+ .to_tool_result()
+ }
+ Ok(DownloadEventOutcome::EventStreamClosed) => {
+ remove_proven_partial(&destination_root, observed_guid.as_deref());
+ BrowserRefusal::new(
+ BrowserRefusalCode::BrowserActionUnavailable,
+ "the browser connection closed before the approved download completed",
+ )
+ .to_tool_result()
+ }
+ Err(_) => {
+ remove_proven_partial(&destination_root, observed_guid.as_deref());
+ BrowserRefusal::new(
+ BrowserRefusalCode::BrowserActionUnavailable,
+ "the approved browser download did not complete within 30 seconds",
+ )
+ .to_tool_result()
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn destination_must_be_absolute_existing_canonical_directory() {
+ assert!(validate_destination_root("relative").is_err());
+ let parent = tempfile::tempdir().unwrap();
+ let missing = parent.path().join("does-not-exist");
+ assert!(validate_destination_root(missing.to_str().unwrap()).is_err());
+
+ let root = tempfile::tempdir().unwrap();
+ let canonical = std::fs::canonicalize(root.path()).unwrap();
+ assert_eq!(
+ validate_destination_root(canonical.to_str().unwrap()).unwrap(),
+ canonical
+ );
+ }
+
+ #[test]
+ fn destination_rejects_regular_files() {
+ let root = tempfile::tempdir().unwrap();
+ let file = root.path().join("not-a-directory");
+ std::fs::write(&file, b"x").unwrap();
+ assert!(validate_destination_root(file.to_str().unwrap()).is_err());
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn destination_rejects_symlink_root() {
+ use std::os::unix::fs::symlink;
+
+ let parent = tempfile::tempdir().unwrap();
+ let real = parent.path().join("real");
+ let link = parent.path().join("link");
+ std::fs::create_dir(&real).unwrap();
+ symlink(&real, &link).unwrap();
+ assert!(validate_destination_root(link.to_str().unwrap()).is_err());
+ }
+
+ #[test]
+ fn completion_proof_accepts_only_direct_regular_guid_file() {
+ let root = tempfile::tempdir().unwrap();
+ let canonical = std::fs::canonicalize(root.path()).unwrap();
+ std::fs::write(canonical.join("opaque-guid"), b"abc").unwrap();
+ assert_eq!(
+ completed_download_size(&canonical, "opaque-guid").unwrap(),
+ 3
+ );
+ assert!(completed_download_size(&canonical, "../escape").is_err());
+ assert!(completed_download_size(&canonical, "missing").is_err());
+ }
+
+ #[test]
+ fn partial_cleanup_is_confined_to_a_direct_guid_file() {
+ let root = tempfile::tempdir().unwrap();
+ let canonical = std::fs::canonicalize(root.path()).unwrap();
+ let partial = canonical.join("opaque-guid");
+ std::fs::write(&partial, b"partial").unwrap();
+
+ remove_proven_partial(&canonical, Some("../escape"));
+ assert!(partial.exists());
+
+ remove_proven_partial(&canonical, Some("opaque-guid"));
+ assert!(!partial.exists());
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/mod.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/mod.rs
index ea899520c4..cbd3ccb64d 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/mod.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/mod.rs
@@ -1,8 +1,7 @@
//! Platform-agnostic browser-tool v1 core.
//!
-//! Five typed tools — `get_browser_state` (strictly read-only),
-//! `browser_prepare`, `browser_navigate`, `browser_click`,
-//! `browser_type` — over an exact-or-refused binding model:
+//! Typed browser inspection, preparation, navigation, input, dialog, upload,
+//! and download tools over an exact-or-refused binding model:
//!
//! - The native entrypoint is `pid + window_id`. Browser target ids,
//! tab ids, and page refs (`p<snapshot>:<index>`) are opaque,
@@ -39,12 +38,14 @@
pub mod approval;
pub mod binding;
pub mod cdp_ws;
+pub mod download;
pub mod engine;
mod grant;
#[cfg(test)]
pub(crate) mod mock_cdp;
mod mutation;
pub mod platform;
+pub mod pointer;
mod prepare;
mod reconnect;
pub mod refusal;
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/pointer.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/pointer.rs
new file mode 100644
index 0000000000..d8e08507ad
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/pointer.rs
@@ -0,0 +1,871 @@
+//! Extended browser pointer actions.
+//!
+//! This module deliberately shares the exact-or-refused posture of the
+//! original browser click tool. Every mutation is serialized by the real CDP
+//! tab, then revalidates the native window, endpoint, tab, and (for refs) frame
+//! identity before dispatch. It never activates a target or brings a page to
+//! the foreground.
+
+use std::sync::Arc;
+use std::time::Duration;
+
+use async_trait::async_trait;
+use serde_json::{json, Value};
+
+use crate::protocol::ToolResult;
+use crate::tool::{Tool, ToolDef};
+use crate::tool_args::ArgsExt;
+
+use super::cdp_ws::CdpConnection;
+use super::engine::{BrowserEngine, ValidatedTab};
+use super::refusal::{BrowserRefusal, BrowserRefusalCode};
+use super::store::{FrameKind, FrameRef};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum PointerAction {
+ Hover,
+ RightClick,
+ DoubleClick,
+ Scroll,
+ Drag,
+}
+
+impl PointerAction {
+ fn parse(value: &str) -> Result<Self, String> {
+ match value {
+ "hover" => Ok(Self::Hover),
+ "right_click" => Ok(Self::RightClick),
+ "double_click" => Ok(Self::DoubleClick),
+ "scroll" => Ok(Self::Scroll),
+ "drag" => Ok(Self::Drag),
+ _ => Err(format!(
+ "action must be hover, right_click, double_click, scroll, or drag, got {value:?}"
+ )),
+ }
+ }
+
+ fn as_str(self) -> &'static str {
+ match self {
+ Self::Hover => "hover",
+ Self::RightClick => "right_click",
+ Self::DoubleClick => "double_click",
+ Self::Scroll => "scroll",
+ Self::Drag => "drag",
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum InputRoute {
+ Trusted,
+ DomEvent,
+}
+
+impl InputRoute {
+ fn parse(value: &str) -> Result<Self, String> {
+ match value {
+ "trusted" => Ok(Self::Trusted),
+ "dom_event" => Ok(Self::DomEvent),
+ _ => Err(format!(
+ "input_route must be \"trusted\" or \"dom_event\", got {value:?}"
+ )),
+ }
+ }
+
+ fn as_str(self) -> &'static str {
+ match self {
+ Self::Trusted => "trusted",
+ Self::DomEvent => "dom_event",
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq)]
+enum Location {
+ Ref(String),
+ Coordinates(f64, f64),
+}
+
+#[derive(Debug, Clone, PartialEq)]
+struct PointerRequest {
+ action: PointerAction,
+ route: InputRoute,
+ origin: Location,
+ destination: Option<Location>,
+ delta_x: f64,
+ delta_y: f64,
+}
+
+fn explicit_session(args: &Value) -> Result<String, ToolResult> {
+ let session = args
+ .opt_str("session")
+ .or_else(|| args.opt_str("_session_id"))
+ .unwrap_or_else(|| "default".into());
+ if session.is_empty() || session == "default" {
+ return Err(ToolResult::error(
+ "Browser targets and page refs are session-scoped capabilities - declare an explicit session (start_session) and pass its id on this call.",
+ ));
+ }
+ Ok(session)
+}
+
+fn finite_pair(args: &Value, x_name: &str, y_name: &str) -> Result<Option<(f64, f64)>, String> {
+ match (args.opt_f64(x_name), args.opt_f64(y_name)) {
+ (None, None) => Ok(None),
+ (Some(x), Some(y)) if x.is_finite() && y.is_finite() => Ok(Some((x, y))),
+ (Some(_), Some(_)) => Err(format!("{x_name} and {y_name} must be finite numbers")),
+ _ => Err(format!("pass both {x_name} and {y_name}, or neither")),
+ }
+}
+
+fn one_location(
+ args: &Value,
+ ref_name: &str,
+ x_name: &str,
+ y_name: &str,
+) -> Result<Option<Location>, String> {
+ let reference = args.opt_str(ref_name);
+ let coords = finite_pair(args, x_name, y_name)?;
+ match (reference, coords) {
+ (Some(_), Some(_)) => Err(format!(
+ "pass either {ref_name} or {x_name}/{y_name}, not both"
+ )),
+ (Some(reference), None) => Ok(Some(Location::Ref(reference))),
+ (None, Some((x, y))) => Ok(Some(Location::Coordinates(x, y))),
+ (None, None) => Ok(None),
+ }
+}
+
+fn parse_request(args: &Value) -> Result<PointerRequest, String> {
+ let action = PointerAction::parse(
+ args.get("action")
+ .and_then(Value::as_str)
+ .ok_or_else(|| "missing required string field: action".to_owned())?,
+ )?;
+ let route = InputRoute::parse(
+ args.get("input_route")
+ .and_then(Value::as_str)
+ .unwrap_or("trusted"),
+ )?;
+ let origin = one_location(args, "ref", "x", "y")?
+ .ok_or_else(|| "browser_pointer needs a ref or x/y coordinates".to_owned())?;
+ let destination = one_location(args, "destination_ref", "to_x", "to_y")?;
+
+ if route == InputRoute::DomEvent && !matches!(origin, Location::Ref(_)) {
+ return Err("input_route=dom_event requires a ref".into());
+ }
+ if action == PointerAction::Drag && destination.is_none() {
+ return Err("action=drag requires destination_ref or to_x/to_y".into());
+ }
+ if action != PointerAction::Drag && destination.is_some() {
+ return Err("destination_ref and to_x/to_y are valid only for action=drag".into());
+ }
+
+ let delta_x = args.opt_f64("delta_x").unwrap_or(0.0);
+ let delta_y = args.opt_f64("delta_y").unwrap_or(0.0);
+ if !delta_x.is_finite() || !delta_y.is_finite() {
+ return Err("delta_x and delta_y must be finite numbers".into());
+ }
+ if action == PointerAction::Scroll && delta_x == 0.0 && delta_y == 0.0 {
+ return Err("action=scroll requires a non-zero delta_x or delta_y".into());
+ }
+ if action != PointerAction::Scroll
+ && (args.get("delta_x").is_some() || args.get("delta_y").is_some())
+ {
+ return Err("delta_x and delta_y are valid only for action=scroll".into());
+ }
+
+ Ok(PointerRequest {
+ action,
+ route,
+ origin,
+ destination,
+ delta_x,
+ delta_y,
+ })
+}
+
+struct ResolvedRef {
+ external: String,
+ backend_node_id: i64,
+ frame: FrameRef,
+ cdp_session: String,
+}
+
+fn same_exact_frame(left: &FrameRef, right: &FrameRef) -> bool {
+ left.kind == right.kind
+ && left.oopif_target_id == right.oopif_target_id
+ && left.identity == right.identity
+}
+
+fn stale(message: impl Into<String>) -> ToolResult {
+ BrowserRefusal::new(BrowserRefusalCode::BrowserRefStale, message).to_tool_result()
+}
+
+async fn resolve_object(
+ conn: &CdpConnection,
+ cdp_session: &str,
+ backend_node_id: i64,
+) -> Result<String, ToolResult> {
+ let resolved = conn
+ .call(
+ Some(cdp_session),
+ "DOM.resolveNode",
+ json!({ "backendNodeId": backend_node_id }),
+ )
+ .await
+ .map_err(|_| stale("the ref's node no longer resolves in the live page"))?;
+ resolved
+ .get("object")
+ .and_then(|object| object.get("objectId"))
+ .and_then(Value::as_str)
+ .map(str::to_owned)
+ .ok_or_else(|| stale("the ref's node has no live object in the page"))
+}
+
+async fn point_for_ref(
+ conn: &CdpConnection,
+ cdp_session: &str,
+ backend_node_id: i64,
+) -> Result<(f64, f64), ToolResult> {
+ let _ = conn
+ .call(
+ Some(cdp_session),
+ "DOM.scrollIntoViewIfNeeded",
+ json!({ "backendNodeId": backend_node_id }),
+ )
+ .await;
+ let model = conn
+ .call(
+ Some(cdp_session),
+ "DOM.getBoxModel",
+ json!({ "backendNodeId": backend_node_id }),
+ )
+ .await
+ .map_err(|_| stale("the ref's node has no live layout box"))?;
+ quad_center(&model).ok_or_else(|| stale("the ref's node returned an unusable layout box"))
+}
+
+fn quad_center(box_model: &Value) -> Option<(f64, f64)> {
+ let quad = box_model.get("model")?.get("content")?.as_array()?;
+ if quad.len() < 8 {
+ return None;
+ }
+ let values = quad
+ .iter()
+ .take(8)
+ .map(Value::as_f64)
+ .collect::<Option<Vec<_>>>()?;
+ Some((
+ (values[0] + values[2] + values[4] + values[6]) / 4.0,
+ (values[1] + values[3] + values[5] + values[7]) / 4.0,
+ ))
+}
+
+pub struct BrowserPointerTool {
+ def: ToolDef,
+ engine: Arc<BrowserEngine>,
+}
+
+impl BrowserPointerTool {
+ pub fn new(engine: Arc<BrowserEngine>) -> Self {
+ Self {
+ def: ToolDef {
+ name: "browser_pointer".into(),
+ description: "Perform hover, right-click, double-click, scroll, or drag in an exactly-bound browser tab. The trusted route uses CDP Input events and refuses if standalone background posture cannot be preserved. The explicit dom_event route requires a page ref and synthesizes full-background DOM events. Never activates or brings a tab to the foreground.".into(),
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "target_id": { "type": "string", "description": "Opaque target id minted by get_browser_state." },
+ "tab_id": { "type": "string", "description": "Opaque tab id minted by get_browser_state." },
+ "session": { "type": "string", "description": "Explicit caller session owning the browser capabilities." },
+ "action": { "type": "string", "enum": ["hover", "right_click", "double_click", "scroll", "drag"] },
+ "input_route": { "type": "string", "enum": ["trusted", "dom_event"], "default": "trusted" },
+ "ref": { "type": "string", "description": "Origin page ref. Alternative to x/y." },
+ "x": { "type": "number", "description": "Origin viewport x in CSS pixels." },
+ "y": { "type": "number", "description": "Origin viewport y in CSS pixels." },
+ "destination_ref": { "type": "string", "description": "Drag destination page ref in the exact same frame." },
+ "to_x": { "type": "number", "description": "Drag destination viewport x in CSS pixels." },
+ "to_y": { "type": "number", "description": "Drag destination viewport y in CSS pixels." },
+ "delta_x": { "type": "number", "description": "Horizontal scroll delta in CSS pixels." },
+ "delta_y": { "type": "number", "description": "Vertical scroll delta in CSS pixels." }
+ },
+ "required": ["target_id", "tab_id", "session", "action"],
+ "additionalProperties": true
+ }),
+ read_only: false,
+ destructive: false,
+ idempotent: false,
+ open_world: false,
+ },
+ engine,
+ }
+ }
+
+ async fn resolve_ref(
+ &self,
+ session: &str,
+ target_id: &str,
+ tab_id: &str,
+ validated: &ValidatedTab,
+ external: &str,
+ ) -> Result<ResolvedRef, ToolResult> {
+ let entry = self
+ .engine
+ .store
+ .resolve_ref(session, target_id, tab_id, external)
+ .map_err(|refusal| refusal.to_tool_result())?;
+ let cdp_session = self
+ .engine
+ .frame_session_for_mutation(session, target_id, tab_id, validated, &entry.frame)
+ .await
+ .map_err(|refusal| refusal.to_tool_result())?;
+ Ok(ResolvedRef {
+ external: external.to_owned(),
+ backend_node_id: entry.backend_node_id,
+ frame: entry.frame,
+ cdp_session,
+ })
+ }
+
+ fn trusted_background_refusal(&self, validated: &ValidatedTab) -> Option<ToolResult> {
+ if validated.record.cdp_window_id.is_some() {
+ if let Some(limitation) = self
+ .engine
+ .platform
+ .standalone_trusted_input_background_limitation()
+ {
+ return Some(
+ BrowserRefusal::new(
+ BrowserRefusalCode::BrowserInputTrustUnavailable,
+ format!(
+ "{limitation}; use input_route=\"dom_event\" with refs to explicitly request synthetic full-background pointer delivery"
+ ),
+ )
+ .to_tool_result(),
+ );
+ }
+ }
+ None
+ }
+
+ async fn dom_event(
+ &self,
+ request: &PointerRequest,
+ validated: &ValidatedTab,
+ origin: &ResolvedRef,
+ destination: Option<&ResolvedRef>,
+ ) -> ToolResult {
+ let conn = &validated.conn;
+ let object_id =
+ match resolve_object(conn, &origin.cdp_session, origin.backend_node_id).await {
+ Ok(id) => id,
+ Err(result) => return result,
+ };
+
+ let (function, arguments) = match request.action {
+ PointerAction::Hover => (
+ "function() { const o={bubbles:true,composed:true,view:this.ownerDocument.defaultView}; this.dispatchEvent(new PointerEvent('pointerover',o)); this.dispatchEvent(new PointerEvent('pointerenter',{...o,bubbles:false})); this.dispatchEvent(new MouseEvent('mouseover',o)); this.dispatchEvent(new MouseEvent('mouseenter',{...o,bubbles:false})); return true; }",
+ json!([]),
+ ),
+ PointerAction::RightClick => (
+ "function() { const o={bubbles:true,cancelable:true,composed:true,button:2,buttons:2,view:this.ownerDocument.defaultView}; this.dispatchEvent(new PointerEvent('pointerdown',o)); this.dispatchEvent(new MouseEvent('mousedown',o)); this.dispatchEvent(new MouseEvent('mouseup',{...o,buttons:0})); this.dispatchEvent(new PointerEvent('pointerup',{...o,buttons:0})); this.dispatchEvent(new MouseEvent('contextmenu',{...o,buttons:0})); return true; }",
+ json!([]),
+ ),
+ PointerAction::DoubleClick => (
+ "function() { const o={bubbles:true,cancelable:true,composed:true,button:0,view:this.ownerDocument.defaultView}; for (let detail=1; detail<=2; detail++) { this.dispatchEvent(new PointerEvent('pointerdown',{...o,buttons:1,detail})); this.dispatchEvent(new MouseEvent('mousedown',{...o,buttons:1,detail})); this.dispatchEvent(new MouseEvent('mouseup',{...o,buttons:0,detail})); this.dispatchEvent(new PointerEvent('pointerup',{...o,buttons:0,detail})); this.dispatchEvent(new MouseEvent('click',{...o,buttons:0,detail})); } this.dispatchEvent(new MouseEvent('dblclick',{...o,buttons:0,detail:2})); return true; }",
+ json!([]),
+ ),
+ PointerAction::Scroll => (
+ "function(dx,dy) { const o={deltaX:dx,deltaY:dy,bubbles:true,cancelable:true,composed:true,view:this.ownerDocument.defaultView}; this.dispatchEvent(new WheelEvent('wheel',o)); let n=this; while (n && n !== this.ownerDocument.documentElement) { const s=this.ownerDocument.defaultView.getComputedStyle(n); if (/(auto|scroll)/.test(s.overflow+s.overflowX+s.overflowY)) break; n=n.parentElement; } const target=n || this.ownerDocument.scrollingElement || this.ownerDocument.documentElement; const beforeX=target.scrollLeft; const beforeY=target.scrollTop; target.scrollBy(dx,dy); const changed=target.scrollLeft !== beforeX || target.scrollTop !== beforeY; if (changed) target.dispatchEvent(new Event('scroll')); return changed; }",
+ json!([{ "value": request.delta_x }, { "value": request.delta_y }]),
+ ),
+ PointerAction::Drag => {
+ let destination_argument = if let Some(destination) = destination {
+ let object_id = match resolve_object(
+ conn,
+ &destination.cdp_session,
+ destination.backend_node_id,
+ )
+ .await
+ {
+ Ok(id) => id,
+ Err(result) => return result,
+ };
+ json!([{ "objectId": object_id }, { "value": Value::Null }, { "value": Value::Null }])
+ } else if let Some(Location::Coordinates(x, y)) = &request.destination {
+ if origin.frame.kind != FrameKind::Main {
+ return BrowserRefusal::new(
+ BrowserRefusalCode::BrowserWrongTargetRefused,
+ "coordinate drag destinations are only provably in the same frame for a main-frame origin; use destination_ref for iframe or OOPIF drag",
+ )
+ .to_tool_result();
+ }
+ json!([{ "value": Value::Null }, { "value": x }, { "value": y }])
+ } else {
+ unreachable!("drag destination validated")
+ };
+ (
+ "function(destination,x,y) { const doc=this.ownerDocument; const dest=destination || doc.elementFromPoint(x,y); if (!dest || dest.ownerDocument !== doc) return false; let data=null; try { data=new DataTransfer(); } catch (_) {} const common={bubbles:true,cancelable:true,composed:true}; this.dispatchEvent(new PointerEvent('pointerdown',{...common,button:0,buttons:1})); this.dispatchEvent(new MouseEvent('mousedown',{...common,button:0,buttons:1})); this.dispatchEvent(new DragEvent('dragstart',{...common,dataTransfer:data})); dest.dispatchEvent(new DragEvent('dragenter',{...common,dataTransfer:data})); dest.dispatchEvent(new DragEvent('dragover',{...common,dataTransfer:data})); dest.dispatchEvent(new DragEvent('drop',{...common,dataTransfer:data})); this.dispatchEvent(new DragEvent('dragend',{...common,dataTransfer:data})); dest.dispatchEvent(new MouseEvent('mouseup',{...common,button:0,buttons:0})); dest.dispatchEvent(new PointerEvent('pointerup',{...common,button:0,buttons:0})); return true; }",
+ destination_argument,
+ )
+ }
+ };
+
+ match conn
+ .call(
+ Some(&origin.cdp_session),
+ "Runtime.callFunctionOn",
+ json!({
+ "objectId": object_id,
+ "functionDeclaration": function,
+ "arguments": arguments,
+ "returnByValue": true,
+ }),
+ )
+ .await
+ {
+ Ok(value)
+ if value.get("exceptionDetails").is_none()
+ && (!matches!(request.action, PointerAction::Scroll | PointerAction::Drag)
+ || value.pointer("/result/value").and_then(Value::as_bool)
+ != Some(false)) =>
+ {
+ ToolResult::text(format!(
+ "dispatched synthetic {} in {}",
+ request.action.as_str(),
+ validated.tab.tab_id
+ ))
+ .with_structured(self.success_json(
+ request,
+ validated,
+ origin,
+ destination,
+ None,
+ None,
+ ))
+ }
+ Ok(value) if value.get("exceptionDetails").is_some() => BrowserRefusal::new(
+ BrowserRefusalCode::BrowserActionUnavailable,
+ format!(
+ "synthetic {} raised a page-side exception and delivery was not proven",
+ request.action.as_str()
+ ),
+ )
+ .to_tool_result(),
+ Ok(_) if request.action == PointerAction::Drag => BrowserRefusal::new(
+ BrowserRefusalCode::BrowserWrongTargetRefused,
+ "the drag destination did not resolve in the origin ref's exact document",
+ )
+ .to_tool_result(),
+ Ok(_) => BrowserRefusal::new(
+ BrowserRefusalCode::BrowserActionUnavailable,
+ "the synthetic scroll target did not move, so delivery was not proven",
+ )
+ .to_tool_result(),
+ Err(error) => ToolResult::error(format!(
+ "synthetic {} failed: {error}",
+ request.action.as_str()
+ )),
+ }
+ }
+
+ fn success_json(
+ &self,
+ request: &PointerRequest,
+ validated: &ValidatedTab,
+ origin: &ResolvedRef,
+ destination: Option<&ResolvedRef>,
+ origin_point: Option<(f64, f64)>,
+ destination_point: Option<(f64, f64)>,
+ ) -> Value {
+ let external_ref = (!origin.external.is_empty()).then_some(origin.external.as_str());
+ json!({
+ "status": "ok",
+ "action": request.action.as_str(),
+ "route": request.route.as_str(),
+ "target_id": validated.record.target_id,
+ "tab_id": validated.tab.tab_id,
+ "ref": external_ref,
+ "frame": origin.frame.kind.as_str(),
+ "destination_ref": destination.map(|value| value.external.as_str()),
+ "x": origin_point.map(|point| point.0),
+ "y": origin_point.map(|point| point.1),
+ "to_x": destination_point.map(|point| point.0),
+ "to_y": destination_point.map(|point| point.1),
+ "delta_x": (request.action == PointerAction::Scroll).then_some(request.delta_x),
+ "delta_y": (request.action == PointerAction::Scroll).then_some(request.delta_y),
+ })
+ }
+
+ async fn trusted(
+ &self,
+ request: &PointerRequest,
+ validated: &ValidatedTab,
+ origin_ref: Option<&ResolvedRef>,
+ destination_ref: Option<&ResolvedRef>,
+ ) -> ToolResult {
+ let conn = &validated.conn;
+ let cdp_session = origin_ref
+ .map(|reference| reference.cdp_session.as_str())
+ .unwrap_or(validated.cdp_session.as_str());
+ let origin = match (&request.origin, origin_ref) {
+ (Location::Coordinates(x, y), None) => (*x, *y),
+ (Location::Ref(_), Some(reference)) => {
+ match point_for_ref(conn, &reference.cdp_session, reference.backend_node_id).await {
+ Ok(point) => point,
+ Err(result) => return result,
+ }
+ }
+ _ => unreachable!("origin resolution matches request"),
+ };
+ let destination = match (&request.destination, destination_ref) {
+ (Some(Location::Coordinates(x, y)), None) => Some((*x, *y)),
+ (Some(Location::Ref(_)), Some(reference)) => {
+ match point_for_ref(conn, &reference.cdp_session, reference.backend_node_id).await {
+ Ok(point) => Some(point),
+ Err(result) => return result,
+ }
+ }
+ (None, None) => None,
+ _ => unreachable!("destination resolution matches request"),
+ };
+
+ if let Err(error) = conn
+ .call(
+ Some(cdp_session),
+ "Emulation.setFocusEmulationEnabled",
+ json!({ "enabled": true }),
+ )
+ .await
+ {
+ return BrowserRefusal::new(
+ BrowserRefusalCode::BrowserInputTrustUnavailable,
+ format!("the target tab could not enter CDP focus emulation: {error}"),
+ )
+ .to_tool_result();
+ }
+ tokio::time::sleep(Duration::from_millis(25)).await;
+
+ let delivery = self
+ .dispatch_trusted(conn, cdp_session, request, origin, destination)
+ .await;
+ let cleanup = conn
+ .call(
+ Some(cdp_session),
+ "Emulation.setFocusEmulationEnabled",
+ json!({ "enabled": false }),
+ )
+ .await;
+ if let Err(error) = delivery {
+ return BrowserRefusal::new(
+ BrowserRefusalCode::BrowserInputTrustUnavailable,
+ format!(
+ "trusted {} failed ({error}); no synthetic fallback was attempted",
+ request.action.as_str()
+ ),
+ )
+ .to_tool_result();
+ }
+ if let Err(error) = cleanup {
+ return BrowserRefusal::new(
+ BrowserRefusalCode::BrowserInputTrustUnavailable,
+ format!(
+ "trusted {} was acknowledged but focus emulation could not be restored ({error}); delivery is unknown and must not be retried automatically",
+ request.action.as_str()
+ ),
+ )
+ .with_detail(json!({ "delivery": "unknown", "retryable": false }))
+ .to_tool_result();
+ }
+
+ let synthetic_origin = ResolvedRef {
+ external: match &request.origin {
+ Location::Ref(reference) => reference.clone(),
+ Location::Coordinates(_, _) => String::new(),
+ },
+ backend_node_id: origin_ref.map_or(0, |reference| reference.backend_node_id),
+ frame: origin_ref
+ .map(|reference| reference.frame.clone())
+ .unwrap_or_else(FrameRef::main_unproven),
+ cdp_session: cdp_session.to_owned(),
+ };
+ ToolResult::text(format!(
+ "dispatched trusted {} in {}",
+ request.action.as_str(),
+ validated.tab.tab_id
+ ))
+ .with_structured(self.success_json(
+ request,
+ validated,
+ &synthetic_origin,
+ destination_ref,
+ Some(origin),
+ destination,
+ ))
+ }
+
+ async fn dispatch_trusted(
+ &self,
+ conn: &CdpConnection,
+ cdp_session: &str,
+ request: &PointerRequest,
+ origin: (f64, f64),
+ destination: Option<(f64, f64)>,
+ ) -> anyhow::Result<()> {
+ let call = |params: Value| conn.call(Some(cdp_session), "Input.dispatchMouseEvent", params);
+ match request.action {
+ PointerAction::Hover => {
+ call(
+ json!({ "type": "mouseMoved", "x": origin.0, "y": origin.1, "button": "none" }),
+ )
+ .await?;
+ }
+ PointerAction::RightClick => {
+ for kind in ["mousePressed", "mouseReleased"] {
+ call(json!({ "type": kind, "x": origin.0, "y": origin.1, "button": "right", "clickCount": 1 })).await?;
+ }
+ }
+ PointerAction::DoubleClick => {
+ for click_count in [1, 2] {
+ for kind in ["mousePressed", "mouseReleased"] {
+ call(json!({ "type": kind, "x": origin.0, "y": origin.1, "button": "left", "clickCount": click_count })).await?;
+ }
+ }
+ }
+ PointerAction::Scroll => {
+ call(json!({ "type": "mouseWheel", "x": origin.0, "y": origin.1, "deltaX": request.delta_x, "deltaY": request.delta_y })).await?;
+ }
+ PointerAction::Drag => {
+ let destination = destination.expect("drag destination validated");
+ call(
+ json!({ "type": "mouseMoved", "x": origin.0, "y": origin.1, "button": "none" }),
+ )
+ .await?;
+ call(json!({ "type": "mousePressed", "x": origin.0, "y": origin.1, "button": "left", "buttons": 1, "clickCount": 1 })).await?;
+ for step in 1..=8 {
+ let progress = f64::from(step) / 8.0;
+ let x = origin.0 + (destination.0 - origin.0) * progress;
+ let y = origin.1 + (destination.1 - origin.1) * progress;
+ call(json!({ "type": "mouseMoved", "x": x, "y": y, "button": "left", "buttons": 1 })).await?;
+ }
+ call(json!({ "type": "mouseReleased", "x": destination.0, "y": destination.1, "button": "left", "buttons": 0, "clickCount": 1 })).await?;
+ }
+ }
+ Ok(())
+ }
+}
+
+#[async_trait]
+impl Tool for BrowserPointerTool {
+ fn def(&self) -> &ToolDef {
+ &self.def
+ }
+
+ async fn invoke(&self, args: Value) -> ToolResult {
+ let target_id = match args.require_str("target_id") {
+ Ok(value) => value,
+ Err(error) => return error,
+ };
+ let tab_id = match args.require_str("tab_id") {
+ Ok(value) => value,
+ Err(error) => return error,
+ };
+ let session = match explicit_session(&args) {
+ Ok(value) => value,
+ Err(error) => return error,
+ };
+ let request = match parse_request(&args) {
+ Ok(value) => value,
+ Err(error) => return ToolResult::error(error),
+ };
+
+ let _mutation = match self
+ .engine
+ .lock_mutation(&session, &target_id, &tab_id)
+ .await
+ {
+ Ok(guard) => guard,
+ Err(refusal) => return refusal.to_tool_result(),
+ };
+ let validated = match self
+ .engine
+ .revalidate_for_mutation(&session, &target_id, Some(&tab_id))
+ .await
+ {
+ Ok(value) => value,
+ Err(refusal) => return refusal.to_tool_result(),
+ };
+ if request.route == InputRoute::Trusted {
+ if let Some(refusal) = self.trusted_background_refusal(&validated) {
+ return refusal;
+ }
+ }
+
+ let origin_ref = match &request.origin {
+ Location::Ref(external) => match self
+ .resolve_ref(&session, &target_id, &tab_id, &validated, external)
+ .await
+ {
+ Ok(reference) => Some(reference),
+ Err(result) => return result,
+ },
+ Location::Coordinates(_, _) => None,
+ };
+ let destination_ref = match &request.destination {
+ Some(Location::Ref(external)) => match self
+ .resolve_ref(&session, &target_id, &tab_id, &validated, external)
+ .await
+ {
+ Ok(reference) => Some(reference),
+ Err(result) => return result,
+ },
+ _ => None,
+ };
+
+ if let (Some(origin), Some(destination)) = (&origin_ref, &destination_ref) {
+ if !same_exact_frame(&origin.frame, &destination.frame)
+ || origin.cdp_session != destination.cdp_session
+ {
+ return BrowserRefusal::new(
+ BrowserRefusalCode::BrowserWrongTargetRefused,
+ "drag origin and destination refs must belong to the exact same live frame",
+ )
+ .to_tool_result();
+ }
+ }
+ if request.action == PointerAction::Drag
+ && origin_ref.is_none()
+ && destination_ref.is_some()
+ {
+ return BrowserRefusal::new(
+ BrowserRefusalCode::BrowserWrongTargetRefused,
+ "a coordinate drag origin cannot prove it shares a frame with destination_ref; use two refs or two coordinate pairs",
+ )
+ .to_tool_result();
+ }
+ if request.action == PointerAction::Drag
+ && matches!(&request.destination, Some(Location::Coordinates(_, _)))
+ && origin_ref
+ .as_ref()
+ .is_some_and(|reference| reference.frame.kind != FrameKind::Main)
+ {
+ return BrowserRefusal::new(
+ BrowserRefusalCode::BrowserWrongTargetRefused,
+ "a viewport-coordinate drag destination is only in the same provable frame as a main-frame ref; use destination_ref for iframe or OOPIF drag",
+ )
+ .to_tool_result();
+ }
+
+ match request.route {
+ InputRoute::DomEvent => {
+ self.dom_event(
+ &request,
+ &validated,
+ origin_ref.as_ref().expect("dom route requires ref"),
+ destination_ref.as_ref(),
+ )
+ .await
+ }
+ InputRoute::Trusted => {
+ self.trusted(
+ &request,
+ &validated,
+ origin_ref.as_ref(),
+ destination_ref.as_ref(),
+ )
+ .await
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn parses_every_action_and_coordinate_origin() {
+ for action in ["hover", "right_click", "double_click"] {
+ let parsed = parse_request(&json!({
+ "action": action,
+ "x": 12.5,
+ "y": 8,
+ }))
+ .unwrap();
+ assert_eq!(parsed.origin, Location::Coordinates(12.5, 8.0));
+ assert_eq!(parsed.route, InputRoute::Trusted);
+ }
+ }
+
+ #[test]
+ fn dom_event_requires_a_ref() {
+ let error = parse_request(&json!({
+ "action": "hover",
+ "input_route": "dom_event",
+ "x": 1,
+ "y": 2,
+ }))
+ .unwrap_err();
+ assert!(error.contains("requires a ref"), "{error}");
+ }
+
+ #[test]
+ fn drag_requires_exactly_one_destination_shape() {
+ assert!(parse_request(&json!({ "action": "drag", "ref": "p1:0" }))
+ .unwrap_err()
+ .contains("requires destination"));
+ assert!(parse_request(&json!({
+ "action": "drag",
+ "ref": "p1:0",
+ "destination_ref": "p1:1",
+ "to_x": 3,
+ "to_y": 4,
+ }))
+ .unwrap_err()
+ .contains("not both"));
+ }
+
+ #[test]
+ fn scroll_requires_a_nonzero_finite_delta() {
+ assert!(parse_request(&json!({ "action": "scroll", "ref": "p1:0" }))
+ .unwrap_err()
+ .contains("non-zero"));
+ let parsed = parse_request(&json!({
+ "action": "scroll",
+ "ref": "p1:0",
+ "delta_y": 240,
+ }))
+ .unwrap();
+ assert_eq!(parsed.delta_y, 240.0);
+ }
+
+ #[test]
+ fn quad_center_rejects_malformed_models() {
+ assert_eq!(
+ quad_center(&json!({ "model": { "content": [0, 0, 10, 0, 10, 20, 0, 20] } })),
+ Some((5.0, 10.0))
+ );
+ assert_eq!(
+ quad_center(&json!({ "model": { "content": [0, 0] } })),
+ None
+ );
+ }
+
+ #[test]
+ fn exact_frame_comparison_includes_document_identity() {
+ let first = FrameRef::main_unproven();
+ let second = FrameRef::main_unproven();
+ assert!(same_exact_frame(&first, &second));
+
+ let navigated = FrameRef {
+ kind: FrameKind::Main,
+ oopif_target_id: None,
+ identity: Some(super::super::store::FrameIdentity {
+ frame_id: "main".into(),
+ loader_id: "new-loader".into(),
+ }),
+ };
+ assert!(!same_exact_frame(&first, &navigated));
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs
index 1906a18113..4b8a819597 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/tools.rs
@@ -15,13 +15,15 @@ use crate::tool::{Tool, ToolDef, ToolRegistry};
use crate::tool_args::ArgsExt;
use super::approval::MCP_HOST_APPROVAL_ARG;
+use super::download::BrowserDownloadTool;
use super::engine::BrowserEngine;
use super::platform::{PrepareAuthorization, PrepareProfile, PrepareRequest, PrepareStrategy};
+use super::pointer::BrowserPointerTool;
use super::refusal::{BrowserRefusal, BrowserRefusalCode};
use super::store::BrowserActionKind;
use super::types::BindingQuality;
-/// Register all five browser tools against one shared engine. Platform
+/// Register the complete browser surface against one shared engine. Platform
/// crates call this from their `register_all` after constructing the
/// engine with their adapter.
pub fn register_browser_tools(engine: &Arc<BrowserEngine>, registry: &mut ToolRegistry) {
@@ -32,6 +34,8 @@ pub fn register_browser_tools(engine: &Arc<BrowserEngine>, registry: &mut ToolRe
registry.register(Box::new(BrowserTypeTool::new(engine.clone())));
registry.register(Box::new(BrowserDialogTool::new(engine.clone())));
registry.register(Box::new(BrowserSetInputFilesTool::new(engine.clone())));
+ registry.register(Box::new(BrowserDownloadTool::new(engine.clone())));
+ registry.register(Box::new(BrowserPointerTool::new(engine.clone())));
}
// ── Shared helpers ───────────────────────────────────────────────────────────
@@ -1482,16 +1486,27 @@ impl Tool for BrowserDialogTool {
};
let conn = &validated.conn;
let cdp_session = validated.cdp_session.as_str();
- if let Err(error) = conn.call(Some(cdp_session), "Page.enable", json!({})).await {
- return BrowserRefusal::new(
- BrowserRefusalCode::BrowserActionUnavailable,
- format!("the exact tab does not expose JavaScript dialog events: {error}"),
- )
- .to_tool_result();
+ let cdp_target_id = validated.tab.cdp_target_id.as_str();
+ if conn.dialog_state(cdp_target_id).is_none()
+ && !conn.has_dialog_session(cdp_target_id)
+ {
+ // Register before Page.enable so an opening event delivered before
+ // the command reply is still attributed to the exact target.
+ conn.register_dialog_session(cdp_session, cdp_target_id);
+ if let Err(error) = conn.call(Some(cdp_session), "Page.enable", json!({})).await {
+ if conn.dialog_state(cdp_target_id).is_none() {
+ conn.unregister_dialog_session(cdp_session, cdp_target_id);
+ return BrowserRefusal::new(
+ BrowserRefusalCode::BrowserActionUnavailable,
+ format!("the exact tab does not expose JavaScript dialog events: {error}"),
+ )
+ .to_tool_result();
+ }
+ }
+ tokio::task::yield_now().await;
}
- tokio::task::yield_now().await;
- let Some(dialog) = conn.dialog_state(cdp_session) else {
+ let Some(dialog) = conn.dialog_state(cdp_target_id) else {
return if action == "inspect" {
ToolResult::text(format!(
"no page-owned JavaScript dialog is open in {tab_id}"
@@ -1537,11 +1552,15 @@ impl Tool for BrowserDialogTool {
params["promptText"] = Value::String(text);
}
match conn
- .call(Some(cdp_session), "Page.handleJavaScriptDialog", params)
+ .call(
+ Some(&dialog.session_id),
+ "Page.handleJavaScriptDialog",
+ params,
+ )
.await
{
Ok(_) => {
- conn.clear_dialog_state(cdp_session, dialog.generation);
+ conn.clear_dialog_state(cdp_target_id, dialog.generation);
ToolResult::text(format!("{action}ed {} dialog in {tab_id}", dialog.kind))
.with_structured(json!({
"status": "ok", "target_id": target_id, "tab_id": tab_id,
@@ -1914,14 +1933,25 @@ mod tests {
BrowserSetInputFilesTool::new(e.clone()).def().clone(),
"browser_set_input_files",
),
+ (
+ BrowserDownloadTool::new(e.clone()).def().clone(),
+ "browser_download",
+ ),
+ (
+ BrowserPointerTool::new(e.clone()).def().clone(),
+ "browser_pointer",
+ ),
] {
assert_eq!(def.name, name);
assert!(!def.read_only, "{name} is a mutation");
assert!(def.input_schema["properties"].is_object(), "{name} schema");
}
- // Navigate reaches the open web; the input tools do not.
+ // Navigate and download reach the open web; ordinary input does not.
assert!(BrowserNavigateTool::new(e.clone()).def().open_world);
- assert!(!BrowserClickTool::new(e).def().open_world);
+ assert!(BrowserDownloadTool::new(e.clone()).def().open_world);
+ assert!(BrowserDownloadTool::new(e.clone()).def().destructive);
+ assert!(!BrowserClickTool::new(e.clone()).def().open_world);
+ assert!(!BrowserPointerTool::new(e).def().open_world);
}
#[test]
@@ -1939,7 +1969,9 @@ mod tests {
"browser_click",
"browser_type",
"browser_dialog",
- "browser_set_input_files"
+ "browser_set_input_files",
+ "browser_download",
+ "browser_pointer"
]
);
}
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 3f9bf8e818..60c3161ad1 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
@@ -265,6 +265,21 @@ pub enum ToolOperation {
BrowserTypeKeystrokes,
BrowserPrepareIsolated,
BrowserPrepareExistingProfile,
+ BrowserDialogInspect,
+ BrowserDialogAccept,
+ BrowserDialogDismiss,
+ BrowserSetInputFiles,
+ BrowserDownload,
+ BrowserPointerHoverTrusted,
+ BrowserPointerHoverDomEvent,
+ BrowserPointerRightClickTrusted,
+ BrowserPointerRightClickDomEvent,
+ BrowserPointerDoubleClickTrusted,
+ BrowserPointerDoubleClickDomEvent,
+ BrowserPointerScrollTrusted,
+ BrowserPointerScrollDomEvent,
+ BrowserPointerDragTrusted,
+ BrowserPointerDragDomEvent,
Other,
}
@@ -288,6 +303,21 @@ impl ToolOperation {
Self::BrowserTypeKeystrokes => "browser_type_keystrokes",
Self::BrowserPrepareIsolated => "browser_prepare_isolated",
Self::BrowserPrepareExistingProfile => "browser_prepare_existing_profile",
+ Self::BrowserDialogInspect => "browser_dialog_inspect",
+ Self::BrowserDialogAccept => "browser_dialog_accept",
+ Self::BrowserDialogDismiss => "browser_dialog_dismiss",
+ Self::BrowserSetInputFiles => "browser_set_input_files",
+ Self::BrowserDownload => "browser_download",
+ Self::BrowserPointerHoverTrusted => "browser_pointer_hover_trusted",
+ Self::BrowserPointerHoverDomEvent => "browser_pointer_hover_dom_event",
+ Self::BrowserPointerRightClickTrusted => "browser_pointer_right_click_trusted",
+ Self::BrowserPointerRightClickDomEvent => "browser_pointer_right_click_dom_event",
+ Self::BrowserPointerDoubleClickTrusted => "browser_pointer_double_click_trusted",
+ Self::BrowserPointerDoubleClickDomEvent => "browser_pointer_double_click_dom_event",
+ Self::BrowserPointerScrollTrusted => "browser_pointer_scroll_trusted",
+ Self::BrowserPointerScrollDomEvent => "browser_pointer_scroll_dom_event",
+ Self::BrowserPointerDragTrusted => "browser_pointer_drag_trusted",
+ Self::BrowserPointerDragDomEvent => "browser_pointer_drag_dom_event",
Self::Other => "other",
}
}
@@ -349,6 +379,35 @@ pub fn tool_operation(tool_name: &str, args: Option<&serde_json::Value>) -> Tool
_ => ToolOperation::Other,
}
}
+ "browser_dialog" => match string_arg("action") {
+ Some("inspect") => ToolOperation::BrowserDialogInspect,
+ Some("accept") => ToolOperation::BrowserDialogAccept,
+ Some("dismiss") => ToolOperation::BrowserDialogDismiss,
+ _ => ToolOperation::Other,
+ },
+ "browser_set_input_files" => ToolOperation::BrowserSetInputFiles,
+ "browser_download" => ToolOperation::BrowserDownload,
+ "browser_pointer" => match (string_arg("action"), string_arg("input_route")) {
+ (Some("hover"), None | Some("trusted")) => ToolOperation::BrowserPointerHoverTrusted,
+ (Some("hover"), Some("dom_event")) => ToolOperation::BrowserPointerHoverDomEvent,
+ (Some("right_click"), None | Some("trusted")) => {
+ ToolOperation::BrowserPointerRightClickTrusted
+ }
+ (Some("right_click"), Some("dom_event")) => {
+ ToolOperation::BrowserPointerRightClickDomEvent
+ }
+ (Some("double_click"), None | Some("trusted")) => {
+ ToolOperation::BrowserPointerDoubleClickTrusted
+ }
+ (Some("double_click"), Some("dom_event")) => {
+ ToolOperation::BrowserPointerDoubleClickDomEvent
+ }
+ (Some("scroll"), None | Some("trusted")) => ToolOperation::BrowserPointerScrollTrusted,
+ (Some("scroll"), Some("dom_event")) => ToolOperation::BrowserPointerScrollDomEvent,
+ (Some("drag"), None | Some("trusted")) => ToolOperation::BrowserPointerDragTrusted,
+ (Some("drag"), Some("dom_event")) => ToolOperation::BrowserPointerDragDomEvent,
+ _ => ToolOperation::Other,
+ },
_ => ToolOperation::NotApplicable,
}
}
@@ -368,6 +427,18 @@ pub fn is_computer_action(tool_name: &str, operation: ToolOperation) -> bool {
| ToolOperation::EnableJavascriptAppleEvents
);
}
+ if tool_name == "browser_dialog" {
+ return matches!(
+ operation,
+ ToolOperation::BrowserDialogAccept | ToolOperation::BrowserDialogDismiss
+ );
+ }
+ if matches!(
+ tool_name,
+ "browser_set_input_files" | "browser_download" | "browser_pointer"
+ ) {
+ return true;
+ }
crate::tool::default_capabilities_for(tool_name)
.iter()
.any(|capability| {
@@ -688,6 +759,10 @@ fn structured_refusal_code(tool_name: &str, result: Option<&serde_json::Value>)
| "browser_navigate"
| "browser_click"
| "browser_type"
+ | "browser_dialog"
+ | "browser_set_input_files"
+ | "browser_download"
+ | "browser_pointer"
) {
return ToolRefusalCode::None;
}
@@ -856,6 +931,14 @@ pub async fn handle_request(
);
}
}
+ if call.name == "browser_download" {
+ if let Some(arguments) = call.args.as_object_mut() {
+ arguments.insert(
+ crate::browser::download::MCP_HOST_DOWNLOAD_APPROVAL_ARG.to_owned(),
+ serde_json::Value::Bool(true),
+ );
+ }
+ }
let result = registry.invoke(&call.name, call.args).await;
match serde_json::to_value(result) {
@@ -911,7 +994,11 @@ mod observation_tests {
#[test]
fn page_operation_is_closed_and_retains_no_argument_content() {
for (action, expected, computer_action) in [
- ("execute_javascript", ToolOperation::ExecuteJavascript, false),
+ (
+ "execute_javascript",
+ ToolOperation::ExecuteJavascript,
+ false,
+ ),
("get_text", ToolOperation::GetText, false),
("query_dom", ToolOperation::QueryDom, false),
("click_element", ToolOperation::ClickElement, true),
@@ -1008,6 +1095,26 @@ mod observation_tests {
}),
ToolOperation::BrowserPrepareExistingProfile,
),
+ (
+ "browser_dialog",
+ serde_json::json!({"action": "accept", "prompt_text": "private prompt"}),
+ ToolOperation::BrowserDialogAccept,
+ ),
+ (
+ "browser_set_input_files",
+ serde_json::json!({"files": ["/private/path"]}),
+ ToolOperation::BrowserSetInputFiles,
+ ),
+ (
+ "browser_download",
+ serde_json::json!({"destination_root": "/private/destination"}),
+ ToolOperation::BrowserDownload,
+ ),
+ (
+ "browser_pointer",
+ serde_json::json!({"action": "drag", "input_route": "dom_event", "ref": "private-ref"}),
+ ToolOperation::BrowserPointerDragDomEvent,
+ ),
] {
let operation = tool_operation(tool_name, Some(&args));
assert_eq!(operation, expected, "tool={tool_name}");
@@ -1019,6 +1126,9 @@ mod observation_tests {
"private typed text",
"private-profile",
"private-token",
+ "private prompt",
+ "/private/path",
+ "/private/destination",
] {
assert!(!debug.contains(forbidden), "observer leaked {forbidden}");
}
@@ -1070,7 +1180,11 @@ mod observation_tests {
ToolRefusalCode::BrowserInputTrustUnavailable
);
let debug = format!("{observation:?}");
- for forbidden in ["private refusal prose", "private refusal message", "private tab id"] {
+ for forbidden in [
+ "private refusal prose",
+ "private refusal message",
+ "private tab id",
+ ] {
assert!(!debug.contains(forbidden), "observer leaked {forbidden}");
}
}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs
index 67870568dc..f0e6bf29d0 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/session.rs
@@ -452,7 +452,14 @@ mod tests {
#[test]
fn browser_mutations_are_computer_actions_but_reads_and_prepare_are_not() {
let args = serde_json::json!({"session": "test-session"});
- for tool_name in ["browser_navigate", "browser_click", "browser_type"] {
+ for tool_name in [
+ "browser_navigate",
+ "browser_click",
+ "browser_type",
+ "browser_set_input_files",
+ "browser_download",
+ "browser_pointer",
+ ] {
let operation = crate::server::tool_operation(tool_name, Some(&args));
assert!(
crate::server::is_computer_action(tool_name, operation),
@@ -466,6 +473,20 @@ mod tests {
"tool={tool_name}"
);
}
+ for action in ["accept", "dismiss"] {
+ let args = serde_json::json!({"action": action});
+ let operation = crate::server::tool_operation("browser_dialog", Some(&args));
+ assert!(crate::server::is_computer_action(
+ "browser_dialog",
+ operation
+ ));
+ }
+ let inspect = serde_json::json!({"action": "inspect"});
+ let operation = crate::server::tool_operation("browser_dialog", Some(&inspect));
+ assert!(!crate::server::is_computer_action(
+ "browser_dialog",
+ operation
+ ));
}
#[test]
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
index 581e2b8aaf..da0299c091 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs
@@ -103,7 +103,8 @@ impl ToolDef {
/// `recording.replay`, `recording.install_dependency`
/// - `page.action`
/// - `browser.state`, `browser.prepare`, `browser.navigate`,
-/// `browser.input.click`, `browser.input.type`
+/// `browser.input.click`, `browser.input.type`, `browser.input.files`,
+/// `browser.dialog`
/// - `driver.update_check`, `driver.probe`
///
/// Tools with no entry get `[]` — that's fine, it just means
@@ -267,6 +268,8 @@ pub fn default_capabilities_for(tool_name: &str) -> Vec<String> {
"browser_type" => &["browser.input.type"],
"browser_dialog" => &["browser.dialog"],
"browser_set_input_files" => &["browser.input.files"],
+ "browser_download" => &["browser.download"],
+ "browser_pointer" => &["browser.input.pointer"],
// ── driver self-service ──────────────────────────────────────
"check_for_update" => &["driver.update_check"],
@@ -484,19 +487,48 @@ fn is_existing_profile_prepare(tool_name: &str, args: &Value) -> bool {
}
fn recording_args_for(tool_name: &str, args: &Value) -> Value {
- if tool_name != "browser_prepare" {
- return args.clone();
- }
let mut redacted = args.clone();
if let Some(arguments) = redacted.as_object_mut() {
- if arguments.contains_key("approval_token") {
- arguments.insert(
- "approval_token".to_owned(),
- Value::String("[redacted]".to_owned()),
- );
+ match tool_name {
+ "browser_prepare" => {
+ if arguments.contains_key("approval_token") {
+ arguments.insert(
+ "approval_token".to_owned(),
+ Value::String("[redacted]".to_owned()),
+ );
+ }
+ arguments.remove("_cua_browser_prepare_mcp_host_approved");
+ arguments.remove("_transport_session_id");
+ }
+ "browser_dialog" => {
+ if arguments.contains_key("prompt_text") {
+ arguments.insert(
+ "prompt_text".to_owned(),
+ Value::String("[redacted]".to_owned()),
+ );
+ }
+ }
+ "browser_set_input_files" => {
+ if let Some(count) = arguments
+ .get("files")
+ .and_then(Value::as_array)
+ .map(Vec::len)
+ {
+ arguments.insert("files".to_owned(), serde_json::json!({ "count": count }));
+ }
+ }
+ "browser_download" => {
+ arguments.remove("_cua_browser_download_mcp_host_approved");
+ if arguments.contains_key("destination_root") {
+ arguments.insert(
+ "destination_root".to_owned(),
+ Value::String("[redacted]".to_owned()),
+ );
+ }
+ }
+ "browser_pointer" => {}
+ _ => {}
}
- arguments.remove("_cua_browser_prepare_mcp_host_approved");
- arguments.remove("_transport_session_id");
}
redacted
}
@@ -586,6 +618,46 @@ mod capability_tests {
assert_eq!(recorded["strategy"]["kind"], "existing_profile");
}
+ #[test]
+ fn browser_sensitive_recording_args_are_path_and_text_free() {
+ let dialog = recording_args_for(
+ "browser_dialog",
+ &serde_json::json!({"action": "accept", "prompt_text": "private reply"}),
+ );
+ assert_eq!(dialog["prompt_text"], "[redacted]");
+
+ let upload = recording_args_for(
+ "browser_set_input_files",
+ &serde_json::json!({"files": ["/private/one", "/private/two"]}),
+ );
+ assert_eq!(upload["files"], serde_json::json!({"count": 2}));
+
+ let download = recording_args_for(
+ "browser_download",
+ &serde_json::json!({
+ "destination_root": "/private/destination",
+ "_cua_browser_download_mcp_host_approved": true,
+ }),
+ );
+ assert_eq!(download["destination_root"], "[redacted]");
+ assert!(download
+ .get("_cua_browser_download_mcp_host_approved")
+ .is_none());
+
+ let serialized = serde_json::json!([dialog, upload, download]).to_string();
+ for forbidden in [
+ "private reply",
+ "/private/one",
+ "/private/two",
+ "/private/destination",
+ ] {
+ assert!(
+ !serialized.contains(forbidden),
+ "recording leaked {forbidden}"
+ );
+ }
+ }
+
#[test]
fn existing_profile_prepare_is_a_private_consent_turn() {
assert!(is_existing_profile_prepare(
@@ -671,6 +743,8 @@ mod capability_tests {
"browser_type",
"browser_dialog",
"browser_set_input_files",
+ "browser_download",
+ "browser_pointer",
];
/// All capability tokens in the canonical vocabulary. Any token
@@ -743,6 +817,10 @@ mod capability_tests {
"browser.navigate",
"browser.input.click",
"browser.input.type",
+ "browser.input.files",
+ "browser.dialog",
+ "browser.download",
+ "browser.input.pointer",
// driver self
"driver.update_check",
"driver.probe",
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
index a636d86c70..45552e7bfd 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/serve.rs
@@ -31,7 +31,7 @@ fn is_active_proxy_session(session: Option<&str>) -> bool {
session.is_some_and(|session| active_proxy_sessions().lock().unwrap().contains(session))
}
-fn inject_browser_prepare_approval(
+fn inject_browser_approvals(
tool_name: &str,
args: &mut serde_json::Value,
session: Option<&str>,
@@ -44,6 +44,14 @@ fn inject_browser_prepare_approval(
);
}
}
+ if tool_name == "browser_download" && is_active_proxy_session(session) {
+ if let Some(arguments) = args.as_object_mut() {
+ arguments.insert(
+ cua_driver_core::browser::download::MCP_HOST_DOWNLOAD_APPROVAL_ARG.to_owned(),
+ serde_json::Value::Bool(true),
+ );
+ }
+ }
}
// ── Recording idle-TTL backstop (#1764) ─────────────────────────────────────────
@@ -482,7 +490,7 @@ async fn invoke_daemon_tool(
}
}
- inject_browser_prepare_approval(&tool_name, &mut args, req.session_id.as_deref());
+ inject_browser_approvals(&tool_name, &mut args, req.session_id.as_deref());
let session_context = observation_transport.and_then(|transport| {
let transport = match transport {
@@ -1843,8 +1851,9 @@ mod telemetry_routing_tests {
#[cfg(test)]
mod session_boundary_tests {
- use super::{active_proxy_sessions, apply_session_identity, inject_browser_prepare_approval};
+ use super::{active_proxy_sessions, apply_session_identity, inject_browser_approvals};
use cua_driver_core::browser::approval::MCP_HOST_APPROVAL_ARG;
+ use cua_driver_core::browser::download::MCP_HOST_DOWNLOAD_APPROVAL_ARG;
use serde_json::json;
#[test]
@@ -1899,7 +1908,7 @@ mod session_boundary_tests {
fn browser_prepare_approval_requires_a_live_proxy_session() {
let session = "approval-boundary-test";
let mut raw_args = json!({"pid": 42});
- inject_browser_prepare_approval("browser_prepare", &mut raw_args, Some(session));
+ inject_browser_approvals("browser_prepare", &mut raw_args, Some(session));
assert!(raw_args.get(MCP_HOST_APPROVAL_ARG).is_none());
active_proxy_sessions()
@@ -1907,7 +1916,7 @@ mod session_boundary_tests {
.unwrap()
.insert(session.to_owned());
let mut proxy_args = json!({"pid": 42});
- inject_browser_prepare_approval("browser_prepare", &mut proxy_args, Some(session));
+ inject_browser_approvals("browser_prepare", &mut proxy_args, Some(session));
active_proxy_sessions().lock().unwrap().remove(session);
assert_eq!(proxy_args[MCP_HOST_APPROVAL_ARG], true);
@@ -1916,8 +1925,21 @@ mod session_boundary_tests {
.lock()
.unwrap()
.insert(session.to_owned());
- inject_browser_prepare_approval("get_browser_state", &mut other_tool, Some(session));
+ inject_browser_approvals("get_browser_state", &mut other_tool, Some(session));
active_proxy_sessions().lock().unwrap().remove(session);
assert!(other_tool.get(MCP_HOST_APPROVAL_ARG).is_none());
+
+ let mut raw_download = json!({"destination_root": "/private/path"});
+ inject_browser_approvals("browser_download", &mut raw_download, Some(session));
+ assert!(raw_download.get(MCP_HOST_DOWNLOAD_APPROVAL_ARG).is_none());
+
+ active_proxy_sessions()
+ .lock()
+ .unwrap()
+ .insert(session.to_owned());
+ let mut proxy_download = json!({"destination_root": "/private/path"});
+ inject_browser_approvals("browser_download", &mut proxy_download, Some(session));
+ active_proxy_sessions().lock().unwrap().remove(session);
+ assert_eq!(proxy_download[MCP_HOST_DOWNLOAD_APPROVAL_ARG], true);
}
}
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 b7335212f6..f3cf9d4a82 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs
@@ -426,6 +426,10 @@ impl AgentSessionState {
| "browser_navigate"
| "browser_click"
| "browser_type"
+ | "browser_dialog"
+ | "browser_set_input_files"
+ | "browser_download"
+ | "browser_pointer"
);
let refused = outcome.refusal_code.is_refusal();
let completed_computer_action = computer_action && !refused;
@@ -2568,6 +2572,55 @@ mod tests {
assert_eq!(session_properties["used_browser"], true);
}
+ #[test]
+ fn every_browser_tool_marks_the_session_without_retaining_arguments() {
+ use cua_driver_core::server::{
+ DurationBucket, OutputSizeBucket, OutputType, ToolCompletionObservation,
+ ToolErrorClass, ToolOperation, ToolRefusalCode,
+ };
+
+ for (tool_name, operation) in [
+ ("browser_dialog", ToolOperation::BrowserDialogAccept),
+ (
+ "browser_set_input_files",
+ ToolOperation::BrowserSetInputFiles,
+ ),
+ ("browser_download", ToolOperation::BrowserDownload),
+ (
+ "browser_pointer",
+ ToolOperation::BrowserPointerDoubleClickDomEvent,
+ ),
+ ] {
+ let mut state = AgentSessionState::new(Transport::McpStdio);
+ state.observe(
+ Transport::McpStdio,
+ true,
+ &ToolCompletionObservation {
+ tool_name: tool_name.into(),
+ operation,
+ computer_action: true,
+ success: true,
+ error_class: ToolErrorClass::None,
+ refusal_code: ToolRefusalCode::None,
+ duration_bucket: DurationBucket::Under10Ms,
+ output_type: OutputType::Text,
+ output_size_bucket: OutputSizeBucket::Under1KiB,
+ },
+ );
+ let properties =
+ state.ended_properties(cua_driver_core::session::SessionEndReason::Explicit, None);
+ assert_eq!(properties["used_browser"], true, "tool={tool_name}");
+ assert_eq!(
+ properties["had_successful_computer_action"], true,
+ "tool={tool_name}"
+ );
+ let serialized = serde_json::to_string(&properties).unwrap();
+ assert!(!serialized.contains("destination_root"));
+ assert!(!serialized.contains("prompt_text"));
+ assert!(!serialized.contains("file_paths"));
+ }
+ }
+
#[test]
fn agent_session_buckets_have_fixed_boundaries() {
for (count, expected) in [