The headless browser for AI agents and web scraping
fix(mcp): collect page console messages
SGavrlbf11721d125a
diff --git a/crates/obscura-browser/src/page.rs b/crates/obscura-browser/src/page.rsindex fdbc3b40..ddea0ec1 100644--- a/crates/obscura-browser/src/page.rs+++ b/crates/obscura-browser/src/page.rs@@ -316,6 +316,7 @@ pub struct Page {/// Page-owned so the subscription survives replacement of the JS runtime/// during navigation.runtime_events_enabled: std::cell::Cell<bool>,+ console_messages_enabled: std::cell::Cell<bool>,pending_frame_work: std::collections::VecDeque<PendingFrameWork>,/// Document-owned HTML script preparation flags saved while the V8 realm/// is suspended for CDP/MCP tab switching. These are restored only when@@ -1162,6 +1163,7 @@ impl Page {intercept_tx: None,preload_scripts: Vec::new(),runtime_events_enabled: std::cell::Cell::new(false),+ console_messages_enabled: std::cell::Cell::new(false),pending_frame_work: std::collections::VecDeque::new(),suspended_started_script_ids: Vec::new(),suspended_cdp_object_state: obscura_js::runtime::CdpObjectState::default(),@@ -1863,6 +1865,7 @@ impl Page {#[cfg(feature = "render")]rt.set_intercept_block_patterns(self.intercept_block_patterns.clone());rt.set_runtime_events_enabled(self.runtime_events_enabled.get());+ rt.set_console_messages_enabled(self.console_messages_enabled.get());if let Some(dom) = self.dom.take() {rt.set_dom(dom);@@ -4571,6 +4574,13 @@ impl Page {}}+ pub fn take_pending_console_messages(&mut self) -> Vec<String> {+ self.js+ .as_ref()+ .map(ObscuraJsRuntime::take_pending_console_messages)+ .unwrap_or_default()+ }+pub fn set_runtime_events_enabled(&self, enabled: bool) {self.runtime_events_enabled.set(enabled);if let Some(js) = &self.js {@@ -4578,6 +4588,13 @@ impl Page {}}+ pub fn set_console_messages_enabled(&self, enabled: bool) {+ self.console_messages_enabled.set(enabled);+ if let Some(js) = &self.js {+ js.set_console_messages_enabled(enabled);+ }+ }+pub fn set_preload_scripts(&mut self, scripts: Vec<String>) {self.preload_scripts = scripts;}diff --git a/crates/obscura-js/src/ops.rs b/crates/obscura-js/src/ops.rsindex 5de565bf..ddb3d918 100644--- a/crates/obscura-js/src/ops.rs+++ b/crates/obscura-js/src/ops.rs@@ -140,6 +140,8 @@ pub struct ObscuraState {// The CDP layer drains this after commands and autonomous event-loop turns.pub pending_runtime_events: VecDeque<RuntimeEvent>,pub runtime_events_enabled: bool,+ pub pending_console_messages: VecDeque<String>,+ pub console_messages_enabled: bool,pub runtime_exception_counter: u64,pub network_response_bodies: HashMap<String, StoredNetworkResponseBody>,pub network_response_body_order: VecDeque<String>,@@ -356,6 +358,8 @@ impl ObscuraState {pending_binding_calls: Vec::new(),pending_runtime_events: VecDeque::new(),runtime_events_enabled: false,+ pending_console_messages: VecDeque::new(),+ console_messages_enabled: false,runtime_exception_counter: 0,network_response_bodies: HashMap::new(),network_response_body_order: VecDeque::new(),@@ -2291,6 +2295,13 @@ fn op_console_msg(let page = state.borrow::<SharedState>().clone();let mut page = page.borrow_mut();+ if page.console_messages_enabled {+ if page.pending_console_messages.len() >= 1_024 {+ page.pending_console_messages.pop_front();+ }+ page.pending_console_messages+ .push_back(format!("[{level}] {msg}"));+ }if !page.runtime_events_enabled {return;}diff --git a/crates/obscura-js/src/runtime.rs b/crates/obscura-js/src/runtime.rsindex 8f678dd5..d342f952 100644--- a/crates/obscura-js/src/runtime.rs+++ b/crates/obscura-js/src/runtime.rs@@ -1245,6 +1245,18 @@ impl ObscuraJsRuntime {self.state.borrow_mut().runtime_events_enabled = enabled;}+ pub fn set_console_messages_enabled(&self, enabled: bool) {+ self.state.borrow_mut().console_messages_enabled = enabled;+ }++ pub fn take_pending_console_messages(&self) -> Vec<String> {+ self.state+ .borrow_mut()+ .pending_console_messages+ .drain(..)+ .collect()+ }+fn record_uncaught_exception(&self, error: &deno_core::error::JsError, fallback_url: &str) {let mut state = self.state.borrow_mut();if !state.runtime_events_enabled {diff --git a/crates/obscura-mcp/src/lib.rs b/crates/obscura-mcp/src/lib.rsindex 2e3a6c53..b52c468e 100644--- a/crates/obscura-mcp/src/lib.rs+++ b/crates/obscura-mcp/src/lib.rs@@ -100,7 +100,9 @@ impl BrowserState {if self.active_tab.is_none() {self.tab_counter += 1;let id = format!("tab-{}", self.tab_counter);- self.tabs.insert(id.clone(), Page::new("mcp-page".to_string(), self.context.clone()));+ let page = Page::new("mcp-page".to_string(), self.context.clone());+ page.set_console_messages_enabled(true);+ self.tabs.insert(id.clone(), page);self.active_tab = Some(id);}let id = self.active_tab.as_ref().unwrap().clone();@@ -111,7 +113,9 @@ impl BrowserState {fn new_tab(&mut self) -> String {self.tab_counter += 1;let id = format!("tab-{}", self.tab_counter);- self.tabs.insert(id.clone(), Page::new(format!("mcp-{id}"), self.context.clone()));+ let page = Page::new(format!("mcp-{id}"), self.context.clone());+ page.set_console_messages_enabled(true);+ self.tabs.insert(id.clone(), page);self.active_tab = Some(id.clone());self.interactive_refs.clear();id@@ -1177,7 +1181,13 @@ fn tool_network_requests(state: &mut BrowserState) -> Result<String, String> {Ok(lines.join("\n"))}-fn tool_console_messages(state: &BrowserState) -> Result<String, String> {+fn tool_console_messages(state: &mut BrowserState) -> Result<String, String> {+ let messages = state.page_mut().take_pending_console_messages();+ state.console_messages.extend(messages);+ if state.console_messages.len() > 1_024 {+ let overflow = state.console_messages.len() - 1_024;+ state.console_messages.drain(..overflow);+ }if state.console_messages.is_empty() {Ok("No console messages.".to_string())} else {@@ -2167,6 +2177,38 @@ mod tests {assert_eq!(invalid_pdf["isError"], true);}+ #[tokio::test(flavor = "current_thread")]+ async fn console_tool_returns_page_messages() {+ const PAGE: &str = "data:text/html,<button id=log>Log</button><script>\+ console.error('mcp-console-inline');\+ document.getElementById('log').onclick=()=>{\+ console.error('mcp-console-click');\+ setTimeout(()=>{console.error('mcp-console-async');document.body.id='done'},25)\+ }</script>";+ let mut state = BrowserState::new(None, None, false);+ state+ .page_mut()+ .navigate(PAGE)+ .await+ .expect("console test page should navigate");++ let inline = tool_console_messages(&mut state).expect("console tool should succeed");+ assert!(+ inline.contains("mcp-console-inline"),+ "inline console message missing from MCP output: {inline}"+ );++ tool_click(&json!({ "selector": "#log" }), &mut state)+ .await+ .expect("console test button should be clickable");+ tool_wait_for(&json!({ "selector": "#done", "timeout": 2 }), &mut state)+ .await+ .expect("asynchronous console callback should complete");+ let later = tool_console_messages(&mut state).expect("console tool should succeed");+ assert!(later.contains("mcp-console-click"), "{later}");+ assert!(later.contains("mcp-console-async"), "{later}");+ }+/// Records the method, path and body of every request it serves, so a test/// can assert what actually left the process rather than what the page/// believes happened. Serves the issue's form at `/` and 200s everything