Skip to content

The headless browser for AI agents and web scraping

feat(cdp): report the page's real child frame tree

xripbbc7d80c7bd1
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rs
index 7f9e1809..6ab2163b 100644
--- a/crates/obscura-browser/src/page.rs
+++ b/crates/obscura-browser/src/page.rs
@@ -1089,6 +1089,18 @@ impl Page {
true
}
+ /// Moves the frame tree forward by one step: give any fetched frame
+ /// document a realm, then hand on any message waiting for a realm.
+ ///
+ /// Reports whether anything happened, so a caller can pump again. A new
+ /// frame runs scripts that can post, and a message usually causes a reply,
+ /// so neither queue is finished until both are quiet.
+ async fn advance_frames(&mut self) -> bool {
+ let attached = self.attach_pending_frames().await;
+ let delivered = self.deliver_frame_messages();
+ attached || delivered
+ }
+
/// URLs of the page's live child frames, in creation order.
pub fn frame_urls(&self) -> Vec<String> {
self.frames
@@ -2459,11 +2471,7 @@ impl Page {
let _ = js.run_event_loop_until_quiescent(remaining, 150).await;
}
}
- let attached = self.attach_pending_frames().await;
- // A message usually causes a reply, so keep going while either the
- // frame tree or the conversation is still moving.
- let delivered = self.deliver_frame_messages();
- if !attached && !delivered {
+ if !self.advance_frames().await {
break;
}
}
@@ -2503,8 +2511,7 @@ impl Page {
// realms once at the end instead of being interleaved as in `settle`.
// Their document scripts still run; only their own deferred work is
// left for a later settle.
- self.attach_pending_frames().await;
- self.deliver_frame_messages();
+ self.advance_frames().await;
}
/// Advance one wake-driven browser task for a continuously owned page.
@@ -2920,9 +2927,50 @@ impl Page {
self.lifecycle = LifecycleState::NetworkIdle;
}
+ self.build_document_frames().await;
+
Ok(())
}
+ /// Builds the child frames of the document that just loaded.
+ ///
+ /// Loading a document includes loading the frames in it, so this belongs to
+ /// navigation rather than to `settle`: a CDP client that only navigates
+ /// would otherwise be told the page has no frames, because nothing had
+ /// given them realms yet.
+ ///
+ /// A frame's document is fetched by page script, so it arrives from the
+ /// event loop rather than being ready the moment parsing ends. Pages
+ /// without an iframe skip the pumping entirely and pay one native selector
+ /// query.
+ async fn build_document_frames(&mut self) {
+ // How many rounds of "attach a frame, let it start its own" to follow.
+ // A frame can add a frame, so this needs a bound rather than a loop
+ // until quiet: a page that adds one on every turn would never finish.
+ const ROUNDS: usize = 8;
+ const ROUND_MS: u64 = 50;
+
+ let has_iframe = self
+ .with_dom(|dom| dom.query_selector("iframe").ok().flatten().is_some())
+ .unwrap_or(false);
+ if !has_iframe {
+ return;
+ }
+
+ for _ in 0..ROUNDS {
+ if let Some(js) = &mut self.js {
+ let _ = tokio::time::timeout(
+ tokio::time::Duration::from_millis(ROUND_MS),
+ js.run_event_loop(),
+ )
+ .await;
+ }
+ if !self.advance_frames().await {
+ break;
+ }
+ }
+ }
+
pub fn navigate_blank(&mut self) {
self.js = None;
self.url = Some(Url::parse("about:blank").unwrap());
diff --git a/crates/obscura-cdp/src/dispatch.rs b/crates/obscura-cdp/src/dispatch.rs
index 997078d2..e06a6308 100644
--- a/crates/obscura-cdp/src/dispatch.rs
+++ b/crates/obscura-cdp/src/dispatch.rs
@@ -44,6 +44,9 @@ pub struct CdpContext {
/// script-initiated Network events must share this id; inventing a loader
/// for each fetch breaks DevTools request grouping.
pub current_loader_ids: HashMap<String, String>,
+ /// Child frame ids already reported to the client, per page, so each frame
+ /// is announced once and a frame that goes away can be retracted.
+ pub announced_frames: HashMap<String, Vec<String>>,
pub pending_events: Vec<CdpEvent>,
#[cfg(feature = "render")]
pub(crate) screencasts: HashMap<String, ScreencastState>,
@@ -155,6 +158,7 @@ impl CdpContext {
pages: Vec::new(),
sessions: HashMap::new(),
current_loader_ids: HashMap::new(),
+ announced_frames: HashMap::new(),
pending_events: Vec::new(),
#[cfg(feature = "render")]
screencasts: HashMap::new(),
@@ -535,6 +539,7 @@ pub async fn dispatch(req: &CdpRequest, ctx: &mut CdpContext) -> CdpResponse {
}
drain_binding_calls(ctx);
+ drain_frame_events(ctx);
match result {
Ok(value) => CdpResponse::success(req.id, value, req.session_id.clone()),
@@ -589,6 +594,81 @@ pub(crate) fn drain_binding_calls(ctx: &mut CdpContext) {
ctx.pending_events.extend(events);
}
+// Announce child frames the client has not been told about yet, and retract
+// the ones that are gone.
+//
+// A frame is built when the page settles, which is not necessarily during the
+// navigation that created it: script can add an iframe at any time, and the
+// settle that gives it a realm may belong to a later command. Diffing here,
+// after every dispatch, reports a frame whenever it actually appears instead
+// of only at navigation, and is the same drain point binding calls use.
+pub(crate) fn drain_frame_events(ctx: &mut CdpContext) {
+ let page_to_session: HashMap<String, String> = ctx
+ .sessions
+ .iter()
+ .map(|(sid, pid)| (pid.clone(), sid.clone()))
+ .collect();
+
+ let mut events: Vec<CdpEvent> = Vec::new();
+ let mut announced: HashMap<String, Vec<String>> = HashMap::new();
+ for page in &ctx.pages {
+ let Some(session_id) = page_to_session.get(&page.id).cloned() else {
+ continue;
+ };
+ let live = crate::domains::page::child_frame_values(page);
+ let known = ctx.announced_frames.get(&page.id);
+ let live_ids: Vec<String> = live
+ .iter()
+ .map(|frame| frame["id"].as_str().unwrap_or_default().to_string())
+ .collect();
+
+ for frame in &live {
+ let id = frame["id"].as_str().unwrap_or_default();
+ if known.is_some_and(|ids| ids.iter().any(|seen| seen == id)) {
+ continue;
+ }
+ // Attach before navigate: a client builds its frame from the attach
+ // event and treats a navigation of a frame it has never seen as a
+ // protocol error.
+ events.push(CdpEvent {
+ method: "Page.frameAttached".into(),
+ params: json!({
+ "frameId": id,
+ "parentFrameId": frame["parentId"].as_str().unwrap_or_default(),
+ }),
+ session_id: Some(session_id.clone()),
+ });
+ events.push(CdpEvent {
+ method: "Page.frameNavigated".into(),
+ params: json!({ "frame": frame, "type": "Navigation" }),
+ session_id: Some(session_id.clone()),
+ });
+ // The frame's document scripts have already run by the time it is
+ // in this list, so it is not still loading.
+ events.push(CdpEvent {
+ method: "Page.frameStoppedLoading".into(),
+ params: json!({ "frameId": id }),
+ session_id: Some(session_id.clone()),
+ });
+ }
+
+ if let Some(known) = known {
+ for id in known {
+ if !live_ids.contains(id) {
+ events.push(CdpEvent {
+ method: "Page.frameDetached".into(),
+ params: json!({ "frameId": id, "reason": "remove" }),
+ session_id: Some(session_id.clone()),
+ });
+ }
+ }
+ }
+ announced.insert(page.id.clone(), live_ids);
+ }
+ ctx.announced_frames.extend(announced);
+ ctx.pending_events.extend(events);
+}
+
async fn dispatch_send_message_to_target(req: &CdpRequest, ctx: &mut CdpContext) -> CdpResponse {
let session_id = req
.params
diff --git a/crates/obscura-cdp/src/domains/page.rs b/crates/obscura-cdp/src/domains/page.rs
index 8d20ba8d..5afc539f 100644
--- a/crates/obscura-cdp/src/domains/page.rs
+++ b/crates/obscura-cdp/src/domains/page.rs
@@ -10,6 +10,82 @@ use crate::dispatch::{ScreencastFormat, ScreencastState};
#[cfg(feature = "render")]
const DEFAULT_SCREENSHOT_QUALITY: i64 = 80;
+
+/// CDP frame ids are strings, while a realm is identified by number, so a
+/// child's protocol id is derived from its page's. It stays stable for the
+/// life of the frame, which is what lets a client match an attach event to the
+/// frame it later sees in the tree.
+fn child_frame_id(page_frame_id: &str, frame_id: u32) -> String {
+ format!("{page_frame_id}-frame-{frame_id}")
+}
+
+fn child_frame_value(page_frame_id: &str, frame: &obscura_js::frame::FrameRealm) -> Value {
+ let id = child_frame_id(page_frame_id, frame.frame_id());
+ let parent_id = if frame.parent_frame_id() == 0 {
+ page_frame_id.to_string()
+ } else {
+ child_frame_id(page_frame_id, frame.parent_frame_id())
+ };
+ json!({
+ "id": id,
+ "parentId": parent_id,
+ "loaderId": format!("{id}-loader"),
+ "url": frame.url(),
+ "domainAndRegistry": "",
+ "securityOrigin": frame.origin(),
+ "mimeType": "text/html",
+ "adFrameStatus": { "adFrameType": "none" },
+ })
+}
+
+/// The page's child frames, flattened with each parent ahead of its children
+/// so an attach event never names a parent the client has not seen yet.
+pub fn child_frame_values(page: &obscura_browser::Page) -> Vec<Value> {
+ fn walk(page: &obscura_browser::Page, parent_frame_id: u32, out: &mut Vec<Value>) {
+ for frame in page
+ .frames
+ .iter()
+ .filter(|frame| frame.parent_frame_id() == parent_frame_id)
+ {
+ out.push(child_frame_value(&page.frame_id, frame));
+ walk(page, frame.frame_id(), out);
+ }
+ }
+
+ let mut out = Vec::new();
+ walk(page, 0, &mut out);
+ out
+}
+
+/// The page's live frame hierarchy. `childFrames` used to be hardcoded empty,
+/// so a client was told the page had no frames however many it had built.
+fn frame_tree(page: &obscura_browser::Page) -> Value {
+ fn children(page: &obscura_browser::Page, parent_frame_id: u32) -> Vec<Value> {
+ page.frames
+ .iter()
+ .filter(|frame| frame.parent_frame_id() == parent_frame_id)
+ .map(|frame| {
+ json!({
+ "frame": child_frame_value(&page.frame_id, frame),
+ "childFrames": children(page, frame.frame_id()),
+ })
+ })
+ .collect()
+ }
+
+ json!({
+ "frame": {
+ "id": page.frame_id,
+ "loaderId": "initial-loader",
+ "url": page.url_string(),
+ "domainAndRegistry": "",
+ "securityOrigin": page.url_string(),
+ "mimeType": "text/html",
+ "adFrameStatus": { "adFrameType": "none" },
+ },
+ "childFrames": children(page, 0),
+ })
+}
#[cfg(feature = "render")]
const MAX_SCREENCAST_FRAMES_IN_FLIGHT: u8 = 2;
#[cfg(feature = "render")]
@@ -1153,20 +1229,7 @@ pub async fn handle(
let page = ctx
.get_session_page(session_id)
.ok_or("No page for session")?;
- Ok(json!({
- "frameTree": {
- "frame": {
- "id": page.frame_id,
- "loaderId": "initial-loader",
- "url": page.url_string(),
- "domainAndRegistry": "",
- "securityOrigin": page.url_string(),
- "mimeType": "text/html",
- "adFrameStatus": { "adFrameType": "none" },
- },
- "childFrames": [],
- }
- }))
+ Ok(json!({ "frameTree": frame_tree(page) }))
}
"createIsolatedWorld" => {
let (frame_id_param, world_name, page_url, page_id) = {
diff --git a/crates/obscura-cdp/src/server.rs b/crates/obscura-cdp/src/server.rs
index 9ee15949..0d2a2b3b 100644
--- a/crates/obscura-cdp/src/server.rs
+++ b/crates/obscura-cdp/src/server.rs
@@ -772,6 +772,7 @@ async fn cdp_processor(
}
sync_live_page_network_events(&mut ctx);
dispatch::drain_binding_calls(&mut ctx);
+ dispatch::drain_frame_events(&mut ctx);
forward_pending_events(&mut ctx, connection_reply_tx.as_ref());
if let (Some(reply_tx), Some((session_id, url, method, body))) = (
connection_reply_tx.as_ref(),
diff --git a/crates/obscura-cdp/tests/child_frame_tree.rs b/crates/obscura-cdp/tests/child_frame_tree.rs
new file mode 100644
index 00000000..53479914
--- /dev/null
+++ b/crates/obscura-cdp/tests/child_frame_tree.rs
@@ -0,0 +1,128 @@
+//! Regression test for the protocol half of issue #600: `Page.getFrameTree`
+//! reported `childFrames: []` however many frames a page had built, and no
+//! `Page.frameAttached` was ever emitted, so a Playwright or Puppeteer client
+//! saw a single-frame page and could never address the child.
+
+use obscura_cdp::dispatch::{dispatch, CdpContext};
+use obscura_cdp::types::CdpRequest;
+use serde_json::{json, Value};
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::TcpListener;
+
+/// `/` embeds `/child.html`, which itself embeds `/grandchild.html`, so the
+/// tree is deep enough to show nesting rather than a flat list.
+async fn serve() -> String {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move {
+ while let Ok((mut socket, _)) = listener.accept().await {
+ tokio::spawn(async move {
+ let mut buf = [0u8; 2048];
+ let read = socket.read(&mut buf).await.unwrap_or(0);
+ let request = String::from_utf8_lossy(&buf[..read]).to_string();
+ let body = if request.starts_with("GET /child.html ") {
+ "<html><body><iframe src=\"/grandchild.html\"></iframe></body></html>"
+ } else if request.starts_with("GET /grandchild.html ") {
+ "<html><body><p>deep</p></body></html>"
+ } else {
+ "<html><body><iframe src=\"/child.html\"></iframe></body></html>"
+ };
+ let resp = format!(
+ "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
+ body.len()
+ );
+ let _ = socket.write_all(resp.as_bytes()).await;
+ });
+ }
+ });
+ format!("http://{addr}/")
+}
+
+async fn cdp(ctx: &mut CdpContext, id: u64, method: &str, params: Value, session: &str) -> Value {
+ let resp = dispatch(
+ &CdpRequest {
+ id,
+ method: method.to_string(),
+ params,
+ session_id: Some(session.to_string()),
+ },
+ ctx,
+ )
+ .await;
+ assert!(resp.error.is_none(), "CDP {method} failed: {:?}", resp.error);
+ resp.result.unwrap_or_else(|| json!({}))
+}
+
+#[tokio::test(flavor = "current_thread")]
+async fn get_frame_tree_reports_nested_child_frames() {
+ std::env::set_var("OBSCURA_ALLOW_PRIVATE_NETWORK", "1");
+ let url = serve().await;
+ let mut ctx = CdpContext::new();
+ let page_id = ctx.create_page();
+ let session = "session-1";
+ ctx.sessions.insert(session.to_string(), page_id);
+
+ cdp(
+ &mut ctx,
+ 1,
+ "Page.navigate",
+ json!({"url": url, "waitUntil": "load"}),
+ session,
+ )
+ .await;
+ // Frames are built when the page settles, which is not part of the
+ // navigation itself.
+ cdp(&mut ctx, 2, "Runtime.evaluate", json!({"expression": "1"}), session).await;
+
+ let tree = cdp(&mut ctx, 3, "Page.getFrameTree", json!({}), session).await;
+ let root = &tree["frameTree"];
+ let child = &root["childFrames"][0];
+ assert!(
+ child["frame"]["url"]
+ .as_str()
+ .unwrap_or_default()
+ .ends_with("/child.html"),
+ "no child frame in the tree: {tree}"
+ );
+ assert_eq!(
+ child["frame"]["parentId"], root["frame"]["id"],
+ "the child does not point back at the main frame"
+ );
+
+ let grandchild = &child["childFrames"][0];
+ assert!(
+ grandchild["frame"]["url"]
+ .as_str()
+ .unwrap_or_default()
+ .ends_with("/grandchild.html"),
+ "a frame inside a frame is missing: {tree}"
+ );
+ assert_eq!(grandchild["frame"]["parentId"], child["frame"]["id"]);
+
+ // A client builds its frame list from the events, so the tree alone is not
+ // enough. Attach must precede the navigation of the same frame.
+ let child_id = child["frame"]["id"].as_str().unwrap().to_string();
+ let attached = ctx
+ .pending_events
+ .iter()
+ .position(|e| e.method == "Page.frameAttached" && e.params["frameId"] == child_id)
+ .expect("no Page.frameAttached for the child frame");
+ let navigated = ctx
+ .pending_events
+ .iter()
+ .position(|e| e.method == "Page.frameNavigated" && e.params["frame"]["id"] == child_id)
+ .expect("no Page.frameNavigated for the child frame");
+ assert!(
+ attached < navigated,
+ "frameAttached must come before frameNavigated"
+ );
+
+ // Each frame is announced once, however many commands the client sends.
+ let before = ctx.pending_events.len();
+ cdp(&mut ctx, 4, "Page.getFrameTree", json!({}), session).await;
+ let repeats = ctx.pending_events[before..]
+ .iter()
+ .filter(|e| e.method == "Page.frameAttached")
+ .count();
+ assert_eq!(repeats, 0, "the same frame was announced twice");
+}