Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(cua-driver): share one approved Chrome connection across sessions (#5115)
Francesco Bonaccia3a50cbc4fe0
diff --git a/docs/content/docs/cua-driver/reference/mcp-tools/page.mdx b/docs/content/docs/cua-driver/reference/mcp-tools/page.mdxindex 0835d3c82f..6d142b9063 100644--- a/docs/content/docs/cua-driver/reference/mcp-tools/page.mdx+++ b/docs/content/docs/cua-driver/reference/mcp-tools/page.mdx@@ -77,7 +77,7 @@ Effect: read-only, idempotent. Platforms: macOS, Linux, Windows.## `browser_prepare`-Attach the browser tools to a browser. For a page in the user's running Chrome, Edge or Brave, call it once with pid, window_id, session and strategy {"kind":"existing_profile"} when get_browser_state refuses with browser_consent_required or browser_requires_setup; then call get_browser_state again and act with browser_click, browser_type or browser_pointer. It attaches, or refuses with nothing changed and says why. Explicitly prepare an owned DevTools endpoint for a browser. pid is required for an existing process or existing-profile attachment, and optional only for allow_launch=true with an isolated profile. Existing endpoints are detected without side effects. Acting setup for an isolated profile follows the runtime permission mode and optional capability manifest. It requires allow_launch=true, launches a separate browser, and never copies, modifies, or terminates the requested user profile. Without pid, only a platform-attested system Chrome/Edge installation (or a root-owned package payload on Linux) is eligible; redirects and user-controlled locations fail closed. Existing-profile attachment is explicit and follows the runtime's immutable permission mode: standard requires an explicit --grant existing-profile launch grant or an embedding authorization host, bounded requires a launch-approved exact resource manifest, and unrestricted requires explicit trusted startup risk acceptance. Ordinary MCP transport approval never proves profile authorization. On proven platforms, an authorized request also permits one bounded exact-window setup: open the recognized browser product's fixed remote-debugging page, toggle its uniquely matched per-instance checkbox, prove the PID-owned loopback endpoint, and close the temporary tab. Every visible effect is reported; ambiguity is refused. Where attaching would bring the browser in front of the user's app (macOS Chrome shows its own remote-debugging prompt in front for every new connection), existing-profile attachment refuses with background_unavailable unless delivery_mode is "foreground" (the app that was in front is brought back afterwards) or the browser window is on another Space than the user's, where it attaches in the background while the driver reverts the browser's own brief activations.+Attach the browser tools to a browser. For a page in the user's running Chrome, Edge or Brave, call it once with pid, window_id, session and strategy {"kind":"existing_profile"} when get_browser_state refuses with browser_consent_required or browser_requires_setup; then call get_browser_state again and act with browser_click, browser_type or browser_pointer. It attaches, or refuses with nothing changed and says why. Explicitly prepare an owned DevTools endpoint for a browser. pid is required for an existing process or existing-profile attachment, and optional only for allow_launch=true with an isolated profile. Existing endpoints are detected without side effects. Acting setup for an isolated profile follows the runtime permission mode and optional capability manifest. It requires allow_launch=true, launches a separate browser, and never copies, modifies, or terminates the requested user profile. Without pid, only a platform-attested system Chrome/Edge installation (or a root-owned package payload on Linux) is eligible; redirects and user-controlled locations fail closed. Existing-profile attachment is explicit and follows the runtime's immutable permission mode: standard requires an explicit --grant existing-profile launch grant or an embedding authorization host, bounded requires a launch-approved exact resource manifest, and unrestricted requires explicit trusted startup risk acceptance. Ordinary MCP transport approval never proves profile authorization. On proven platforms, an authorized request also permits one bounded exact-window setup: open the recognized browser product's fixed remote-debugging page, toggle its uniquely matched per-instance checkbox, prove the PID-owned loopback endpoint, and close the temporary tab. Every visible effect is reported; ambiguity is refused. Where attaching would bring the browser in front of the user's app (macOS Chrome shows its own remote-debugging prompt in front whenever the driver opens a new browser connection; sessions for the same browser share one approved connection, kept for up to 30 minutes idle and 8 hours in total, so later sessions do not prompt again), existing-profile attachment refuses with background_unavailable unless delivery_mode is "foreground" (the app that was in front is brought back afterwards) or the browser window is on another Space than the user's, where it attaches in the background while the driver reverts the browser's own brief activations.Effect: destructive. Platforms: macOS, Linux, Windows.diff --git a/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md b/libs/cua-driver/rust/Skills/cua-driver/BROWSER.mdindex dce2cab2e6..fedfb1a582 100644--- a/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md+++ b/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md@@ -208,6 +208,15 @@ authorize generic pixel interaction.On macOS this attachment cannot stay in the background. Chrome brings itselfto the front to show its "Allow remote debugging?" prompt for every newDevTools connection, and turning remote debugging on needs Chrome in front.+Chrome does not prompt again for tabs or targets reached over a connection it+already allowed, so the driver keeps one approved connection per running+Chrome and every session for that Chrome shares it: a second session, or a new+session after the previous one ended, attaches without another prompt. Each+session still needs its own `browser_prepare` approval from the driver, and+only sees the targets it bound. The shared connection closes after 30 minutes+without a session, 8 hours after the prompt that opened it, when the daemon+restarts, on `cua-driver revoke --all`, or when the driver turns remote+debugging back off; the next session after that prompts once again.When the Chrome window is on another Space than the user's, the attach runs inthe background: the driver turns remote debugging on without bringing Chromeforward, and reverts Chrome's own brief activations (its consent window opensdiff --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.rsindex 08580616fb..c401f20b43 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@@ -14,8 +14,8 @@use std::collections::{HashMap, HashSet};use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};-use std::sync::{Arc, Mutex as StdMutex, OnceLock};-use std::time::Duration;+use std::sync::{Arc, Mutex as StdMutex, OnceLock, Weak};+use std::time::{Duration, Instant};use futures_util::stream::{SplitSink, SplitStream};use futures_util::{SinkExt, StreamExt};@@ -408,10 +408,65 @@ impl CdpConnection {}}+/// How long a consented existing-profile socket may stay open with no session+/// holding it. Matches the existing-profile grant idle bound.+pub const SHARED_SOCKET_IDLE_TTL: Duration = Duration::from_secs(30 * 60);+/// Absolute bound measured from the browser consent that opened the socket.+/// Matches the existing-profile grant absolute bound.+pub const SHARED_SOCKET_ABSOLUTE_TTL: Duration = Duration::from_secs(8 * 60 * 60);++/// How a grant gives up its hold on a shared existing-profile socket.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum SharedSocketRelease {+ /// Normal session end: when this was the last holder, keep the+ /// already-consented socket open (parked) for the idle bound so the next+ /// approved session does not trigger another browser consent prompt.+ Park,+ /// Security-relevant end (identity change, remote debugging being turned+ /// back off, expiry): close the socket once no other session holds it.+ Close,+}++/// Grant-owned state of one browser-level existing-profile socket. Chrome+/// asks the person to approve every new browser-level WebSocket, but not+/// target attaches over an existing one, so every approved session for the+/// same browser instance multiplexes over this one socket through flattened+/// target sessions.+#[derive(Clone)]+struct SharedSocket {+ /// Live grant generations bound to this socket. Generations are unique+ /// per engine, so one holder can never release another holder's claim.+ holders: HashSet<u64>,+ opened_at: Instant,+ last_used_at: Instant,+}++impl SharedSocket {+ fn new(generation: u64, now: Instant) -> Self {+ Self {+ holders: HashSet::from([generation]),+ opened_at: now,+ last_used_at: now,+ }+ }++ fn expired(&self, now: Instant, ttl: &SharedSocketTtl) -> bool {+ now.duration_since(self.opened_at) > ttl.absolute+ || (self.holders.is_empty() && now.duration_since(self.last_used_at) > ttl.idle)+ }+}+#[derive(Clone)]struct PoolEntry {conn: Arc<CdpConnection>,- generation: Option<u64>,+ /// `None` for an unrestricted driver-owned endpoint.+ shared: Option<SharedSocket>,+}++#[derive(Clone, Copy)]+struct SharedSocketTtl {+ idle: Duration,+ absolute: Duration,}fn claimed_ports() -> &'static StdMutex<HashMap<u16, usize>> {@@ -419,6 +474,11 @@ fn claimed_ports() -> &'static StdMutex<HashMap<u16, usize>> {CLAIMED.get_or_init(|| StdMutex::new(HashMap::new()))}+fn live_pools() -> &'static StdMutex<Vec<Weak<PoolInner>>> {+ static POOLS: OnceLock<StdMutex<Vec<Weak<PoolInner>>>> = OnceLock::new();+ POOLS.get_or_init(|| StdMutex::new(Vec::new()))+}+fn loopback_port(url: &str) -> Option<u16> {let rest = url.strip_prefix("ws://")?;let authority = rest.split('/').next()?;@@ -434,19 +494,152 @@ pub fn endpoint_port_is_grant_owned(url: &str) -> bool {loopback_port(url).is_some_and(|port| claimed_ports().lock().unwrap().contains_key(&port))}+/// Close every parked (unheld) existing-profile socket in this process. Used+/// when the person revokes all driver sessions: revocation must not leave an+/// already-consented browser socket waiting for the next session.+pub async fn close_parked_browser_sockets() -> usize {+ let pools: Vec<Arc<PoolInner>> = {+ let mut pools = live_pools().lock().unwrap();+ pools.retain(|pool| pool.strong_count() > 0);+ pools.iter().filter_map(Weak::upgrade).collect()+ };+ let mut closed = 0;+ for pool in pools {+ closed += pool.close_parked().await;+ }+ closed+}++/// Per-pool record of which endpoint URLs are grant-owned, so the global+/// per-port marker is held exactly while at least one grant-owned entry for+/// that port exists in this pool.+#[derive(Default)]+struct Markers {+ urls: HashSet<String>,+ ports: HashMap<u16, usize>,+}++struct PoolInner {+ conns: Mutex<HashMap<String, PoolEntry>>,+ /// Serializes every browser-level dial for grant-owned sockets so two+ /// sessions can never open two sockets (and two consent prompts) at once.+ dial_gate: Mutex<()>,+ markers: StdMutex<Markers>,+ ttl: SharedSocketTtl,+}++impl PoolInner {+ async fn close_parked(&self) -> usize {+ let mut conns = self.conns.lock().await;+ let parked: Vec<String> = conns+ .iter()+ .filter(|(_, entry)| entry.shared.as_ref().is_some_and(|s| s.holders.is_empty()))+ .map(|(url, _)| url.clone())+ .collect();+ for url in &parked {+ self.remove_entry(&mut conns, url);+ }+ parked.len()+ }++ fn mark_shared(&self, url: &str) {+ let Some(port) = loopback_port(url) else {+ return;+ };+ let mut markers = self.markers.lock().unwrap();+ if !markers.urls.insert(url.to_owned()) {+ return;+ }+ let count = markers.ports.entry(port).or_default();+ *count += 1;+ if *count == 1 {+ *claimed_ports().lock().unwrap().entry(port).or_default() += 1;+ }+ }++ fn unmark_shared(&self, url: &str) {+ let Some(port) = loopback_port(url) else {+ return;+ };+ let mut markers = self.markers.lock().unwrap();+ if !markers.urls.remove(url) {+ return;+ }+ if let Some(count) = markers.ports.get_mut(&port) {+ *count -= 1;+ if *count == 0 {+ markers.ports.remove(&port);+ release_claimed_port(port);+ }+ }+ }++ fn insert_shared(&self, conns: &mut HashMap<String, PoolEntry>, url: &str, entry: PoolEntry) {+ conns.insert(url.to_owned(), entry);+ self.mark_shared(url);+ }++ fn remove_entry(&self, conns: &mut HashMap<String, PoolEntry>, url: &str) {+ if conns+ .remove(url)+ .is_some_and(|entry| entry.shared.is_some())+ {+ self.unmark_shared(url);+ }+ }++ /// Return the live shared socket for `url`, dropping it first when it is+ /// closed or past its bounds.+ fn live_shared<'a>(+ &self,+ conns: &'a mut HashMap<String, PoolEntry>,+ url: &str,+ now: Instant,+ ) -> Option<&'a mut PoolEntry> {+ let stale = conns.get(url).is_some_and(|entry| {+ entry+ .shared+ .as_ref()+ .is_some_and(|shared| entry.conn.is_closed() || shared.expired(now, &self.ttl))+ });+ if stale {+ self.remove_entry(conns, url);+ }+ conns.get_mut(url).filter(|entry| entry.shared.is_some())+ }+}++impl Drop for PoolInner {+ fn drop(&mut self) {+ let markers = std::mem::take(self.markers.get_mut().unwrap());+ for port in markers.ports.into_keys() {+ release_claimed_port(port);+ }+ }+}+/// One pooled browser-level connection per endpoint URL. Existing-profile-/// entries are additionally owned by one explicit connection generation.+/// entries are shared by every grant for that browser instance: each grant+/// generation is a refcounted holder, and the socket outlives individual+/// sessions only within the bounded parking window.pub struct CdpPool {- conns: Mutex<HashMap<String, PoolEntry>>,- claimed_loopback_ports: StdMutex<HashSet<u16>>,+ inner: Arc<PoolInner>,}impl CdpPool {pub fn new() -> Self {- Self {+ Self::with_shared_socket_ttls(SHARED_SOCKET_IDLE_TTL, SHARED_SOCKET_ABSOLUTE_TTL)+ }++ pub(crate) fn with_shared_socket_ttls(idle: Duration, absolute: Duration) -> Self {+ let inner = Arc::new(PoolInner {conns: Mutex::new(HashMap::new()),- claimed_loopback_ports: StdMutex::new(HashSet::new()),- }+ dial_gate: Mutex::new(()),+ markers: StdMutex::new(Markers::default()),+ ttl: SharedSocketTtl { idle, absolute },+ });+ live_pools().lock().unwrap().push(Arc::downgrade(&inner));+ Self { inner }}/// Get the pooled connection for `ws_url`, dialing if needed.@@ -457,9 +650,9 @@ impl CdpPool {"this DevTools endpoint is owned by a first-class existing-profile attachment");}- let mut conns = self.conns.lock().await;+ let mut conns = self.inner.conns.lock().await;if let Some(existing) = conns.get(ws_url) {- if existing.generation.is_some() {+ if existing.shared.is_some() {anyhow::bail!("this DevTools endpoint is owned by an attachment generation");}if !existing.conn.is_closed() {@@ -472,42 +665,77 @@ impl CdpPool {ws_url.to_owned(),PoolEntry {conn: conn.clone(),- generation: None,+ shared: None,},);Ok(conn)}- /// Convert the one live browser-level socket into grant-owned state. This- /// does not redial and therefore cannot create a second consent prompt.+ /// Bind grant `generation` to the browser socket for `ws_url`. A live+ /// shared socket (held by another session, or parked after one ended) is+ /// joined without dialing, so no new browser consent prompt appears. Only+ /// when no usable socket exists is exactly one new socket opened.pub async fn claim_existing(&self,ws_url: &str,generation: u64,) -> anyhow::Result<Arc<CdpConnection>> {- let port = loopback_port(ws_url)+ loopback_port(ws_url).ok_or_else(|| anyhow::anyhow!("existing-profile endpoint has no loopback port"))?;- let mut conns = self.conns.lock().await;- let conn = match conns.get(ws_url) {- Some(entry) if !entry.conn.is_closed() => entry.conn.clone(),- Some(_) => anyhow::bail!("the approved browser socket closed before it was claimed"),- None => Arc::new(CdpConnection::connect(ws_url).await?),- };+ let _dial = self.inner.dial_gate.lock().await;+ {+ let now = Instant::now();+ let mut conns = self.inner.conns.lock().await;+ if let Some(entry) = self.inner.live_shared(&mut conns, ws_url, now) {+ let shared = entry+ .shared+ .as_mut()+ .expect("live_shared returns shared entries");+ shared.holders.insert(generation);+ shared.last_used_at = now;+ return Ok(entry.conn.clone());+ }+ match conns.get(ws_url) {+ Some(entry) if !entry.conn.is_closed() => {+ // Convert the one live socket that proved the endpoint+ // into grant-owned state in place, without redialing.+ let conn = entry.conn.clone();+ conn.restrict_to_existing_profile();+ self.inner.insert_shared(+ &mut conns,+ ws_url,+ PoolEntry {+ conn: conn.clone(),+ shared: Some(SharedSocket::new(generation, now)),+ },+ );+ return Ok(conn);+ }+ Some(_) => {+ anyhow::bail!("the approved browser socket closed before it was claimed")+ }+ None => {}+ }+ }++ // The WebSocket handshake can wait for browser-owned consent UI.+ // Never hold the entry mutex across that wait: other sessions keep+ // using their sockets and revocation stays responsive.+ let conn = Arc::new(CdpConnection::connect(ws_url).await?);conn.restrict_to_existing_profile();- conns.insert(- ws_url.to_owned(),+ let mut conns = self.inner.conns.lock().await;+ self.inner.insert_shared(+ &mut conns,+ ws_url,PoolEntry {conn: conn.clone(),- generation: Some(generation),+ shared: Some(SharedSocket::new(generation, Instant::now())),},);- if self.claimed_loopback_ports.lock().unwrap().insert(port) {- *claimed_ports().lock().unwrap().entry(port).or_default() += 1;- }Ok(conn)}- /// Reuse only the socket belonging to the exact live grant generation.+ /// Reuse the shared socket only while `generation` still holds it./// Closed sockets are not replaced here; reconnect is an explicit state/// transition owned by the browser engine.pub async fn get_existing(@@ -515,115 +743,162 @@ impl CdpPool {ws_url: &str,generation: u64,) -> anyhow::Result<Arc<CdpConnection>> {- let conns = self.conns.lock().await;+ let now = Instant::now();+ let mut conns = self.inner.conns.lock().await;let entry = conns- .get(ws_url)+ .get_mut(ws_url).ok_or_else(|| anyhow::anyhow!("the grant-owned browser socket is missing"))?;- if entry.generation != Some(generation) {+ let shared = entry+ .shared+ .as_mut()+ .ok_or_else(|| anyhow::anyhow!("the browser socket is not grant-owned"))?;+ if !shared.holders.contains(&generation) {anyhow::bail!("the browser socket belongs to a different connection generation");}if entry.conn.is_closed() {anyhow::bail!("the grant-owned browser socket is closed");}+ if now.duration_since(shared.opened_at) > self.inner.ttl.absolute {+ anyhow::bail!("the grant-owned browser socket reached its absolute lifetime");+ }+ shared.last_used_at = now;Ok(entry.conn.clone())}- /// Replace one dead grant-owned socket with exactly one new generation.+ /// Move one grant from `old_generation` to `new_generation`. If another+ /// session already re-established a live shared socket, join it without+ /// dialing; otherwise open exactly one replacement socket (which the+ /// browser treats as a new connection and may ask the person to approve).pub async fn reconnect_existing(&self,ws_url: &str,old_generation: u64,new_generation: u64,) -> anyhow::Result<Arc<CdpConnection>> {+ let _dial = self.inner.dial_gate.lock().await;{- let conns = self.conns.lock().await;- if let Some(entry) = conns.get(ws_url) {- if entry- .generation- .is_some_and(|generation| generation > old_generation)- {- anyhow::bail!("the reconnect source generation is no longer current");- }- if entry.generation == Some(old_generation) && !entry.conn.is_closed() {- return Ok(entry.conn.clone());- }+ let now = Instant::now();+ let mut conns = self.inner.conns.lock().await;+ if let Some(entry) = self.inner.live_shared(&mut conns, ws_url, now) {+ let shared = entry+ .shared+ .as_mut()+ .expect("live_shared returns shared entries");+ shared.holders.remove(&old_generation);+ shared.holders.insert(new_generation);+ shared.last_used_at = now;+ return Ok(entry.conn.clone());}}- // A WebSocket handshake can wait for browser-owned consent UI. Never- // hold the pool mutex across that wait: grant revocation must remain- // able to remove the old generation when consent is refused.+ // See claim_existing: never hold the entry mutex across a dial that+ // can wait for browser-owned consent UI.let conn = Arc::new(CdpConnection::connect(ws_url).await?);conn.restrict_to_existing_profile();- let mut conns = self.conns.lock().await;- if let Some(entry) = conns.get(ws_url) {- if entry- .generation- .is_some_and(|generation| generation > old_generation)- {- if entry.generation == Some(new_generation) && !entry.conn.is_closed() {- return Ok(entry.conn.clone());- }- anyhow::bail!("the reconnect source generation is no longer current");- }- }- conns.insert(- ws_url.to_owned(),+ let mut conns = self.inner.conns.lock().await;+ // Holders of the dead socket rebind through their own reconnect,+ // which joins this socket without dialing.+ self.inner.insert_shared(+ &mut conns,+ ws_url,PoolEntry {conn: conn.clone(),- generation: Some(new_generation),+ shared: Some(SharedSocket::new(new_generation, Instant::now())),},);Ok(conn)}- /// Drop a (likely dead) connection so the next call redials.+ /// Drop a (likely dead) unrestricted connection so the next call+ /// redials. Grant-owned sockets are never evicted by the legacy route.pub async fn evict(&self, ws_url: &str) {- self.conns.lock().await.remove(ws_url);- }-- pub fn release_claim_marker(&self, ws_url: &str) {- if let Some(port) = loopback_port(ws_url) {- if self.claimed_loopback_ports.lock().unwrap().remove(&port) {- release_claimed_port(port);- }- }- }-- pub async fn release_existing(&self, ws_url: &str, generation: u64) {- let mut conns = self.conns.lock().await;+ let mut conns = self.inner.conns.lock().await;if conns.get(ws_url)- .is_some_and(|entry| entry.generation == Some(generation))+ .is_some_and(|entry| entry.shared.is_none()){conns.remove(ws_url);}- drop(conns);- self.release_claim_marker(ws_url);}-}-impl Default for CdpPool {- fn default() -> Self {- Self::new()+ /// Release grant `generation`'s hold on the socket for `ws_url`. Only a+ /// current holder can affect the socket, and the socket is never closed+ /// while another session still holds it.+ pub async fn release_existing(&self, ws_url: &str, generation: u64, mode: SharedSocketRelease) {+ let now = Instant::now();+ let mut conns = self.inner.conns.lock().await;+ let Some(entry) = conns.get_mut(ws_url) else {+ return;+ };+ let Some(shared) = entry.shared.as_mut() else {+ return;+ };+ if !shared.holders.remove(&generation) || !shared.holders.is_empty() {+ return;+ }+ if mode == SharedSocketRelease::Park+ && !entry.conn.is_closed()+ && !shared.expired(now, &self.inner.ttl)+ {+ shared.last_used_at = now;+ drop(conns);+ self.schedule_parked_reaper(ws_url);+ } else {+ self.inner.remove_entry(&mut conns, ws_url);+ }}-}-impl Drop for CdpPool {- fn drop(&mut self) {- let claimed_loopback_ports = self.claimed_loopback_ports.get_mut().unwrap();- if claimed_loopback_ports.is_empty() {+ /// Number of sessions holding the shared socket for `ws_url`, or `None`+ /// when no grant-owned socket exists (diagnostics/tests).+ pub async fn shared_socket_holders(&self, ws_url: &str) -> Option<usize> {+ let conns = self.inner.conns.lock().await;+ conns+ .get(ws_url)+ .and_then(|entry| entry.shared.as_ref())+ .map(|shared| shared.holders.len())+ }++ fn schedule_parked_reaper(&self, ws_url: &str) {+ let Ok(runtime) = tokio::runtime::Handle::try_current() else {return;- }- let mut global = claimed_ports().lock().unwrap();- for port in claimed_loopback_ports.drain() {- if let Some(count) = global.get_mut(&port) {- *count -= 1;- if *count == 0 {- global.remove(&port);+ };+ let weak = Arc::downgrade(&self.inner);+ let url = ws_url.to_owned();+ let mut wait = self.inner.ttl.idle;+ runtime.spawn(async move {+ loop {+ tokio::time::sleep(wait + Duration::from_millis(10)).await;+ let Some(inner) = weak.upgrade() else {+ return;+ };+ let now = Instant::now();+ let mut conns = inner.conns.lock().await;+ let Some(entry) = conns.get(&url) else {+ return;+ };+ let Some(shared) = entry.shared.as_ref() else {+ return;+ };+ if !shared.holders.is_empty() {+ // Held again; a later release schedules a fresh reaper.+ return;+ }+ if entry.conn.is_closed() || shared.expired(now, &inner.ttl) {+ inner.remove_entry(&mut conns, &url);+ return;}+ wait = inner+ .ttl+ .idle+ .saturating_sub(now.duration_since(shared.last_used_at));}- }+ });+ }+}++impl Default for CdpPool {+ fn default() -> Self {+ Self::new()}}@@ -703,13 +978,191 @@ mod tests {assert!(pool.get_existing(&url, 2).await.is_err());let reused = pool.get_existing(&url, 1).await.unwrap();assert!(Arc::ptr_eq(&claimed, &reused));- pool.release_existing(&url, 1).await;+ pool.release_existing(&url, 1, SharedSocketRelease::Close)+ .await;assert!(pool.get(&url).await.is_ok(),- "session cleanup releases ownership"+ "closing the last holder releases ownership");}+ /// Accepts browser-level sockets and counts each handshake, i.e. each+ /// time a real browser would show its remote-debugging consent prompt.+ async fn counting_browser() -> (+ String,+ StdArc<std::sync::atomic::AtomicUsize>,+ tokio::task::JoinHandle<()>,+ ) {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let port = listener.local_addr().unwrap().port();+ let dials = StdArc::new(std::sync::atomic::AtomicUsize::new(0));+ let counter = dials.clone();+ let task = tokio::spawn(async move {+ loop {+ let Ok((stream, _)) = listener.accept().await else {+ return;+ };+ let counter = counter.clone();+ tokio::spawn(async move {+ let Ok(mut ws) = tokio_tungstenite::accept_async(stream).await else {+ return;+ };+ counter.fetch_add(1, Ordering::SeqCst);+ while let Some(Ok(_)) = ws.next().await {}+ });+ }+ });+ (+ format!("ws://127.0.0.1:{port}/devtools/browser/shared"),+ dials,+ task,+ )+ }++ #[tokio::test]+ async fn sessions_share_one_browser_socket_and_cannot_close_each_other() {+ let (url, dials, server) = counting_browser().await;+ let pool = CdpPool::new();+ let a = pool.claim_existing(&url, 10).await.unwrap();+ let b = pool.claim_existing(&url, 11).await.unwrap();+ assert!(Arc::ptr_eq(&a, &b), "second session must join, not redial");+ assert_eq!(+ dials.load(Ordering::SeqCst),+ 1,+ "one consent for both sessions"+ );+ assert_eq!(pool.shared_socket_holders(&url).await, Some(2));++ // A security close by one session leaves the other session's socket alone.+ pool.release_existing(&url, 10, SharedSocketRelease::Close)+ .await;+ assert!(!b.is_closed());+ let still = pool.get_existing(&url, 11).await.unwrap();+ assert!(Arc::ptr_eq(&b, &still));+ assert!(+ pool.get_existing(&url, 10).await.is_err(),+ "a released generation cannot keep using the shared socket"+ );++ // Releasing a generation that never held the socket is a no-op.+ pool.release_existing(&url, 99, SharedSocketRelease::Close)+ .await;+ assert_eq!(pool.shared_socket_holders(&url).await, Some(1));+ server.abort();+ }++ #[tokio::test]+ async fn parked_socket_serves_the_next_session_without_a_new_dial() {+ let (url, dials, server) = counting_browser().await;+ let pool = CdpPool::new();+ let first = pool.claim_existing(&url, 1).await.unwrap();+ pool.release_existing(&url, 1, SharedSocketRelease::Park)+ .await;+ assert_eq!(pool.shared_socket_holders(&url).await, Some(0), "parked");+ assert!(+ endpoint_port_is_grant_owned(&url),+ "a parked personal-profile socket stays off the legacy route"+ );+ assert!(pool.get(&url).await.is_err());++ let next = pool.claim_existing(&url, 2).await.unwrap();+ assert!(Arc::ptr_eq(&first, &next));+ assert_eq!(dials.load(Ordering::SeqCst), 1);+ server.abort();+ }++ #[tokio::test]+ async fn parked_socket_closes_after_the_idle_bound() {+ let (url, dials, server) = counting_browser().await;+ let pool = CdpPool::with_shared_socket_ttls(+ std::time::Duration::from_millis(50),+ std::time::Duration::from_secs(3600),+ );+ pool.claim_existing(&url, 1).await.unwrap();+ pool.release_existing(&url, 1, SharedSocketRelease::Park)+ .await;+ tokio::time::sleep(std::time::Duration::from_millis(200)).await;+ assert_eq!(+ pool.shared_socket_holders(&url).await,+ None,+ "the reaper closes an idle parked socket"+ );+ assert!(!endpoint_port_is_grant_owned(&url));++ pool.claim_existing(&url, 2).await.unwrap();+ assert_eq!(+ dials.load(Ordering::SeqCst),+ 2,+ "a later session dials again"+ );+ server.abort();+ }++ #[tokio::test]+ async fn socket_past_its_absolute_bound_is_not_joined() {+ let (url, dials, server) = counting_browser().await;+ let pool = CdpPool::with_shared_socket_ttls(+ std::time::Duration::from_secs(3600),+ std::time::Duration::from_millis(50),+ );+ let old = pool.claim_existing(&url, 1).await.unwrap();+ tokio::time::sleep(std::time::Duration::from_millis(100)).await;+ assert!(pool.get_existing(&url, 1).await.is_err());+ let fresh = pool.claim_existing(&url, 2).await.unwrap();+ assert!(!Arc::ptr_eq(&old, &fresh));+ assert_eq!(dials.load(Ordering::SeqCst), 2);+ server.abort();+ }++ #[tokio::test]+ async fn security_close_of_the_last_holder_does_not_park() {+ let (url, _dials, server) = counting_browser().await;+ let pool = CdpPool::new();+ pool.claim_existing(&url, 1).await.unwrap();+ pool.release_existing(&url, 1, SharedSocketRelease::Close)+ .await;+ assert_eq!(pool.shared_socket_holders(&url).await, None);+ assert!(!endpoint_port_is_grant_owned(&url));+ server.abort();+ }++ #[tokio::test]+ async fn reconnect_joins_a_socket_another_session_already_reopened() {+ let (url, dials, server) = counting_browser().await;+ let pool = CdpPool::new();+ let dead = pool.claim_existing(&url, 1).await.unwrap();+ pool.claim_existing(&url, 2).await.unwrap();+ dead.demux.close();++ let reopened = pool.reconnect_existing(&url, 1, 3).await.unwrap();+ let joined = pool.reconnect_existing(&url, 2, 4).await.unwrap();+ assert!(Arc::ptr_eq(&reopened, &joined));+ assert_eq!(+ dials.load(Ordering::SeqCst),+ 2,+ "one reconnect dial for both sessions"+ );+ assert_eq!(pool.shared_socket_holders(&url).await, Some(2));+ server.abort();+ }++ #[tokio::test]+ async fn revoking_all_sessions_closes_parked_sockets_only() {+ let (parked_url, _d1, s1) = counting_browser().await;+ let (held_url, _d2, s2) = counting_browser().await;+ let pool = CdpPool::new();+ pool.claim_existing(&parked_url, 1).await.unwrap();+ pool.release_existing(&parked_url, 1, SharedSocketRelease::Park)+ .await;+ pool.claim_existing(&held_url, 2).await.unwrap();++ assert_eq!(pool.inner.close_parked().await, 1);+ assert_eq!(pool.shared_socket_holders(&parked_url).await, None);+ assert_eq!(pool.shared_socket_holders(&held_url).await, Some(1));+ s1.abort();+ s2.abort();+ }+#[tokio::test]async fn existing_profile_policy_rejects_fingerprint_and_interception_methods() {let seen = StdArc::new(StdMutex::new(Vec::<String>::new()));@@ -798,7 +1251,7 @@ mod tests {}tokio::time::timeout(std::time::Duration::from_millis(500),- pool.release_existing(&url, 1),+ pool.release_existing(&url, 1, SharedSocketRelease::Close),).await.expect("grant release must not wait for the reconnect handshake");@@ -966,4 +1419,112 @@ mod tests {);second.call(None, "Ping.pong", json!({})).await.unwrap();}++ /// Live check against a real Chrome whose remote debugging was allowed in+ /// `chrome://inspect/#remote-debugging`. Chrome shows its "Allow remote+ /// debugging?" prompt for the first socket; a person (or the driver's+ /// consent adapter) must accept it within the connect timeout. Every later+ /// session must reuse that socket without a second prompt.+ ///+ /// CUA_E2E_CHROME_DEVTOOLS_ACTIVE_PORT=<user-data-dir>/DevToolsActivePort \+ /// cargo test -p cua-driver-core --lib real_chrome -- --ignored --nocapture+ #[tokio::test]+ #[ignore = "needs a disposable Chrome with remote debugging allowed and a person to accept one prompt"]+ async fn real_chrome_sessions_share_one_consented_socket() {+ let Some(path) = std::env::var_os("CUA_E2E_CHROME_DEVTOOLS_ACTIVE_PORT") else {+ return;+ };+ let active = std::fs::read_to_string(path).unwrap();+ let mut lines = active.lines();+ let port = lines.next().unwrap().trim();+ let browser_path = lines.next().unwrap().trim();+ let url = format!("ws://127.0.0.1:{port}{browser_path}");+ let pool = CdpPool::new();+ let started = std::time::Instant::now();+ let log = |step: &str| eprintln!("[{:>7.3}s] {step}", started.elapsed().as_secs_f64());++ log("session A: claim (Chrome prompts for this first socket)");+ let a = pool.claim_existing(&url, 1).await.unwrap();+ log("session A: socket open");++ let page = |conn: Arc<CdpConnection>| async move {+ let targets = conn+ .call(None, "Target.getTargets", json!({}))+ .await+ .unwrap();+ targets["targetInfos"]+ .as_array()+ .unwrap()+ .iter()+ .find(|t| t["type"] == "page")+ .map(|t| t["targetId"].as_str().unwrap().to_owned())+ .unwrap()+ };+ let attach_and_eval = |conn: Arc<CdpConnection>, target: String| async move {+ let attached = conn+ .call(+ None,+ "Target.attachToTarget",+ json!({ "targetId": target, "flatten": true }),+ )+ .await+ .unwrap();+ let session = attached["sessionId"].as_str().unwrap().to_owned();+ let value = conn+ .call(+ Some(&session),+ "Runtime.evaluate",+ json!({ "expression": "1 + 1", "returnByValue": true }),+ )+ .await+ .unwrap();+ assert_eq!(value["result"]["value"], 2);+ session+ };+ let target = page(a.clone()).await;+ let session_a = attach_and_eval(a.clone(), target.clone()).await;++ let t = std::time::Instant::now();+ let b = pool.claim_existing(&url, 2).await.unwrap();+ log("session B: claimed");+ assert!(+ Arc::ptr_eq(&a, &b),+ "session B must reuse the consented socket"+ );+ assert!(+ t.elapsed() < std::time::Duration::from_millis(500),+ "no consent wait"+ );+ let session_b = attach_and_eval(b.clone(), target.clone()).await;+ assert_ne!(+ session_a, session_b,+ "each session gets its own flattened CDP session"+ );++ pool.release_existing(&url, 1, SharedSocketRelease::Close)+ .await;+ log("session A: ended");+ let b = pool.get_existing(&url, 2).await.unwrap();+ attach_and_eval(b, target.clone()).await;+ log("session B: still working after A ended");++ pool.release_existing(&url, 2, SharedSocketRelease::Park)+ .await;+ log("session B: ended (socket parked)");+ let t = std::time::Instant::now();+ let c = pool.claim_existing(&url, 3).await.unwrap();+ assert!(+ Arc::ptr_eq(&a, &c),+ "a later session must reuse the parked socket"+ );+ assert!(+ t.elapsed() < std::time::Duration::from_millis(500),+ "no consent wait"+ );+ attach_and_eval(c, target).await;+ log("session C: working on the parked socket without a prompt");+ pool.release_existing(&url, 3, SharedSocketRelease::Close)+ .await;+ log("session C: ended; socket closed");+ }}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rsindex 5599276b79..c4e14caa41 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/engine.rs@@ -37,7 +37,7 @@ use super::binding::{cardinality_exact_candidate, correlate, selected_tab_target_id, BindingOutcome,CdpWindowCandidate,};-use super::cdp_ws::{CdpConnection, CdpPool};+use super::cdp_ws::{CdpConnection, CdpPool, SharedSocketRelease};use super::grant::{ExistingProfileGrant, ExistingProfileGrants, GrantLookup};use super::mutation::{MutationGates, MutationKey};use super::platform::{@@ -699,7 +699,6 @@ impl BrowserEngine {let mut pending = engine.pending_existing_profile_cleanups.lock().unwrap();let mut requests = pending.remove(session_id).unwrap_or_default();for grant in engine.existing_profile_grants.remove_session(session_id) {- engine.pool.release_claim_marker(&grant.endpoint_ws_url);if grant.cleanup_remote_debugging {requests.push(ExistingProfileSetupRequest {pid: grant.pid,@@ -713,9 +712,21 @@ impl BrowserEngine {if let Ok(runtime) = tokio::runtime::Handle::try_current() {let engine = engine.clone();runtime.spawn(async move {+ // A normal session end parks the already-consented+ // socket for the next approved session, unless the+ // driver is turning remote debugging back off.+ let mode = if grant.cleanup_remote_debugging {+ SharedSocketRelease::Close+ } else {+ SharedSocketRelease::Park+ };engine.pool- .release_existing(&grant.endpoint_ws_url, grant.generation)+ .release_existing(+ &grant.endpoint_ws_url,+ grant.generation,+ mode,+ ).await;if let Some(protected) = grant.protected_consent.as_ref() {engine.approval_broker.revoke(protected).await;@@ -768,7 +779,6 @@ impl BrowserEngine {GrantLookup::Missing => Ok(None),GrantLookup::Live(grant) => Ok(Some(grant)),GrantLookup::Expired(grant) => {- self.pool.release_claim_marker(&grant.endpoint_ws_url);if grant.cleanup_remote_debugging {let request = ExistingProfileSetupRequest {pid: grant.pid,@@ -789,7 +799,11 @@ impl BrowserEngine {}}self.pool- .release_existing(&grant.endpoint_ws_url, grant.generation)+ .release_existing(+ &grant.endpoint_ws_url,+ grant.generation,+ SharedSocketRelease::Close,+ ).await;if let Some(protected) = grant.protected_consent.as_ref() {self.approval_broker.revoke(protected).await;@@ -812,7 +826,6 @@ impl BrowserEngine {.existing_profile_grants.revoke(session, transport_session, pid){- self.pool.release_claim_marker(&grant.endpoint_ws_url);if grant.cleanup_remote_debugging {let request = ExistingProfileSetupRequest {pid: grant.pid,@@ -833,7 +846,11 @@ impl BrowserEngine {}}self.pool- .release_existing(&grant.endpoint_ws_url, grant.generation)+ .release_existing(+ &grant.endpoint_ws_url,+ grant.generation,+ SharedSocketRelease::Close,+ ).await;if let Some(protected) = grant.protected_consent.as_ref() {self.approval_broker.revoke(protected).await;diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/grant.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/grant.rsindex 98af8fb2c6..7469b0e828 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/grant.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/grant.rs@@ -5,6 +5,7 @@//! grant, connection generation, and reconnect budget.use std::collections::HashMap;+use std::sync::atomic::{AtomicU64, Ordering};use std::sync::Mutex;use std::time::{Duration, Instant};@@ -73,6 +74,11 @@ impl ExistingProfileGrant {#[derive(Default)]pub(crate) struct ExistingProfileGrants {inner: Mutex<HashMap<GrantKey, ExistingProfileGrant>>,+ /// Connection generations are unique across every grant in this engine,+ /// not just per session. Sessions for the same browser share one socket,+ /// so a per-session counter would let one session's generation match,+ /// release, or invalidate another session's claim and targets.+ last_generation: AtomicU64,}impl ExistingProfileGrants {@@ -80,6 +86,10 @@ impl ExistingProfileGrants {Self::default()}+ fn next_generation(&self) -> u64 {+ self.last_generation.fetch_add(1, Ordering::Relaxed) + 1+ }+fn key(public_session: &str, transport_session: Option<&str>, pid: i64) -> GrantKey {GrantKey {public_session: public_session.to_owned(),@@ -106,12 +116,7 @@ impl ExistingProfileGrants {) -> ExistingProfileGrant {let now = Instant::now();let key = Self::key(public_session, transport_session, pid);- let generation = self- .inner- .lock()- .unwrap()- .get(&key)- .map_or(1, |grant| grant.generation.saturating_add(1));+ let generation = self.next_generation();let grant = ExistingProfileGrant {public_session: public_session.to_owned(),transport_session: transport_session.unwrap_or(public_session).to_owned(),@@ -209,7 +214,7 @@ impl ExistingProfileGrants {));}grant.reconnect_attempts_remaining -= 1;- grant.generation = grant.generation.saturating_add(1);+ grant.generation = self.next_generation();grant.last_used_at = Instant::now();Ok(grant.generation)}@@ -415,4 +420,33 @@ mod tests {};assert!(!reused_process.cleanup_remote_debugging);}++ #[test]+ fn generations_are_unique_across_sessions_for_the_same_browser() {+ let grants = ExistingProfileGrants::new();+ let mint = |session: &str| {+ grants+ .mint(+ session,+ None,+ 42,+ 9,+ fingerprint(42),+ "chromium".to_owned(),+ BrowserProduct::GoogleChrome,+ "ws://127.0.0.1:1/devtools/browser/x".to_owned(),+ false,+ None,+ )+ .generation+ };+ let a = mint("session-a");+ let b = mint("session-b");+ assert_ne!(a, b, "sessions sharing one socket need distinct holders");+ let bumped = grants.bump_generation("session-a", None, 42).unwrap();+ assert!(+ bumped > b,+ "a reconnect generation never collides with another session"+ );+ }}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/mock_cdp.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/mock_cdp.rsindex bdd3a39f6a..404ddd2a30 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/mock_cdp.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/mock_cdp.rs@@ -67,6 +67,9 @@ pub(crate) type MockHandler = Arc<dyn Fn(&MockCall) -> MockReply + Send + Sync>;/// A running mock endpoint. Dropping it aborts the accept loop.pub(crate) struct MockCdpServer {addr: SocketAddr,+ /// Completed WebSocket handshakes: each one is a browser-level+ /// connection a real browser would ask the person to approve.+ accepted: Arc<std::sync::atomic::AtomicUsize>,accept_task: tokio::task::JoinHandle<()>,}@@ -76,16 +79,20 @@ impl MockCdpServer {.await.expect("bind loopback");let addr = listener.local_addr().expect("local addr");+ let accepted = Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let accepted_count = accepted.clone();let accept_task = tokio::spawn(async move {loop {let Ok((stream, _)) = listener.accept().await else {break;};let handler = handler.clone();+ let accepted_count = accepted_count.clone();tokio::spawn(async move {let Ok(mut ws) = tokio_tungstenite::accept_async(stream).await else {return;};+ accepted_count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);while let Some(Ok(msg)) = ws.next().await {let Message::Text(text) = msg else { continue };let Ok(v) = serde_json::from_str::<Value>(&text) else {@@ -133,7 +140,15 @@ impl MockCdpServer {});}});- Self { addr, accept_task }+ Self {+ addr,+ accepted,+ accept_task,+ }+ }++ pub fn accepted_connections(&self) -> usize {+ self.accepted.load(std::sync::atomic::Ordering::SeqCst)}pub fn ws_url(&self) -> String {diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rsindex bff1d430bd..1c5972a826 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs@@ -1306,14 +1306,15 @@ impl BrowserEngine {);if let Some(previous) = previous_grant {self.pool- .release_existing(&previous.endpoint_ws_url, previous.generation)+ .release_existing(+ &previous.endpoint_ws_url,+ previous.generation,+ super::cdp_ws::SharedSocketRelease::Park,+ ).await;if let Some(protected) = previous.protected_consent.as_ref() {self.approval_broker.revoke(protected).await;}- if previous.endpoint_ws_url != endpoint.ws_url {- self.pool.release_claim_marker(&previous.endpoint_ws_url);- }}let (claimed, displayed_consent_prompt) = match claim_with_delayed_consent(self.pool.claim_existing(&endpoint.ws_url, grant.generation),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.rsindex ee333e2915..be1b121829 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@@ -635,7 +635,10 @@ impl BrowserPrepareTool {endpoint, and close the temporary tab. Every visible effect is reported; \ambiguity is refused. Where attaching would bring the browser in front of \the user's app (macOS Chrome shows its own remote-debugging prompt in front \- for every new connection), existing-profile attachment refuses with \+ whenever the driver opens a new browser connection; sessions for the same \+ browser share one approved connection, kept for up to 30 minutes idle and \+ 8 hours in total, so later sessions do not prompt again), existing-profile \+ attachment refuses with \background_unavailable unless delivery_mode is \"foreground\" (the app that \was in front is brought back afterwards) or the browser window is on another \Space than the user's, where it attaches in the background while the driver \diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rsindex 34b8f8ffba..e21df42d35 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/v2_tests.rs@@ -1361,6 +1361,79 @@ async fn approved_existing_profile_tools_stay_within_the_reviewed_cdp_surface()crate::session::fire_session_end(TRANSPORT);}+#[tokio::test]+async fn existing_profile_sessions_share_one_browser_connection_across_session_ends() {+ // Chrome asks the person to approve every new browser-level WebSocket.+ // Sessions for the same browser instance must therefore multiplex over+ // the one approved socket, survive each other's session end, and let a+ // later session reuse the parked socket without a new browser prompt.+ let (f, _provider) = protected_existing_profile_fixture().await;+ let prepare = |session: &'static str, transport: &'static str| {+ let engine = f.engine.clone();+ async move {+ let prepared = BrowserPrepareTool::new(engine)+ .invoke(json!({+ "pid": 1,+ "window_id": 7,+ "session": session,+ "_transport_session_id": transport,+ "strategy": { "kind": "existing_profile" }+ }))+ .await;+ structured(&prepared).clone()+ }+ };+ let state = |session: &'static str, transport: &'static str| {+ let engine = f.engine.clone();+ async move {+ let state = GetBrowserStateTool::new(engine)+ .invoke(json!({+ "pid": 1,+ "window_id": 7,+ "session": session,+ "_transport_session_id": transport+ }))+ .await;+ structured(&state).clone()+ }+ };++ let a = prepare("shared-socket-a", "shared-transport-a").await;+ assert_eq!(a["status"], "ok", "{a}");+ let after_first_attach = f._server.accepted_connections();+ assert!(after_first_attach >= 1);++ let b = prepare("shared-socket-b", "shared-transport-b").await;+ assert_eq!(b["status"], "ok", "{b}");+ assert_eq!(b["side_effects"]["displayed_consent_prompt"], false);+ let a_state = state("shared-socket-a", "shared-transport-a").await;+ assert_eq!(a_state["status"], "ok", "{a_state}");+ let b_state = state("shared-socket-b", "shared-transport-b").await;+ assert_eq!(b_state["status"], "ok", "{b_state}");+ assert_eq!(+ f._server.accepted_connections(),+ after_first_attach,+ "a second session must not open another browser-level socket"+ );++ // Ending A must neither close nor invalidate B's use of the socket.+ crate::session::fire_session_end("shared-transport-a");+ tokio::task::yield_now().await;+ let b_state = state("shared-socket-b", "shared-transport-b").await;+ assert_eq!(b_state["status"], "ok", "{b_state}");++ // After every session ended, the next approved session reuses the+ // parked socket instead of dialing (which would prompt again).+ crate::session::fire_session_end("shared-transport-b");+ tokio::task::yield_now().await;+ let c = prepare("shared-socket-c", "shared-transport-c").await;+ assert_eq!(c["status"], "ok", "{c}");+ let c_state = state("shared-socket-c", "shared-transport-c").await;+ assert_eq!(c_state["status"], "ok", "{c_state}");+ assert_eq!(f._server.accepted_connections(), after_first_attach);+ crate::session::fire_session_end("shared-transport-c");+}+#[tokio::test]async fn protected_provider_accepts_exact_attach_and_session_end_revokes_the_grant() {const PROTECTED_SESSION: &str = "protected-provider-v2";diff --git a/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs b/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rsindex 9fe048bb35..b06386078b 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/sdk_adapter.rs@@ -303,6 +303,9 @@ impl SdkAdapter {cua_driver_core::session::suspend_runtime_scope(&self.runtime_scope);let count = cua_driver_core::session::revoke_sessions_with_prefix(&self.runtime_prefix);self.mark_all_sessions_ended();+ // Revoking everything must not leave an already-approved browser+ // socket parked for a later session.+ cua_driver_core::browser::cdp_ws::close_parked_browser_sockets().await;count}diff --git a/libs/cua-driver/rust/crates/platform-macos/src/browser/platform.rs b/libs/cua-driver/rust/crates/platform-macos/src/browser/platform.rsindex 5a97ce0bd6..219cd56abd 100644--- a/libs/cua-driver/rust/crates/platform-macos/src/browser/platform.rs+++ b/libs/cua-driver/rust/crates/platform-macos/src/browser/platform.rs@@ -905,8 +905,8 @@ impl BrowserPlatform for MacOsBrowserPlatform {// only navigates on real keystrokes.Some("Chrome brings itself to the front to show its \"Allow remote debugging?\" prompt \- for every new DevTools connection, and turning remote debugging on needs Chrome in \- front",+ whenever a new DevTools connection opens (sessions then share that one connection), \+ and turning remote debugging on needs Chrome in front",)}diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.jsonindex 657428edad..d0fdf9321e 100644--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json@@ -2447,7 +2447,7 @@"read_only": true},{- "description": "Attach the browser tools to a browser. For a page in the user's running Chrome, Edge or Brave, call it once with pid, window_id, session and strategy {\"kind\":\"existing_profile\"} when get_browser_state refuses with browser_consent_required or browser_requires_setup; then call get_browser_state again and act with browser_click, browser_type or browser_pointer. It attaches, or refuses with nothing changed and says why. Explicitly prepare an owned DevTools endpoint for a browser. pid is required for an existing process or existing-profile attachment, and optional only for allow_launch=true with an isolated profile. Existing endpoints are detected without side effects. Acting setup for an isolated profile follows the runtime permission mode and optional capability manifest. It requires allow_launch=true, launches a separate browser, and never copies, modifies, or terminates the requested user profile. Without pid, only a platform-attested system Chrome/Edge installation (or a root-owned package payload on Linux) is eligible; redirects and user-controlled locations fail closed. Existing-profile attachment is explicit and follows the runtime's immutable permission mode: standard requires an explicit --grant existing-profile launch grant or an embedding authorization host, bounded requires a launch-approved exact resource manifest, and unrestricted requires explicit trusted startup risk acceptance. Ordinary MCP transport approval never proves profile authorization. On proven platforms, an authorized request also permits one bounded exact-window setup: open the recognized browser product's fixed remote-debugging page, toggle its uniquely matched per-instance checkbox, prove the PID-owned loopback endpoint, and close the temporary tab. Every visible effect is reported; ambiguity is refused. Where attaching would bring the browser in front of the user's app (macOS Chrome shows its own remote-debugging prompt in front for every new connection), existing-profile attachment refuses with background_unavailable unless delivery_mode is \"foreground\" (the app that was in front is brought back afterwards) or the browser window is on another Space than the user's, where it attaches in the background while the driver reverts the browser's own brief activations.",+ "description": "Attach the browser tools to a browser. For a page in the user's running Chrome, Edge or Brave, call it once with pid, window_id, session and strategy {\"kind\":\"existing_profile\"} when get_browser_state refuses with browser_consent_required or browser_requires_setup; then call get_browser_state again and act with browser_click, browser_type or browser_pointer. It attaches, or refuses with nothing changed and says why. Explicitly prepare an owned DevTools endpoint for a browser. pid is required for an existing process or existing-profile attachment, and optional only for allow_launch=true with an isolated profile. Existing endpoints are detected without side effects. Acting setup for an isolated profile follows the runtime permission mode and optional capability manifest. It requires allow_launch=true, launches a separate browser, and never copies, modifies, or terminates the requested user profile. Without pid, only a platform-attested system Chrome/Edge installation (or a root-owned package payload on Linux) is eligible; redirects and user-controlled locations fail closed. Existing-profile attachment is explicit and follows the runtime's immutable permission mode: standard requires an explicit --grant existing-profile launch grant or an embedding authorization host, bounded requires a launch-approved exact resource manifest, and unrestricted requires explicit trusted startup risk acceptance. Ordinary MCP transport approval never proves profile authorization. On proven platforms, an authorized request also permits one bounded exact-window setup: open the recognized browser product's fixed remote-debugging page, toggle its uniquely matched per-instance checkbox, prove the PID-owned loopback endpoint, and close the temporary tab. Every visible effect is reported; ambiguity is refused. Where attaching would bring the browser in front of the user's app (macOS Chrome shows its own remote-debugging prompt in front whenever the driver opens a new browser connection; sessions for the same browser share one approved connection, kept for up to 30 minutes idle and 8 hours in total, so later sessions do not prompt again), existing-profile attachment refuses with background_unavailable unless delivery_mode is \"foreground\" (the app that was in front is brought back afterwards) or the browser window is on another Space than the user's, where it attaches in the background while the driver reverts the browser's own brief activations.","destructive": true,"idempotent": false,"input_schema": {diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.jsonindex 7acbb7af4f..c0c6ebe9a5 100644--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json@@ -2094,7 +2094,7 @@"read_only": true},{- "description": "Attach the browser tools to a browser. For a page in the user's running Chrome, Edge or Brave, call it once with pid, window_id, session and strategy {\"kind\":\"existing_profile\"} when get_browser_state refuses with browser_consent_required or browser_requires_setup; then call get_browser_state again and act with browser_click, browser_type or browser_pointer. It attaches, or refuses with nothing changed and says why. Explicitly prepare an owned DevTools endpoint for a browser. pid is required for an existing process or existing-profile attachment, and optional only for allow_launch=true with an isolated profile. Existing endpoints are detected without side effects. Acting setup for an isolated profile follows the runtime permission mode and optional capability manifest. It requires allow_launch=true, launches a separate browser, and never copies, modifies, or terminates the requested user profile. Without pid, only a platform-attested system Chrome/Edge installation (or a root-owned package payload on Linux) is eligible; redirects and user-controlled locations fail closed. Existing-profile attachment is explicit and follows the runtime's immutable permission mode: standard requires an explicit --grant existing-profile launch grant or an embedding authorization host, bounded requires a launch-approved exact resource manifest, and unrestricted requires explicit trusted startup risk acceptance. Ordinary MCP transport approval never proves profile authorization. On proven platforms, an authorized request also permits one bounded exact-window setup: open the recognized browser product's fixed remote-debugging page, toggle its uniquely matched per-instance checkbox, prove the PID-owned loopback endpoint, and close the temporary tab. Every visible effect is reported; ambiguity is refused. Where attaching would bring the browser in front of the user's app (macOS Chrome shows its own remote-debugging prompt in front for every new connection), existing-profile attachment refuses with background_unavailable unless delivery_mode is \"foreground\" (the app that was in front is brought back afterwards) or the browser window is on another Space than the user's, where it attaches in the background while the driver reverts the browser's own brief activations.",+ "description": "Attach the browser tools to a browser. For a page in the user's running Chrome, Edge or Brave, call it once with pid, window_id, session and strategy {\"kind\":\"existing_profile\"} when get_browser_state refuses with browser_consent_required or browser_requires_setup; then call get_browser_state again and act with browser_click, browser_type or browser_pointer. It attaches, or refuses with nothing changed and says why. Explicitly prepare an owned DevTools endpoint for a browser. pid is required for an existing process or existing-profile attachment, and optional only for allow_launch=true with an isolated profile. Existing endpoints are detected without side effects. Acting setup for an isolated profile follows the runtime permission mode and optional capability manifest. It requires allow_launch=true, launches a separate browser, and never copies, modifies, or terminates the requested user profile. Without pid, only a platform-attested system Chrome/Edge installation (or a root-owned package payload on Linux) is eligible; redirects and user-controlled locations fail closed. Existing-profile attachment is explicit and follows the runtime's immutable permission mode: standard requires an explicit --grant existing-profile launch grant or an embedding authorization host, bounded requires a launch-approved exact resource manifest, and unrestricted requires explicit trusted startup risk acceptance. Ordinary MCP transport approval never proves profile authorization. On proven platforms, an authorized request also permits one bounded exact-window setup: open the recognized browser product's fixed remote-debugging page, toggle its uniquely matched per-instance checkbox, prove the PID-owned loopback endpoint, and close the temporary tab. Every visible effect is reported; ambiguity is refused. Where attaching would bring the browser in front of the user's app (macOS Chrome shows its own remote-debugging prompt in front whenever the driver opens a new browser connection; sessions for the same browser share one approved connection, kept for up to 30 minutes idle and 8 hours in total, so later sessions do not prompt again), existing-profile attachment refuses with background_unavailable unless delivery_mode is \"foreground\" (the app that was in front is brought back afterwards) or the browser window is on another Space than the user's, where it attaches in the background while the driver reverts the browser's own brief activations.","destructive": true,"idempotent": false,"input_schema": {diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.jsonindex 927cf82609..2b0b9407d0 100644--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json@@ -2142,7 +2142,7 @@"read_only": true},{- "description": "Attach the browser tools to a browser. For a page in the user's running Chrome, Edge or Brave, call it once with pid, window_id, session and strategy {\"kind\":\"existing_profile\"} when get_browser_state refuses with browser_consent_required or browser_requires_setup; then call get_browser_state again and act with browser_click, browser_type or browser_pointer. It attaches, or refuses with nothing changed and says why. Explicitly prepare an owned DevTools endpoint for a browser. pid is required for an existing process or existing-profile attachment, and optional only for allow_launch=true with an isolated profile. Existing endpoints are detected without side effects. Acting setup for an isolated profile follows the runtime permission mode and optional capability manifest. It requires allow_launch=true, launches a separate browser, and never copies, modifies, or terminates the requested user profile. Without pid, only a platform-attested system Chrome/Edge installation (or a root-owned package payload on Linux) is eligible; redirects and user-controlled locations fail closed. Existing-profile attachment is explicit and follows the runtime's immutable permission mode: standard requires an explicit --grant existing-profile launch grant or an embedding authorization host, bounded requires a launch-approved exact resource manifest, and unrestricted requires explicit trusted startup risk acceptance. Ordinary MCP transport approval never proves profile authorization. On proven platforms, an authorized request also permits one bounded exact-window setup: open the recognized browser product's fixed remote-debugging page, toggle its uniquely matched per-instance checkbox, prove the PID-owned loopback endpoint, and close the temporary tab. Every visible effect is reported; ambiguity is refused. Where attaching would bring the browser in front of the user's app (macOS Chrome shows its own remote-debugging prompt in front for every new connection), existing-profile attachment refuses with background_unavailable unless delivery_mode is \"foreground\" (the app that was in front is brought back afterwards) or the browser window is on another Space than the user's, where it attaches in the background while the driver reverts the browser's own brief activations.",+ "description": "Attach the browser tools to a browser. For a page in the user's running Chrome, Edge or Brave, call it once with pid, window_id, session and strategy {\"kind\":\"existing_profile\"} when get_browser_state refuses with browser_consent_required or browser_requires_setup; then call get_browser_state again and act with browser_click, browser_type or browser_pointer. It attaches, or refuses with nothing changed and says why. Explicitly prepare an owned DevTools endpoint for a browser. pid is required for an existing process or existing-profile attachment, and optional only for allow_launch=true with an isolated profile. Existing endpoints are detected without side effects. Acting setup for an isolated profile follows the runtime permission mode and optional capability manifest. It requires allow_launch=true, launches a separate browser, and never copies, modifies, or terminates the requested user profile. Without pid, only a platform-attested system Chrome/Edge installation (or a root-owned package payload on Linux) is eligible; redirects and user-controlled locations fail closed. Existing-profile attachment is explicit and follows the runtime's immutable permission mode: standard requires an explicit --grant existing-profile launch grant or an embedding authorization host, bounded requires a launch-approved exact resource manifest, and unrestricted requires explicit trusted startup risk acceptance. Ordinary MCP transport approval never proves profile authorization. On proven platforms, an authorized request also permits one bounded exact-window setup: open the recognized browser product's fixed remote-debugging page, toggle its uniquely matched per-instance checkbox, prove the PID-owned loopback endpoint, and close the temporary tab. Every visible effect is reported; ambiguity is refused. Where attaching would bring the browser in front of the user's app (macOS Chrome shows its own remote-debugging prompt in front whenever the driver opens a new browser connection; sessions for the same browser share one approved connection, kept for up to 30 minutes idle and 8 hours in total, so later sessions do not prompt again), existing-profile attachment refuses with background_unavailable unless delivery_mode is \"foreground\" (the app that was in front is brought back afterwards) or the browser window is on another Space than the user's, where it attaches in the background while the driver reverts the browser's own brief activations.","destructive": true,"idempotent": false,"input_schema": {