The headless browser for AI agents and web scraping
fix(cdp): scope execution context ownership
Jernej Barbaric76735915c9ca
diff --git a/crates/obscura-cdp/src/dispatch.rs b/crates/obscura-cdp/src/dispatch.rsindex 0007a1ee..fa4c32a9 100644--- a/crates/obscura-cdp/src/dispatch.rs+++ b/crates/obscura-cdp/src/dispatch.rs@@ -37,6 +37,17 @@ pub(crate) struct ScreencastState {pub autonomous_frame_pending: bool,}+#[derive(Clone, Debug)]+pub(crate) struct ExecutionContextRecord {+ pub id: i64,+ pub unique_id: String,+ pub page_id: String,+ pub frame_id: String,+ pub origin: String,+ pub world_name: String,+ pub is_default: bool,+}+pub struct CdpContext {pub pages: Vec<Page>,pub sessions: HashMap<String, String>, // session_id -> page_id@@ -68,18 +79,11 @@ pub struct CdpContext {/// Sessions that called Runtime.enable. Console and exception events are/// page-scoped but only delivered to these subscribers.pub runtime_enabled_sessions: HashSet<String>,- // World names registered via Page.createIsolatedWorld. After every- // navigation Obscura clears execution contexts (via- // Runtime.executionContextsCleared) and must re-emit a- // Runtime.executionContextCreated for each registered world, otherwise- // Playwright/Puppeteer hang waiting for their utility world to come- // back. Stored as plain Strings (not by-page) — for now we only model- // a single page in CdpContext anyway.+ // Legacy direct-embedder configuration. Protocol-created worlds live only+ // in `page_isolated_worlds`, so this vector does not grow with page churn.pub isolated_worlds: Vec<String>,- // Set of executionContextIds Obscura has emitted via- // Runtime.executionContextCreated. Pre-populated with the default-frame- // contexts (`1`, `2`) that Runtime.enable / Page.navigate emit, then- // extended each time Page.createIsolatedWorld assigns a fresh id.+ // Set of allocated executionContextIds. An id is routable for an attached+ // session only when `execution_contexts` also records the owning page.//// Runtime.evaluate / Runtime.callFunctionOn consult this set to reject// requests targeting an unknown context — matching real Chrome's@@ -94,6 +98,10 @@ pub struct CdpContext {// claims and increments from this counter so the ids real Chrome would// emit (incrementing, never reused) are mirrored.pub next_isolated_context_id: i64,+ next_default_context_id: i64,+ execution_contexts: HashMap<i64, ExecutionContextRecord>,+ page_contexts: HashMap<String, Vec<i64>>,+ page_isolated_worlds: HashMap<String, Vec<String>>,pub fetch_intercept: FetchInterceptState,pub intercept_tx: Option<tokio::sync::mpsc::UnboundedSender<InterceptedRequest>>,// Open IO streams for Fetch.takeResponseBodyAsStream. Each holds a response@@ -155,14 +163,7 @@ impl CdpContext {/// context. The server passes a fresh isolated context per WebSocket; tests/// and embedders may construct their own.pub fn new_with_shared_context(default_context: Arc<BrowserContext>) -> Self {- // Pre-seed with the default-frame execution context ids that- // `Runtime.enable` (1) and post-navigation re-emission (2) advertise via- // Runtime.executionContextCreated. Anything else has to be registered- // explicitly (Page.createIsolatedWorld), otherwise- // Runtime.{evaluate,callFunctionOn} should reject it per CDP spec.- let mut valid_context_ids = HashSet::new();- valid_context_ids.insert(1);- valid_context_ids.insert(2);+ let valid_context_ids = HashSet::new();CdpContext {pages: Vec::new(),sessions: HashMap::new(),@@ -187,6 +188,10 @@ impl CdpContext {isolated_worlds: Vec::new(),valid_context_ids,next_isolated_context_id: 100,+ next_default_context_id: 1,+ execution_contexts: HashMap::new(),+ page_contexts: HashMap::new(),+ page_isolated_worlds: HashMap::new(),io_streams: crate::domains::io::IoStreamStore::default(),v8_lock: Arc::new(tokio::sync::Mutex::new(())),}@@ -215,8 +220,15 @@ impl CdpContext {/// Claim the next isolated-world execution context id and register it as/// valid for `Runtime.evaluate`/`callFunctionOn`. Issue #192.pub fn next_isolated_context(&mut self) -> i64 {+ while self.valid_context_ids.contains(&self.next_isolated_context_id)+ || self.execution_contexts.contains_key(&self.next_isolated_context_id)+ {+ self.next_isolated_context_id = self.next_isolated_context_id.checked_add(1)+ .expect("execution context id space exhausted");+ }let id = self.next_isolated_context_id;- self.next_isolated_context_id += 1;+ self.next_isolated_context_id = id.checked_add(1)+ .expect("execution context id space exhausted");self.valid_context_ids.insert(id);id}@@ -328,9 +340,162 @@ impl CdpContext {for session_id in &removed_sessions {self.runtime_enabled_sessions.remove(session_id);}+ if let Some(context_ids) = self.page_contexts.remove(id) {+ for context_id in context_ids {+ self.execution_contexts.remove(&context_id);+ self.valid_context_ids.remove(&context_id);+ }+ }+ self.page_isolated_worlds.remove(id);self.sessions.retain(|_, v| v != id);}+ fn allocate_context(+ &mut self,+ page_id: &str,+ frame_id: &str,+ origin: &str,+ world_name: &str,+ is_default: bool,+ ) -> ExecutionContextRecord {+ while self.valid_context_ids.contains(&self.next_default_context_id)+ || self.execution_contexts.contains_key(&self.next_default_context_id)+ {+ self.next_default_context_id = self.next_default_context_id.checked_add(1)+ .expect("execution context id space exhausted");+ }+ let id = self.next_default_context_id;+ self.next_default_context_id = id.checked_add(1)+ .expect("execution context id space exhausted");+ let context = ExecutionContextRecord {+ id,+ unique_id: format!("obscura-context-{}", uuid::Uuid::new_v4()),+ page_id: page_id.to_string(),+ frame_id: frame_id.to_string(),+ origin: origin.to_string(),+ world_name: world_name.to_string(),+ is_default,+ };+ self.valid_context_ids.insert(id);+ self.execution_contexts.insert(id, context.clone());+ self.page_contexts.entry(page_id.to_string()).or_default().push(id);+ context+ }++ pub(crate) fn ensure_default_context(&mut self, page_id: &str) -> Option<ExecutionContextRecord> {+ if let Some(context) = self.contexts_for_page(page_id).into_iter().find(|context| context.is_default) {+ return Some(context.clone());+ }+ let page = self.get_page(page_id)?;+ let frame_id = page.frame_id.clone();+ let origin = page.url_string();+ Some(self.allocate_context(page_id, &frame_id, &origin, "", true))+ }++ /// The single hook for an installed replacement Document.+ pub(crate) fn commit_default_context(+ &mut self,+ page_id: &str,+ frame_id: &str,+ origin: &str,+ ) -> Vec<ExecutionContextRecord> {+ if let Some(previous) = self.page_contexts.remove(page_id) {+ for id in previous {+ self.execution_contexts.remove(&id);+ self.valid_context_ids.remove(&id);+ }+ }+ let mut contexts = vec![self.allocate_context(page_id, frame_id, origin, "", true)];+ let mut worlds = self.isolated_worlds.clone();+ if let Some(page_worlds) = self.page_isolated_worlds.get(page_id) {+ for world in page_worlds {+ if !worlds.contains(world) {+ worlds.push(world.clone());+ }+ }+ }+ if worlds.is_empty() {+ worlds.push("__puppeteer_utility_world__24.40.0".to_string());+ }+ for world in worlds {+ contexts.push(self.allocate_context(page_id, frame_id, origin, &world, false));+ }+ contexts+ }++ pub(crate) fn context_by_id(&self, id: i64) -> Option<&ExecutionContextRecord> {+ self.execution_contexts.get(&id)+ }++ pub(crate) fn context_by_unique_id(&self, unique_id: &str) -> Option<&ExecutionContextRecord> {+ self.execution_contexts.values().find(|context| context.unique_id == unique_id)+ }++ pub(crate) fn contexts_for_page(+ &self,+ page_id: &str,+ ) -> impl Iterator<Item = &ExecutionContextRecord> {+ self.page_contexts.get(page_id).into_iter().flatten()+ .filter_map(|id| self.execution_contexts.get(id))+ }++ pub(crate) fn create_isolated_context(+ &mut self,+ page_id: &str,+ frame_id: &str,+ origin: &str,+ world_name: &str,+ persist_across_navigation: bool,+ ) -> (ExecutionContextRecord, bool) {+ if !world_name.is_empty() {+ if let Some(existing) = self.contexts_for_page(page_id).find(|context| {+ !context.is_default && context.frame_id == frame_id && context.world_name == world_name+ }) {+ return (existing.clone(), false);+ }+ if persist_across_navigation {+ let worlds = self.page_isolated_worlds.entry(page_id.to_string()).or_default();+ if !worlds.iter().any(|world| world == world_name) {+ worlds.push(world_name.to_string());+ }+ }+ }+ (self.allocate_context(page_id, frame_id, origin, world_name, false), true)+ }++ pub(crate) fn default_context_id(&self, page_id: &str) -> Option<i64> {+ self.contexts_for_page(page_id)+ .find(|context| context.is_default).map(|context| context.id)+ }++ fn remove_frame_contexts(+ &mut self,+ page_id: &str,+ frame_id: &str,+ ) -> Vec<ExecutionContextRecord> {+ let removed = self.page_contexts.get(page_id).into_iter().flatten()+ .copied()+ .filter(|id| self.execution_contexts.get(id)+ .is_some_and(|context| context.frame_id == frame_id))+ .collect::<Vec<_>>();+ if let Some(contexts) = self.page_contexts.get_mut(page_id) {+ contexts.retain(|id| !removed.contains(id));+ }+ removed.into_iter().filter_map(|id| {+ self.valid_context_ids.remove(&id);+ self.execution_contexts.remove(&id)+ }).collect()+ }++ pub(crate) fn runtime_sessions_for_page(&self, page_id: &str) -> Vec<String> {+ let mut sessions = self.runtime_enabled_sessions.iter()+ .filter(|session| self.sessions.get(*session).is_some_and(|owner| owner == page_id))+ .cloned()+ .collect::<Vec<_>>();+ sessions.sort_unstable();+ sessions+ }+#[cfg(feature = "render")]pub(crate) fn next_screencast_session(&mut self) -> i64 {// Never wrap a delayed acknowledgement onto a replacement stream.@@ -367,6 +532,111 @@ impl CdpContext {}}+#[cfg(test)]+mod context_ownership_tests {+ use super::*;++ #[test]+ fn repeated_page_teardown_does_not_grow_context_maps() {+ let mut ctx = CdpContext::new();+ for cycle in 0..64 {+ let page_id = ctx.create_page();+ let session_id = format!("session-{cycle}");+ ctx.sessions.insert(session_id.clone(), page_id.clone());+ ctx.ensure_default_context(&page_id).unwrap();+ ctx.create_isolated_context(+ &page_id,+ &page_id,+ "about:blank",+ &format!("world-{cycle}"),+ true,+ );+ ctx.remove_page(&page_id);++ assert!(ctx.execution_contexts.is_empty());+ assert!(ctx.page_contexts.is_empty());+ assert!(ctx.page_isolated_worlds.is_empty());+ assert!(ctx.valid_context_ids.is_empty());+ assert!(ctx.runtime_enabled_sessions.is_empty());+ assert!(ctx.sessions.is_empty());+ }+ }++ #[test]+ fn isolated_compatibility_ids_are_not_claimed_as_default_realm_routes() {+ let mut ctx = CdpContext::new();+ let isolated = ctx.next_isolated_context();++ assert!(ctx.valid_context_ids.contains(&isolated));+ assert!(ctx.context_by_id(isolated).is_none());+ }++ #[test]+ fn default_and_isolated_allocators_do_not_collide_past_one_thousand_ids() {+ let mut ctx = CdpContext::new();+ let mut ids = HashSet::new();+ for index in 0..1_200 {+ let id = if index % 2 == 0 {+ ctx.allocate_context("page", "frame", "about:blank", "", true).id+ } else {+ ctx.next_isolated_context()+ };+ assert!(ids.insert(id), "duplicate execution context id {id}");+ }+ assert_eq!(ids.len(), 1_200);+ }++ #[test]+ fn repeated_document_commits_keep_only_live_page_contexts() {+ let mut ctx = CdpContext::new();+ let first = ctx.create_page();+ let second = ctx.create_page();+ ctx.ensure_default_context(&second).unwrap();+ let sibling_id = ctx.default_context_id(&second).unwrap();++ for generation in 0..64 {+ let contexts = ctx.commit_default_context(+ &first,+ &first,+ &format!("https://example.test/{generation}"),+ );+ assert_eq!(contexts.len(), 2);+ assert_eq!(ctx.page_contexts[&first].len(), 2);+ assert_eq!(ctx.execution_contexts.len(), 3);+ assert_eq!(ctx.default_context_id(&second), Some(sibling_id));+ }+ }++ #[test]+ fn detached_frame_contexts_are_pruned_without_touching_siblings() {+ let mut ctx = CdpContext::new();+ let page = ctx.create_page();+ let main = ctx.ensure_default_context(&page).unwrap();+ let child = ctx.create_isolated_context(+ &page,+ "child-frame",+ "https://example.test/child",+ "utility",+ false,+ ).0;+ let sibling = ctx.create_isolated_context(+ &page,+ "sibling-frame",+ "https://example.test/sibling",+ "utility",+ false,+ ).0;++ let removed = ctx.remove_frame_contexts(&page, "child-frame");++ assert_eq!(removed.iter().map(|context| context.id).collect::<Vec<_>>(), vec![child.id]);+ assert!(ctx.context_by_id(child.id).is_none());+ assert!(ctx.context_by_id(main.id).is_some());+ assert!(ctx.context_by_id(sibling.id).is_some());+ }++}+/// Whether a CDP method can be served WITHOUT acquiring the per-connection V8 lock.////// Methods listed here were audited to confirm they do not transitively@@ -579,6 +849,17 @@ pub async fn dispatch(req: &CdpRequest, ctx: &mut CdpContext) -> CdpResponse {}pub(crate) fn drain_runtime_events(ctx: &mut CdpContext) {+ let mut drained = Vec::new();+ for page in &mut ctx.pages {+ let runtime_events = page.take_pending_runtime_events();+ if !runtime_events.is_empty() {+ drained.push((page.id.clone(), runtime_events));+ }+ }+ if drained.is_empty() {+ return;+ }+let mut page_to_sessions: HashMap<&str, Vec<&str>> = HashMap::new();for session_id in &ctx.runtime_enabled_sessions {if let Some(page_id) = ctx.sessions.get(session_id) {@@ -591,25 +872,12 @@ pub(crate) fn drain_runtime_events(ctx: &mut CdpContext) {for sessions in page_to_sessions.values_mut() {sessions.sort_unstable();}-let mut events = Vec::new();- for page in &mut ctx.pages {- let runtime_events = page.take_pending_runtime_events();- if runtime_events.is_empty() {- continue;- }- let Some(sessions) = page_to_sessions.get(page.id.as_str()) else {+ for (page_id, runtime_events) in drained {+ let Some(sessions) = page_to_sessions.get(page_id.as_str()) else {continue;};- let execution_context_id = if ctx- .current_loader_ids- .get(&page.id)- .is_some_and(|loader_id| loader_id.starts_with("loader-blank-"))- {- 1- } else {- 2- };+ let execution_context_id = ctx.default_context_id(&page_id).unwrap_or(1);for runtime_event in runtime_events {for session_id in sessions {let (method, params) = match &runtime_event {@@ -663,6 +931,17 @@ pub(crate) fn drain_runtime_events(ctx: &mut CdpContext) {// in the queue while V8 is running inside a CDP handler, so there is no// window in which they could pile up without a draining opportunity.pub(crate) fn drain_binding_calls(ctx: &mut CdpContext) {+ let mut drained = Vec::new();+ for page in &mut ctx.pages {+ let calls = page.take_pending_binding_calls();+ if !calls.is_empty() {+ drained.push((page.id.clone(), calls));+ }+ }+ if drained.is_empty() {+ return;+ }+// page_id -> every session on that page. A page commonly has more than one:// Target.createTarget opens a session and the Target.attachToTarget that// follows opens another, so a client that reaches a page the ordinary way@@ -678,18 +957,14 @@ pub(crate) fn drain_binding_calls(ctx: &mut CdpContext) {for sessions in page_to_sessions.values_mut() {sessions.sort_unstable();}-let mut events: Vec<CdpEvent> = Vec::new();- for page in &mut ctx.pages {- let calls = page.take_pending_binding_calls();- if calls.is_empty() {- continue;- }- let Some(page_sessions) = page_to_sessions.get(page.id.as_str()) else {+ for (page_id, calls) in drained {+ let Some(page_sessions) = page_to_sessions.get(page_id.as_str()) else {// No session attached — drop the calls; there is no client to// deliver them to.continue;};+ let execution_context_id = ctx.default_context_id(&page_id).unwrap_or(1);for (name, payload) in calls {// The sessions that asked for this binding, narrowed to the page the// call came from. Falling back to every session of the page keeps a@@ -711,14 +986,10 @@ pub(crate) fn drain_binding_calls(ctx: &mut CdpContext) {for session_id in targets {events.push(CdpEvent {method: "Runtime.bindingCalled".into(),- // Use executionContextId=2: the default main-frame context- // emitted post-navigation (see domains/page.rs phase1).- // Puppeteer matches on session_id + binding name and- // tolerates any registered context id.params: json!({"name": name,"payload": payload,- "executionContextId": 2,+ "executionContextId": execution_context_id,}),session_id: Some(session_id.to_string()),});@@ -756,6 +1027,7 @@ pub(crate) fn drain_frame_events(ctx: &mut CdpContext) {let mut events: Vec<CdpEvent> = Vec::new();let mut announced: HashMap<String, Vec<String>> = HashMap::new();+ let mut detached = Vec::new();for page in &ctx.pages {let Some(session_ids) = page_to_sessions.get(&page.id) else {continue;@@ -802,18 +1074,35 @@ pub(crate) fn drain_frame_events(ctx: &mut CdpContext) {if let Some(known) = known {for id in known {if !live_ids.contains(id) {- for session_id in session_ids {- events.push(CdpEvent {- method: "Page.frameDetached".into(),- params: json!({ "frameId": id, "reason": "remove" }),- session_id: Some(session_id.clone()),- });- }+ detached.push((page.id.clone(), id.clone(), session_ids.clone()));}}}announced.insert(page.id.clone(), live_ids);}+ for (page_id, frame_id, page_sessions) in detached {+ let removed = ctx.remove_frame_contexts(&page_id, &frame_id);+ let runtime_sessions = ctx.runtime_sessions_for_page(&page_id);+ for context in removed {+ for session_id in &runtime_sessions {+ events.push(CdpEvent::with_session(+ "Runtime.executionContextDestroyed",+ json!({+ "executionContextId": context.id,+ "executionContextUniqueId": context.unique_id,+ }),+ session_id.clone(),+ ));+ }+ }+ for session_id in page_sessions {+ events.push(CdpEvent {+ method: "Page.frameDetached".into(),+ params: json!({ "frameId": frame_id, "reason": "remove" }),+ session_id: Some(session_id),+ });+ }+ }ctx.announced_frames.extend(announced);ctx.pending_events.extend(events);}diff --git a/crates/obscura-cdp/src/domains/page.rs b/crates/obscura-cdp/src/domains/page.rsindex 7fd05791..5f3082cb 100644--- a/crates/obscura-cdp/src/domains/page.rs+++ b/crates/obscura-cdp/src/domains/page.rs@@ -906,51 +906,32 @@ pub fn emit_navigation_events(});}- // executionContextsCleared invalidates every prior context id, so a- // Runtime.evaluate / callFunctionOn targeting a pre-navigation context- // must be rejected (Chrome: "Cannot find context with specified id"). The- // default world (id 2) and isolated worlds are re-registered below as their- // executionContextCreated events are emitted. Issue #407: previously this- // set was insert-only, so stale ids kept validating and grew unbounded.- ctx.valid_context_ids.clear();- let mut phase1 = vec![- CdpEvent {- method: "Page.lifecycleEvent".into(),- params: json!({"frameId": frame_id, "loaderId": loader_id, "name": "init", "timestamp": ts}),- session_id: es.clone(),- },- CdpEvent {- method: "Runtime.executionContextsCleared".into(),- params: json!({}),- session_id: es.clone(),- },- CdpEvent {- method: "Page.frameNavigated".into(),- params: json!({"frame": frame_value(frame_id, None, loader_id, page_url, &nav_mime), "type": "Navigation"}),- session_id: es.clone(),- },- CdpEvent {- method: "Runtime.executionContextCreated".into(),- params: json!({"context": {"id": 2, "origin": page_url, "name": "", "uniqueId": format!("ctx-nav-{}", page_id), "auxData": {"isDefault": true, "type": "default", "frameId": frame_id}}}),- session_id: es.clone(),- },- ];- // The default world is re-created as context id 2; re-register it. Isolated- // worlds register themselves via next_isolated_context in the loop below.- ctx.valid_context_ids.insert(2);- let world_names: Vec<String> = if ctx.isolated_worlds.is_empty() {- vec!["__puppeteer_utility_world__24.40.0".to_string()]- } else {- ctx.isolated_worlds.clone()- };- // Issue #192: fresh, monotonically increasing executionContextId per re-create.- for world_name in &world_names {- let world_ctx_id = ctx.next_isolated_context();- phase1.push(CdpEvent {- method: "Runtime.executionContextCreated".into(),- params: json!({"context": {"id": world_ctx_id, "origin": page_url, "name": world_name, "uniqueId": format!("ctx-isolated-nav-{}-{}", page_id, world_ctx_id), "auxData": {"isDefault": false, "type": "isolated", "frameId": frame_id}}}),- session_id: es.clone(),- });+ let contexts = ctx.commit_default_context(page_id, frame_id, page_url);+ let runtime_sessions = ctx.runtime_sessions_for_page(page_id);+ let mut phase1 = vec![CdpEvent {+ method: "Page.lifecycleEvent".into(),+ params: json!({"frameId": frame_id, "loaderId": loader_id, "name": "init", "timestamp": ts}),+ session_id: es.clone(),+ }];+ for runtime_session in &runtime_sessions {+ phase1.push(CdpEvent::with_session(+ "Runtime.executionContextsCleared",+ json!({}),+ runtime_session.clone(),+ ));+ }+ phase1.push(CdpEvent {+ method: "Page.frameNavigated".into(),+ params: json!({"frame": frame_value(frame_id, None, loader_id, page_url, &nav_mime), "type": "Navigation"}),+ session_id: es.clone(),+ });+ for runtime_session in runtime_sessions {+ for context in &contexts {+ phase1.push(super::runtime::execution_context_created_event(+ context,+ Some(runtime_session.clone()),+ ));+ }}phase1.push(CdpEvent { method: "Page.lifecycleEvent".into(), params: json!({"frameId": frame_id, "loaderId": loader_id, "name": "commit", "timestamp": ts}), session_id: es.clone() });ctx.pending_events.extend(phase1);@@ -1289,59 +1270,54 @@ pub async fn handle(Ok(json!({ "frameTree": frame_tree(page, &loader_id) }))}"createIsolatedWorld" => {- let (frame_id_param, world_name, page_url, page_id) = {+ let (frame_id_param, world_name, origin, page_id, persist_across_navigation) = {let page = ctx.get_session_page(session_id).ok_or("No page for session")?;- (- params+ let frame_id = params.get("frameId").and_then(|v| v.as_str()).unwrap_or(&page.frame_id)- .to_string(),+ .to_string();+ let (origin, persist) = if frame_id == page.frame_id {+ (page.url_string(), true)+ } else if let Some(frame) = page.frames.iter().find(|frame| {+ child_frame_id(&page.frame_id, frame.frame_id()) == frame_id+ }) {+ (frame.url().to_string(), false)+ } else {+ return Err(format!("No frame with given id found: {frame_id}"));+ };+ (+ frame_id,params.get("worldName").and_then(|v| v.as_str()).unwrap_or("").to_string(),- page.url_string(),+ origin,page.id.clone(),+ persist,)};- // Track this world so Page.navigate can re-emit a context for it- // post-navigation. Without this, Playwright (and Puppeteer)- // hang in any operation that uses the utility world — including- // page.title() — because their utility world is gone after- // Runtime.executionContextsCleared and never re-created.- if !world_name.is_empty() && !ctx.isolated_worlds.contains(&world_name) {- ctx.isolated_worlds.push(world_name.clone());+ ctx.ensure_default_context(&page_id)+ .ok_or("No page for session")?;+ let (context, created) = ctx.create_isolated_context(+ &page_id,+ &frame_id_param,+ &origin,+ &world_name,+ persist_across_navigation,+ );+ if created {+ for runtime_session in ctx.runtime_sessions_for_page(&page_id) {+ ctx.pending_events.push(super::runtime::execution_context_created_event(+ &context, Some(runtime_session),+ ));+ }}- // Issue #192: every isolated world emission gets a fresh id from- // the monotonic counter and is registered as a valid contextId.- // Reusing id 100 across navigations made Playwright's bookkeeping- // diverge (it expected 101 on the second nav) and Runtime.evaluate- // failed with "Cannot find context with specified id: 101".- let context_id = ctx.next_isolated_context();-- ctx.pending_events.push(CdpEvent {- method: "Runtime.executionContextCreated".to_string(),- params: json!({- "context": {- "id": context_id,- "origin": page_url,- "name": world_name,- "uniqueId": format!("ctx-isolated-{}-{}", page_id, context_id),- "auxData": {- "isDefault": false,- "type": "isolated",- "frameId": frame_id_param,- }- }- }),- session_id: session_id.clone(),- });- Ok(json!({ "executionContextId": context_id }))+ Ok(json!({ "executionContextId": context.id }))}"setLifecycleEventsEnabled" => Ok(json!({})),"addScriptToEvaluateOnNewDocument" => {diff --git a/crates/obscura-cdp/src/domains/runtime.rs b/crates/obscura-cdp/src/domains/runtime.rsindex d9165a25..bfb9554b 100644--- a/crates/obscura-cdp/src/domains/runtime.rs+++ b/crates/obscura-cdp/src/domains/runtime.rs@@ -4,6 +4,29 @@ use serde_json::{json, Value};use crate::dispatch::CdpContext;+pub(crate) fn execution_context_created_event(+ context: &crate::dispatch::ExecutionContextRecord,+ session_id: Option<String>,+) -> crate::types::CdpEvent {+ crate::types::CdpEvent {+ method: "Runtime.executionContextCreated".to_string(),+ params: json!({+ "context": {+ "id": context.id,+ "origin": context.origin,+ "name": context.world_name,+ "uniqueId": context.unique_id,+ "auxData": {+ "isDefault": context.is_default,+ "type": if context.is_default { "default" } else { "isolated" },+ "frameId": context.frame_id,+ }+ }+ }),+ session_id,+ }+}+/// Whether a binding name is a plain JS identifier and therefore safe to/// interpolate into the generated shim / teardown scripts. Chromium bindings/// are identifiers; anything else (quotes, brackets, spaces, operators) could@@ -72,36 +95,21 @@ pub async fn handle(// a context appears. Returning "No page" here breaks the standard// puppeteer connect/newPage flow. If there's no session, succeed// silently — the next Target.attachToTarget will set things up.- match ctx.get_session_page(session_id) {- Some(page) => {- let origin = page.url_string();- let page_id = page.id.clone();- let frame_id = page.frame_id.clone();- if let Some(session_id) = session_id {- ctx.runtime_enabled_sessions.insert(session_id.clone());- }- ctx.refresh_runtime_event_collection(&page_id);- let event = crate::types::CdpEvent {- method: "Runtime.executionContextCreated".to_string(),- params: json!({- "context": {- "id": 1,- "origin": origin,- "name": "",- "uniqueId": format!("ctx-{}", page_id),- "auxData": {- "isDefault": true,- "type": "default",- "frameId": frame_id,- }- }- }),- session_id: session_id.clone(),- };- ctx.pending_events.push(event);- }- None => {- // No session attached yet — that's fine. Just ack.+ if let Some(page_id) = session_id.as_ref()+ .and_then(|session| ctx.sessions.get(session)).cloned()+ {+ let newly_enabled = session_id.as_ref().is_some_and(|session| {+ ctx.runtime_enabled_sessions.insert(session.clone())+ });+ ctx.refresh_runtime_event_collection(&page_id);+ ctx.ensure_default_context(&page_id);+ if newly_enabled {+ let events = ctx.contexts_for_page(&page_id)+ .map(|context| execution_context_created_event(+ context, session_id.clone(),+ ))+ .collect::<Vec<_>>();+ ctx.pending_events.extend(events);}}Ok(json!({}))@@ -126,7 +134,7 @@ pub async fn handle(.and_then(|v| v.as_bool()).unwrap_or(false);- validate_context_id(params, "contextId", ctx, "evaluate")?;+ validate_context(params, "contextId", ctx, session_id, "evaluate")?;let await_promise = params.get("awaitPromise")@@ -191,9 +199,9 @@ pub async fn handle(// #51: validate executionContextId the same way Runtime.evaluate// does. CDP names this field `executionContextId` on// callFunctionOn (not `contextId`); a request may omit it when- // `objectId` is supplied — in that case validate_context_id is a+ // `objectId` is supplied — in that case context validation is a// no-op and the default context is used.- validate_context_id(params, "executionContextId", ctx, "callFunctionOn")?;+ validate_context(params, "executionContextId", ctx, session_id, "callFunctionOn")?;// Keep awaitPromise alive for the same command budget as evaluate.// Playwright implements waits with callFunctionOn on some utility@@ -444,31 +452,52 @@ pub async fn handle(}/// Reject `Runtime.{evaluate,callFunctionOn}` calls that target an execution-/// context Obscura has not advertised. Returns `Ok(())` when the parameter is-/// absent (defaulting to the page's default context) or when the id matches-/// one of `ctx.valid_context_ids`. Logs a debug trace on accept for #51.-fn validate_context_id(+/// context Obscura has not advertised for the attached page. An absent identity+/// uses the page's default context. Direct embedders retain the compatibility+/// path for ids reserved through `next_isolated_context`.+fn validate_context(params: &Value,field: &str,ctx: &crate::dispatch::CdpContext,+ session_id: &Option<String>,method: &str,) -> Result<(), String> {- let Some(id) = params.get(field).and_then(|v| v.as_i64()) else {+ let id = params.get(field).and_then(|value| value.as_i64());+ let unique_id = params.get("uniqueContextId").and_then(|value| value.as_str());+ if id.is_some() && unique_id.is_some() {+ return Err(format!(+ "Runtime.{method} cannot specify both {field} and uniqueContextId"+ ));+ }+ if id.is_none() && unique_id.is_none() {return Ok(());- };- if !ctx.valid_context_ids.contains(&id) {+ }+ let record = id.and_then(|id| ctx.context_by_id(id))+ .or_else(|| unique_id.and_then(|id| ctx.context_by_unique_id(id)));+ if let Some(record) = record {+ let owner = session_id.as_ref().and_then(|session| ctx.sessions.get(session));+ if owner == Some(&record.page_id) {+ // This registry currently validates ownership/routing only. A+ // named isolated context still executes in the owning page's+ // current V8 runtime/global; it is not a separate V8 realm yet.+ return Ok(());+ }+ } else if session_id.is_none() && unique_id.is_none()+ && id.is_some_and(|id| ctx.valid_context_ids.contains(&id))+ {+ // Direct embedders can still reserve an id through the existing public+ // next_isolated_context API. Attached sessions require page ownership.+ return Ok(());+ }+ let identity = id.map(|id| id.to_string())+ .or_else(|| unique_id.map(str::to_string))+ .unwrap_or_default();+ if record.is_none() || session_id.is_some() {return Err(format!("Cannot find context with specified id: {}",- id+ identity));}- tracing::debug!(- target: "obscura_cdp::runtime",- "Runtime.{}: {}={} (single-isolate routing)",- method,- field,- id- );Ok(())}@@ -552,25 +581,18 @@ mod tests {}#[tokio::test]- async fn evaluate_accepts_default_context_id_one() {- // Runtime.enable advertises contextId=1 — that must be accepted as- // valid input to evaluate, regardless of whether a page is attached.- // (Without a page we get an Err("No page") AFTER the contextId check,- // which proves validation passed for id=1.)- let mut ctx = CdpContext::new();- let result = handle(- "evaluate",- &json!({ "expression": "1 + 1", "contextId": 1 }),- &mut ctx,- &None,- )- .await;- match result {- Ok(_) => {} // accepted + executed (would happen if a page is attached)- Err(e) => assert!(- !e.contains("Cannot find context"),- "contextId=1 must be accepted, got: {e}"- ),+ async fn evaluate_rejects_unadvertised_compatibility_context_ids() {+ for context_id in [1, 2] {+ let mut ctx = CdpContext::new();+ let error = handle(+ "evaluate",+ &json!({ "expression": "1 + 1", "contextId": context_id }),+ &mut ctx,+ &None,+ )+ .await+ .expect_err("an unadvertised compatibility id must not route");+ assert!(error.contains("Cannot find context"));}}diff --git a/crates/obscura-cdp/src/domains/target.rs b/crates/obscura-cdp/src/domains/target.rsindex 2b9215c6..4fde0ec7 100644--- a/crates/obscura-cdp/src/domains/target.rs+++ b/crates/obscura-cdp/src/domains/target.rs@@ -88,12 +88,20 @@ pub async fn handle(let page_id = ctx.create_page_in_context(context_id)?;let session_id = format!("{}-session", page_id);- if let Some(page) = ctx.get_page_mut(&page_id) {+ let committed_document = if let Some(page) = ctx.get_page_mut(&page_id) {if url == "about:blank" || url.is_empty() {page.navigate_blank();+ None} else {- let _ = page.navigate(url).await;+ page.navigate(url).await.ok().map(|_| {+ (page.frame_id.clone(), page.url_string())+ })}+ } else {+ None+ };+ if let Some((frame_id, origin)) = committed_document {+ ctx.commit_default_context(&page_id, &frame_id, &origin);}ctx.sessions.insert(session_id.clone(), page_id.clone());@@ -207,15 +215,20 @@ pub async fn handle(.get("targetId").and_then(|v| v.as_str()).ok_or("targetId required")?;- let session_id = format!("{}-session", target_id);-- ctx.pending_events.push(CdpEvent::new(- "Target.detachedFromTarget",- json!({- "sessionId": session_id,- "targetId": target_id,- }),- ));+ let mut sessions = ctx.sessions.iter()+ .filter(|(_, page_id)| page_id.as_str() == target_id)+ .map(|(session_id, _)| session_id.clone())+ .collect::<Vec<_>>();+ sessions.sort_unstable();+ for session_id in sessions {+ ctx.pending_events.push(CdpEvent::new(+ "Target.detachedFromTarget",+ json!({+ "sessionId": session_id,+ "targetId": target_id,+ }),+ ));+ }ctx.pending_events.push(CdpEvent::new("Target.targetDestroyed",json!({ "targetId": target_id }),@@ -460,6 +473,41 @@ mod tests {assert!(!ctx.sessions.contains_key(&session_id));}+ #[tokio::test]+ async fn closing_target_detaches_every_actual_page_session() {+ let mut ctx = CdpContext::new();+ let page_id = ctx.create_page();+ let parent_session = Some("browser-session".to_string());+ let first = handle(+ "attachToTarget",+ &json!({"targetId": page_id, "flatten": true}),+ &mut ctx,+ &parent_session,+ ).await.unwrap()["sessionId"].as_str().unwrap().to_string();+ let second = handle(+ "attachToTarget",+ &json!({"targetId": page_id, "flatten": true}),+ &mut ctx,+ &parent_session,+ ).await.unwrap()["sessionId"].as_str().unwrap().to_string();+ ctx.pending_events.clear();++ handle(+ "closeTarget",+ &json!({"targetId": page_id}),+ &mut ctx,+ &None,+ ).await.unwrap();++ let detached = ctx.pending_events.iter()+ .filter(|event| event.method == "Target.detachedFromTarget")+ .map(|event| event.params["sessionId"].as_str().unwrap())+ .collect::<Vec<_>>();+ assert_eq!(detached, vec![first.as_str(), second.as_str()]);+ let fabricated = format!("{page_id}-session");+ assert!(!detached.contains(&fabricated.as_str()));+ }+#[tokio::test]async fn unknown_target_method_still_errors() {let mut ctx = CdpContext::new();diff --git a/crates/obscura-cdp/tests/child_frame_tree.rs b/crates/obscura-cdp/tests/child_frame_tree.rsindex 5214865c..44c69de3 100644--- a/crates/obscura-cdp/tests/child_frame_tree.rs+++ b/crates/obscura-cdp/tests/child_frame_tree.rs@@ -183,3 +183,141 @@ async fn get_frame_tree_reports_nested_child_frames() {.count();assert_eq!(repeats, 0, "the same frame was announced twice");}++#[tokio::test(flavor = "current_thread")]+async fn isolated_worlds_are_owned_by_their_exact_frame() {+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");+ let url = serve().await;+ let mut ctx = CdpContext::new();+ let session = attached_session(&mut ctx).await;++ cdp(&mut ctx, 1, "Page.navigate", json!({"url": url}), &session).await;+ cdp(&mut ctx, 2, "Runtime.evaluate", json!({"expression": "1"}), &session).await;+ let target = ctx.sessions[&session].clone();+ let attached = dispatch(+ &CdpRequest {+ id: 3,+ method: "Target.attachToTarget".to_string(),+ params: json!({"targetId": target, "flatten": true}),+ session_id: None,+ },+ &mut ctx,+ ).await.result.unwrap();+ let second_session = attached["sessionId"].as_str().unwrap().to_string();+ for runtime_session in [&session, &second_session] {+ cdp(&mut ctx, 3, "Runtime.enable", json!({}), runtime_session).await;+ }+ let tree = cdp(&mut ctx, 4, "Page.getFrameTree", json!({}), &session).await;+ let main_id = tree["frameTree"]["frame"]["id"].as_str().unwrap().to_string();+ let child_id = tree["frameTree"]["childFrames"][0]["frame"]["id"]+ .as_str().unwrap().to_string();+ let grandchild_id = tree["frameTree"]["childFrames"][0]["childFrames"][0]["frame"]["id"]+ .as_str().unwrap().to_string();++ let main_world = cdp(+ &mut ctx, 5, "Page.createIsolatedWorld",+ json!({"frameId": main_id.clone(), "worldName": "utility"}), &session,+ ).await["executionContextId"].as_i64().unwrap();+ let child_world = cdp(+ &mut ctx, 6, "Page.createIsolatedWorld",+ json!({"frameId": child_id.clone(), "worldName": "utility"}), &session,+ ).await["executionContextId"].as_i64().unwrap();+ let grandchild_world = cdp(+ &mut ctx, 7, "Page.createIsolatedWorld",+ json!({"frameId": grandchild_id.clone(), "worldName": "utility"}), &session,+ ).await["executionContextId"].as_i64().unwrap();+ assert_ne!(main_world, child_world);+ assert_ne!(child_world, grandchild_world);++ let unknown = dispatch(+ &CdpRequest {+ id: 8,+ method: "Page.createIsolatedWorld".to_string(),+ params: json!({"frameId": "missing-frame", "worldName": "utility"}),+ session_id: Some(session.clone()),+ },+ &mut ctx,+ ).await;+ assert!(unknown.error.unwrap().message.contains("No frame with given id"));++ ctx.pending_events.clear();+ cdp(+ &mut ctx,+ 9,+ "Runtime.evaluate",+ json!({"expression": "document.querySelector('iframe').remove()"}),+ &session,+ ).await;+ for _ in 0..3 {+ ctx.get_session_page_mut(&Some(session.clone()))+ .unwrap()+ .run_autonomous_event_loop_turn()+ .await+ .unwrap();+ }+ cdp(&mut ctx, 10, "Runtime.evaluate", json!({"expression": "1"}), &session).await;++ for (frame_id, context_id) in [+ (&child_id, child_world),+ (&grandchild_id, grandchild_world),+ ] {+ for runtime_session in [&session, &second_session] {+ let destroyed = ctx.pending_events.iter().position(|event| {+ event.method == "Runtime.executionContextDestroyed"+ && event.session_id.as_deref() == Some(runtime_session.as_str())+ && event.params["executionContextId"] == context_id+ }).unwrap_or_else(|| panic!(+ "missing executionContextDestroyed for {frame_id}/{context_id}: {:?}",+ ctx.pending_events.iter().map(|event| (+ event.method.as_str(),+ event.session_id.as_deref(),+ event.params.clone(),+ )).collect::<Vec<_>>(),+ ));+ let detached = ctx.pending_events.iter().position(|event| {+ event.method == "Page.frameDetached"+ && event.session_id.as_deref() == Some(runtime_session.as_str())+ && event.params["frameId"] == frame_id.as_str()+ }).expect("missing frameDetached");+ assert!(destroyed < detached, "context must be destroyed before its frame detaches");+ }+ }++ let main_still_routes = dispatch(+ &CdpRequest {+ id: 11,+ method: "Runtime.evaluate".to_string(),+ params: json!({"expression": "1", "contextId": main_world}),+ session_id: Some(session.clone()),+ },+ &mut ctx,+ ).await;+ assert!(main_still_routes.error.is_none());+ for (id, stale_context) in [(12, child_world), (13, grandchild_world)] {+ let stale = dispatch(+ &CdpRequest {+ id,+ method: "Runtime.evaluate".to_string(),+ params: json!({"expression": "1", "contextId": stale_context}),+ session_id: Some(session.clone()),+ },+ &mut ctx,+ ).await;+ assert!(stale.error.unwrap().message.contains("Cannot find context"));+ }++ ctx.pending_events.clear();+ cdp(+ &mut ctx, 14, "Page.navigate",+ json!({"url": "data:text/html,<p>replacement</p>", "waitUntil": "load"}),+ &session,+ ).await;+ let recreated = ctx.pending_events.iter().filter(|event| {+ event.method == "Runtime.executionContextCreated"+ && event.session_id.as_deref() == Some(session.as_str())+ && event.params["context"]["name"] == "utility"+ }).collect::<Vec<_>>();+ assert_eq!(recreated.len(), 1, "only the main-frame world should persist");+ assert_eq!(recreated[0].params["context"]["auxData"]["frameId"], main_id);++}diff --git a/crates/obscura-cdp/tests/execution_context_ownership.rs b/crates/obscura-cdp/tests/execution_context_ownership.rsnew file mode 100644index 00000000..bfc88a84--- /dev/null+++ b/crates/obscura-cdp/tests/execution_context_ownership.rs@@ -0,0 +1,277 @@+use obscura_cdp::dispatch::{dispatch, CdpContext};+use obscura_cdp::types::CdpRequest;+use serde_json::{json, Value};++async fn cdp(+ ctx: &mut CdpContext,+ id: u64,+ method: &str,+ params: Value,+ session_id: Option<&str>,+) -> obscura_cdp::types::CdpResponse {+ dispatch(&CdpRequest {+ id,+ method: method.to_string(),+ params,+ session_id: session_id.map(str::to_string),+ }, ctx).await+}++async fn create_and_attach(ctx: &mut CdpContext, url: &str, id: u64) -> (String, String) {+ let created = cdp(ctx, id, "Target.createTarget", json!({"url": url}), None).await;+ assert!(created.error.is_none(), "createTarget failed: {:?}", created.error);+ let target = created.result.unwrap()["targetId"].as_str().unwrap().to_string();+ let attached = cdp(+ ctx, id + 1, "Target.attachToTarget",+ json!({"targetId": target, "flatten": true}), None,+ ).await;+ let session = attached.result.unwrap()["sessionId"].as_str().unwrap().to_string();+ (target, session)+}++fn latest_default_context(ctx: &CdpContext, session: &str) -> (i64, String, String) {+ let context = &ctx.pending_events.iter().rev().find(|event| {+ event.method == "Runtime.executionContextCreated"+ && event.session_id.as_deref() == Some(session)+ && event.params["context"]["auxData"]["isDefault"] == true+ }).expect("missing default context").params["context"];+ (+ context["id"].as_i64().unwrap(),+ context["uniqueId"].as_str().unwrap().to_string(),+ context["origin"].as_str().unwrap().to_string(),+ )+}++#[tokio::test(flavor = "current_thread")]+async fn nonblank_create_target_exposes_only_the_committed_document_context() {+ let mut ctx = CdpContext::new();+ let (_, session) = create_and_attach(+ &mut ctx, "data:text/html,<title>committed</title>", 1,+ ).await;+ ctx.pending_events.clear();+ cdp(&mut ctx, 3, "Runtime.enable", json!({}), Some(&session)).await;++ let (id, _, origin) = latest_default_context(&ctx, &session);+ assert_eq!(id, 1);+ assert!(origin.starts_with("data:text/html,"));+ assert!(!ctx.pending_events.iter().any(|event| {+ event.method == "Runtime.executionContextCreated"+ && event.params["context"]["origin"] == "about:blank"+ }));+}++#[tokio::test(flavor = "current_thread")]+async fn default_context_identity_is_page_owned_for_id_and_unique_id() {+ let mut ctx = CdpContext::new();+ let (_, first) = create_and_attach(&mut ctx, "about:blank", 1).await;+ let (_, second) = create_and_attach(&mut ctx, "about:blank", 10).await;+ cdp(&mut ctx, 20, "Runtime.enable", json!({}), Some(&first)).await;+ let (id, unique_id, _) = latest_default_context(&ctx, &first);++ let foreign_id = cdp(+ &mut ctx, 21, "Runtime.evaluate",+ json!({"expression": "1", "contextId": id}), Some(&second),+ ).await;+ assert!(foreign_id.error.unwrap().message.contains("Cannot find context"));+ let foreign_unique = cdp(+ &mut ctx, 22, "Runtime.evaluate",+ json!({"expression": "1", "uniqueContextId": unique_id.clone()}), Some(&second),+ ).await;+ assert!(foreign_unique.error.unwrap().message.contains("Cannot find context"));++ let foreign_call = cdp(+ &mut ctx, 23, "Runtime.callFunctionOn",+ json!({+ "functionDeclaration": "() => 1",+ "executionContextId": id,+ "returnByValue": true,+ }),+ Some(&second),+ ).await;+ assert!(foreign_call.error.unwrap().message.contains("Cannot find context"));++ cdp(+ &mut ctx, 24, "Page.navigate",+ json!({"url": "data:text/html,<p>replacement</p>", "waitUntil": "load"}),+ Some(&first),+ ).await;+ for (request_id, params) in [+ (25, json!({"expression": "1", "uniqueContextId": unique_id})),+ (26, json!({+ "functionDeclaration": "() => 1",+ "executionContextId": id,+ "returnByValue": true,+ })),+ ] {+ let method = if request_id == 25 { "Runtime.evaluate" } else { "Runtime.callFunctionOn" };+ let stale = cdp(&mut ctx, request_id, method, params, Some(&first)).await;+ assert!(stale.error.unwrap().message.contains("Cannot find context"));+ }+}++#[tokio::test(flavor = "current_thread")]+async fn navigating_one_page_preserves_the_other_pages_isolated_context() {+ let mut ctx = CdpContext::new();+ let (_, first) = create_and_attach(&mut ctx, "about:blank", 1).await;+ let (_, second) = create_and_attach(&mut ctx, "about:blank", 10).await;+ for (id, session) in [(20, &first), (21, &second)] {+ cdp(&mut ctx, id, "Runtime.enable", json!({}), Some(session)).await;+ }+ let first_isolated = cdp(+ &mut ctx, 30, "Page.createIsolatedWorld",+ json!({"worldName": "first-utility"}), Some(&first),+ ).await.result.unwrap()["executionContextId"].as_i64().unwrap();+ let second_isolated = cdp(+ &mut ctx, 31, "Page.createIsolatedWorld",+ json!({"worldName": "second-utility"}), Some(&second),+ ).await.result.unwrap()["executionContextId"].as_i64().unwrap();++ cdp(+ &mut ctx, 32, "Page.navigate",+ json!({"url": "data:text/html,<p>first replacement</p>", "waitUntil": "load"}),+ Some(&first),+ ).await;++ let second_still_routes = cdp(+ &mut ctx, 33, "Runtime.evaluate",+ json!({"expression": "1", "contextId": second_isolated}), Some(&second),+ ).await;+ assert!(second_still_routes.error.is_none());+ let first_is_stale = cdp(+ &mut ctx, 34, "Runtime.evaluate",+ json!({"expression": "1", "contextId": first_isolated}), Some(&first),+ ).await;+ assert!(first_is_stale.error.unwrap().message.contains("Cannot find context"));+}++#[tokio::test(flavor = "current_thread")]+async fn attached_isolated_context_ids_share_the_current_page_global_for_now() {+ let mut ctx = CdpContext::new();+ let (_, session) = create_and_attach(&mut ctx, "about:blank", 1).await;+ cdp(+ &mut ctx, 3, "Runtime.evaluate",+ json!({"expression": "globalThis.realmProbe = 'default'"}), Some(&session),+ ).await;+ let isolated = cdp(+ &mut ctx, 4, "Page.createIsolatedWorld",+ json!({"worldName": "bookkeeping-only"}), Some(&session),+ ).await.result.unwrap()["executionContextId"].as_i64().unwrap();+ let isolated_response = cdp(+ &mut ctx, 5, "Runtime.evaluate",+ json!({+ "expression": "(function(){ globalThis.realmProbe += '-isolated'; return globalThis.realmProbe; })()",+ "contextId": isolated,+ "returnByValue": true,+ }),+ Some(&session),+ ).await;+ assert!(isolated_response.error.is_none(), "isolated evaluate failed: {:?}", isolated_response.error);+ let isolated_value = isolated_response.result.unwrap();+ assert_eq!(isolated_value["result"]["value"], "default-isolated");+ let default_value = cdp(+ &mut ctx, 6, "Runtime.evaluate",+ json!({"expression": "globalThis.realmProbe", "returnByValue": true}),+ Some(&session),+ ).await.result.unwrap();+ assert_eq!(default_value["result"]["value"], "default-isolated");+}++#[tokio::test(flavor = "current_thread")]+async fn navigation_context_events_preserve_order_for_every_runtime_attachment() {+ let mut ctx = CdpContext::new();+ let (target, first) = create_and_attach(&mut ctx, "about:blank", 1).await;+ let attached = cdp(+ &mut ctx, 3, "Target.attachToTarget",+ json!({"targetId": target, "flatten": true}), None,+ ).await;+ let second = attached.result.unwrap()["sessionId"].as_str().unwrap().to_string();+ for (id, session) in [(10, &first), (11, &second)] {+ cdp(&mut ctx, id, "Runtime.enable", json!({}), Some(session)).await;+ }+ cdp(+ &mut ctx, 12, "Page.createIsolatedWorld",+ json!({"worldName": "utility"}), Some(&first),+ ).await;+ ctx.pending_events.clear();++ cdp(+ &mut ctx, 13, "Page.navigate",+ json!({"url": "data:text/html,<p>replacement</p>", "waitUntil": "load"}),+ Some(&first),+ ).await;++ let first_methods = ctx.pending_events.iter().filter(|event| {+ event.session_id.as_deref() == Some(first.as_str())+ && (event.method == "Page.lifecycleEvent"+ || event.method == "Page.frameNavigated"+ || event.method.starts_with("Runtime.executionContext"))+ }).map(|event| {+ if event.method == "Page.lifecycleEvent" {+ format!("{}:{}", event.method, event.params["name"].as_str().unwrap_or(""))+ } else {+ event.method.clone()+ }+ }).collect::<Vec<_>>();+ assert_eq!(&first_methods[..4], [+ "Page.lifecycleEvent:init",+ "Runtime.executionContextsCleared",+ "Page.frameNavigated",+ "Runtime.executionContextCreated",+ ]);+ assert_eq!(first_methods.iter().filter(|method| {+ method.as_str() == "Runtime.executionContextCreated"+ }).count(), 2);++ let second_methods = ctx.pending_events.iter().filter(|event| {+ event.session_id.as_deref() == Some(second.as_str())+ && event.method.starts_with("Runtime.executionContext")+ }).map(|event| event.method.as_str()).collect::<Vec<_>>();+ assert_eq!(second_methods, [+ "Runtime.executionContextsCleared",+ "Runtime.executionContextCreated",+ "Runtime.executionContextCreated",+ ]);+}++#[tokio::test(flavor = "current_thread")]+async fn runtime_and_binding_events_use_the_owning_pages_default_context() {+ let mut ctx = CdpContext::new();+ let (_, first) = create_and_attach(&mut ctx, "about:blank", 1).await;+ let (_, second) = create_and_attach(&mut ctx, "about:blank", 10).await;+ for (id, session) in [(20, &first), (21, &second)] {+ cdp(&mut ctx, id, "Runtime.enable", json!({}), Some(session)).await;+ }+ let (first_context, _, _) = latest_default_context(&ctx, &first);+ cdp(+ &mut ctx,+ 22,+ "Runtime.addBinding",+ json!({"name": "probe"}),+ Some(&second),+ ).await;+ ctx.pending_events.clear();++ cdp(+ &mut ctx,+ 23,+ "Page.navigate",+ json!({+ "url": "data:text/html,<script>console.log('owned');probe('bound')</script>",+ "waitUntil": "load",+ }),+ Some(&second),+ ).await;+ let (second_context, _, _) = latest_default_context(&ctx, &second);+ assert_ne!(first_context, second_context);++ let console = ctx.pending_events.iter().find(|event| {+ event.method == "Runtime.consoleAPICalled"+ && event.session_id.as_deref() == Some(second.as_str())+ }).expect("missing console event");+ assert_eq!(console.params["executionContextId"], second_context);+ let binding = ctx.pending_events.iter().find(|event| {+ event.method == "Runtime.bindingCalled"+ && event.session_id.as_deref() == Some(second.as_str())+ }).expect("missing binding event");+ assert_eq!(binding.params["executionContextId"], second_context);+}diff --git a/crates/obscura-cdp/tests/execution_context_pruned_on_navigation.rs b/crates/obscura-cdp/tests/execution_context_pruned_on_navigation.rsindex 8762112f..0e0dea74 100644--- a/crates/obscura-cdp/tests/execution_context_pruned_on_navigation.rs+++ b/crates/obscura-cdp/tests/execution_context_pruned_on_navigation.rs@@ -1,69 +1,56 @@-// Regression for issue #407: `CdpContext.valid_context_ids` was insert-only,-// so `Runtime.executionContextsCleared` on navigation never pruned the old-// context ids. A `Runtime.callFunctionOn` targeting a pre-navigation context-// still ran (Chrome rejects it with "Cannot find context with specified id"),-// and the set grew by one id per navigation on a long-lived connection.--use obscura_cdp::dispatch::CdpContext;-use obscura_cdp::domains::page::emit_navigation_events;-use obscura_browser::lifecycle::WaitUntil;--fn navigate(ctx: &mut CdpContext, page_id: &str) {- emit_navigation_events(- ctx,- &Some("session-1".to_string()),- "frame-1",- "loader-1",- "http://127.0.0.1/page",- page_id,- &[],- WaitUntil::Load,- true,- );+// Regression for issue #407: navigation must retire a page's old execution+// context ids without deleting live contexts owned by another page.++use obscura_cdp::dispatch::{dispatch, CdpContext};+use obscura_cdp::types::CdpRequest;+use serde_json::{json, Value};++async fn cdp(+ ctx: &mut CdpContext,+ id: u64,+ method: &str,+ params: Value,+ session_id: &str,+) -> obscura_cdp::types::CdpResponse {+ dispatch(&CdpRequest {+ id,+ method: method.to_string(),+ params,+ session_id: Some(session_id.to_string()),+ }, ctx).await}-#[test]-fn navigation_prunes_stale_execution_context_ids() {+#[tokio::test(flavor = "current_thread")]+async fn navigation_prunes_only_the_navigated_pages_stale_context_ids() {let mut ctx = CdpContext::new();- // Seed a stale id that no navigation re-creates (simulates a context from- // a prior page state, or simply the pre-navigation main id 1).- ctx.valid_context_ids.insert(999);-- navigate(&mut ctx, "page-1");-- // The stale id is gone after executionContextsCleared; the default world- // (id 2) and the first isolated world (id 100, counter starts at 100) remain.- assert!(- !ctx.valid_context_ids.contains(&999),- "stale execution context id must be pruned on navigation"- );- assert!(ctx.valid_context_ids.contains(&2), "default world id 2 must be re-registered");- assert!(- ctx.valid_context_ids.contains(&100),- "isolated world id 100 must be registered: {:?}",- ctx.valid_context_ids- );-- navigate(&mut ctx, "page-1");-- // Second navigation: the first nav's isolated id (100) is now stale, and a- // fresh id (101) takes its place. The set must not grow across navigations.- assert!(- !ctx.valid_context_ids.contains(&100),- "previous navigation's isolated context id must be pruned"- );- assert!(ctx.valid_context_ids.contains(&101), "fresh isolated id 101 must be registered");- assert!(ctx.valid_context_ids.contains(&2), "default world id 2 must survive navigation");-- // Unbounded-growth check: two navigations leave exactly the default world- // plus the current isolated world(s), not an accumulating union.- let count_after_two_navs = ctx.valid_context_ids.len();- navigate(&mut ctx, "page-1");- navigate(&mut ctx, "page-1");- assert_eq!(- ctx.valid_context_ids.len(),- count_after_two_navs,- "valid_context_ids must not grow across navigations (was {count_after_two_navs}, now {})",- ctx.valid_context_ids.len()- );+ let first_page = ctx.create_page();+ let second_page = ctx.create_page();+ ctx.sessions.insert("first".to_string(), first_page);+ ctx.sessions.insert("second".to_string(), second_page);++ let stale = cdp(+ &mut ctx, 1, "Page.createIsolatedWorld",+ json!({"worldName": "first-world"}), "first",+ ).await.result.unwrap()["executionContextId"].as_i64().unwrap();+ let other_page = cdp(+ &mut ctx, 2, "Page.createIsolatedWorld",+ json!({"worldName": "second-world"}), "second",+ ).await.result.unwrap()["executionContextId"].as_i64().unwrap();++ cdp(+ &mut ctx, 3, "Page.navigate",+ json!({"url": "data:text/html,<p>replacement</p>", "waitUntil": "load"}),+ "first",+ ).await;++ let stale_result = cdp(+ &mut ctx, 4, "Runtime.evaluate",+ json!({"expression": "1", "contextId": stale}), "first",+ ).await;+ assert!(stale_result.error.unwrap().message.contains("Cannot find context"));+ let other_result = cdp(+ &mut ctx, 5, "Runtime.evaluate",+ json!({"expression": "1", "contextId": other_page}), "second",+ ).await;+ assert!(other_result.error.is_none(), "other page context was pruned");}