Skip to content

The headless browser for AI agents and web scraping

fix(cdp): preserve evaluation handles across tab switches

SGavrl4227c632a1b6
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rs
index 3658ee5e..6fab89a2 100644
--- a/crates/obscura-browser/src/page.rs
+++ b/crates/obscura-browser/src/page.rs
@@ -292,6 +292,10 @@ pub struct Page {
/// is suspended for CDP/MCP tab switching. These are restored only when
/// the same surviving DomTree is resumed; navigation clears them.
suspended_started_script_ids: Vec<u32>,
+ /// Re-creatable CDP handles retained while tab switching replaces this
+ /// page's V8 runtime. Chromium keeps these handles alive with the target;
+ /// preserving them avoids order-dependent failures in concurrent clients.
+ suspended_cdp_object_state: obscura_js::runtime::CdpObjectState,
/// Passive on_request/on_response callbacks, scoped to this page (issue
/// #408): they fire only for requests this page drives and die with it.
/// Arc because the JS runtime state holds a second handle for fetch()/XHR.
@@ -1134,6 +1138,7 @@ impl Page {
preload_scripts: Vec::new(),
runtime_events_enabled: std::cell::Cell::new(false),
suspended_started_script_ids: Vec::new(),
+ suspended_cdp_object_state: obscura_js::runtime::CdpObjectState::default(),
callbacks: Arc::new(CallbackRegistry::new()),
#[cfg(feature = "stealth")]
stealth_client,
@@ -1611,6 +1616,7 @@ impl Page {
// same DomTree is installed; a navigation must never inherit IDs from
// a suspended prior document whose allocator may reuse them.
self.suspended_started_script_ids.clear();
+ self.suspended_cdp_object_state = obscura_js::runtime::CdpObjectState::default();
// Drop any existing runtime so the JS realm starts clean on
// every navigation. The old code reused the V8 isolate and
// only re-bound `globalThis.document`, leaving window.onload,
@@ -4188,10 +4194,11 @@ impl Page {
}
pub fn suspend_js(&mut self) {
- let Some(js) = &self.js else {
+ let Some(js) = &mut self.js else {
return;
};
let started_script_ids = js.started_script_ids();
+ self.suspended_cdp_object_state = js.take_cdp_object_state();
let dom = js.take_dom();
if let Some(dom) = dom {
self.dom = Some(dom);
@@ -4213,9 +4220,11 @@ impl Page {
return;
}
let started_script_ids = std::mem::take(&mut self.suspended_started_script_ids);
+ let cdp_object_state = std::mem::take(&mut self.suspended_cdp_object_state);
self.init_js();
- if let Some(js) = &self.js {
+ if let Some(js) = &mut self.js {
js.restore_started_script_ids(&started_script_ids);
+ js.restore_cdp_object_state(cdp_object_state);
}
}
@@ -5623,6 +5632,44 @@ mod tests {
assert_eq!(after, serde_json::json!(["1", "1", "0"]));
}
+ #[tokio::test(flavor = "current_thread")]
+ async fn suspend_resume_preserves_cdp_evaluation_handles() {
+ let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
+ "cdp-handle-suspend".to_string(),
+ None,
+ false,
+ None,
+ None,
+ true,
+ ));
+ let mut page = super::Page::new("cdp-handle-suspend".to_string(), context);
+ page.url = Some(url::Url::parse("http://example.com/").unwrap());
+ page.dom = Some(parse_html("<html><body></body></html>"));
+ page.init_js();
+
+ let object = page
+ .evaluate_for_cdp_with_timeout("({ increment(value) { return value + 1; } })", false, false, 1_000)
+ .await
+ .unwrap();
+ let object_id = object.object_id.expect("remote evaluation returned no handle");
+
+ page.suspend_js();
+ page.resume_js();
+
+ let result = page
+ .call_function_on_for_cdp_with_timeout(
+ "function(value) { return this.increment(value); }",
+ Some(&object_id),
+ &[serde_json::json!({ "value": 41 })],
+ true,
+ false,
+ 1_000,
+ )
+ .await
+ .unwrap();
+ assert_eq!(result.value, Some(serde_json::json!(42.0)));
+ }
+
#[test]
fn new_document_does_not_inherit_suspended_script_ids() {
let context = std::sync::Arc::new(crate::BrowserContext::with_storage_and_network(
diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rs
index 2bd9a0bd..1e444099 100644
--- a/crates/obscura-js/src/runtime.rs
+++ b/crates/obscura-js/src/runtime.rs
@@ -130,10 +130,25 @@ pub struct RemoteObjectInfo {
pub value: Option<serde_json::Value>,
}
+/// CDP remote objects that can be rebuilt when a page's V8 runtime is
+/// temporarily replaced during tab switching.
+///
+/// Obscura currently keeps one entered isolate per connection. Switching tabs
+/// therefore rebuilds the target page's runtime, but CDP clients reasonably
+/// expect handles returned by `Runtime.evaluate` to remain usable. Retaining
+/// the originating expressions lets the page restore a handle on demand under
+/// the same id without retaining a second isolate.
+#[derive(Default)]
+pub struct CdpObjectState {
+ object_counter: u64,
+ evaluation_recipes: HashMap<String, String>,
+}
+
pub struct ObscuraJsRuntime {
runtime: JsRuntime,
state: Rc<RefCell<ObscuraState>>,
object_store: HashMap<String, String>,
+ evaluation_recipes: HashMap<String, String>,
object_counter: u64,
import_map: Rc<RefCell<ImportMap>>,
/// Loader-owned signal for pending dynamic-import graph fetches. This is
@@ -376,6 +391,7 @@ impl ObscuraJsRuntime {
runtime,
state,
object_store: HashMap::new(),
+ evaluation_recipes: HashMap::new(),
object_counter: 0,
import_map,
module_load_activity,
@@ -1753,6 +1769,10 @@ impl ObscuraJsRuntime {
oid.clone(),
format!("globalThis.__obscura_objects['{}']", oid),
);
+ if !return_by_value {
+ self.evaluation_recipes
+ .insert(oid.clone(), cleaned_expr.to_string());
+ }
if await_promise && return_by_value {
let read = self
@@ -2015,6 +2035,7 @@ impl ObscuraJsRuntime {
}
pub fn release_object(&mut self, object_id: &str) {
+ self.evaluation_recipes.remove(object_id);
if self.object_store.remove(object_id).is_some() {
let frame_id = object_id
.strip_prefix("console-")
@@ -2051,6 +2072,19 @@ impl ObscuraJsRuntime {
}
let _ = self.execute_runtime_script("<releaseGroup>", code);
self.object_store.clear();
+ self.evaluation_recipes.clear();
+ }
+
+ pub fn take_cdp_object_state(&mut self) -> CdpObjectState {
+ CdpObjectState {
+ object_counter: self.object_counter,
+ evaluation_recipes: std::mem::take(&mut self.evaluation_recipes),
+ }
+ }
+
+ pub fn restore_cdp_object_state(&mut self, state: CdpObjectState) {
+ self.object_counter = self.object_counter.max(state.object_counter);
+ self.evaluation_recipes = state.evaluation_recipes;
}
pub async fn load_module(&mut self, url: &str, budget_ms: u64) -> Result<(), String> {
let deadline = tokio::time::Instant::now() + tokio::time::Duration::from_millis(budget_ms);
@@ -3132,11 +3166,27 @@ impl ObscuraJsRuntime {
)
}
- fn resolve_this(&self, object_id: Option<&str>) -> String {
+ fn resolve_remote_object(&mut self, object_id: &str) -> Option<String> {
+ if let Some(retrieval) = self.object_store.get(object_id) {
+ return Some(retrieval.clone());
+ }
+ let expression = self.evaluation_recipes.get(object_id)?.clone();
+ let object_id_literal = js_string_literal(object_id);
+ let code = format!(
+ "globalThis.__obscura_objects[{object_id_literal}] = (\n{expression}\n);"
+ );
+ self.execute_runtime_script("<restore-cdp-object>", code).ok()?;
+ let retrieval = format!("globalThis.__obscura_objects[{object_id_literal}]");
+ self.object_store
+ .insert(object_id.to_string(), retrieval.clone());
+ Some(retrieval)
+ }
+
+ fn resolve_this(&mut self, object_id: Option<&str>) -> String {
match object_id {
Some(oid) => {
- if let Some(retrieval) = self.object_store.get(oid) {
- retrieval.clone()
+ if let Some(retrieval) = self.resolve_remote_object(oid) {
+ retrieval
} else if oid.starts_with("node-") {
let nid = oid.strip_prefix("node-").unwrap_or("0");
format!(
@@ -3156,7 +3206,7 @@ impl ObscuraJsRuntime {
}
}
- fn build_args(&self, arguments: &[serde_json::Value]) -> (String, String) {
+ fn build_args(&mut self, arguments: &[serde_json::Value]) -> (String, String) {
let mut setup_lines = Vec::new();
let mut arg_names = Vec::new();
@@ -3167,7 +3217,7 @@ impl ObscuraJsRuntime {
serde_json::to_string(value).unwrap_or_else(|_| "undefined".to_string());
setup_lines.push(format!("var {} = {};", arg_name, json_str));
} else if let Some(oid) = arg.get("objectId").and_then(|v| v.as_str()) {
- if let Some(retrieval) = self.object_store.get(oid) {
+ if let Some(retrieval) = self.resolve_remote_object(oid) {
setup_lines.push(format!("var {} = {};", arg_name, retrieval));
} else {
setup_lines.push(format!("var {} = undefined;", arg_name));