Skip to content

The headless browser for AI agents and web scraping

Fix inline text whitespace serialization

lisa03149e5332d26843
diff --git a/crates/obscura-cli/src/main.rs b/crates/obscura-cli/src/main.rs
index 0e6a36c1..56ad5d29 100644
--- a/crates/obscura-cli/src/main.rs
+++ b/crates/obscura-cli/src/main.rs
@@ -1396,6 +1396,28 @@ fn dump_markdown(page: &mut Page) -> String {
result.as_str().unwrap_or_default().to_string()
}
+fn is_html_whitespace(c: char) -> bool {
+ matches!(c, '\t' | '\n' | '\x0C' | '\r' | ' ')
+}
+
+fn append_readable_text_segment(result: &mut String, pending_space: &mut bool, contents: &str) {
+ let trimmed = contents.trim_matches(is_html_whitespace);
+ if trimmed.is_empty() {
+ if contents.chars().any(is_html_whitespace) {
+ *pending_space = true;
+ }
+ return;
+ }
+
+ let begins_with_space = contents.chars().next().is_some_and(is_html_whitespace);
+ let result_ends_with_space = result.chars().next_back().is_some_and(char::is_whitespace);
+ if (*pending_space || begins_with_space) && !result.is_empty() && !result_ends_with_space {
+ result.push(' ');
+ }
+ result.push_str(trimmed);
+ *pending_space = contents.chars().next_back().is_some_and(is_html_whitespace);
+}
+
fn extract_readable_text(dom: &obscura_dom::DomTree, node_id: obscura_dom::NodeId) -> String {
use obscura_dom::NodeData;
@@ -1415,6 +1437,7 @@ fn extract_readable_text(dom: &obscura_dom::DomTree, node_id: obscura_dom::NodeI
const MAX_NODES: usize = 5_000_000;
let mut result = String::new();
+ let mut pending_space = false;
let mut stack: Vec<Work> = vec![Work::Visit(node_id)];
let mut visited = 0usize;
@@ -1422,6 +1445,7 @@ fn extract_readable_text(dom: &obscura_dom::DomTree, node_id: obscura_dom::NodeI
let id = match work {
Work::Newline => {
result.push('\n');
+ pending_space = false;
continue;
}
Work::Visit(id) => id,
@@ -1439,10 +1463,7 @@ fn extract_readable_text(dom: &obscura_dom::DomTree, node_id: obscura_dom::NodeI
match &node.data {
NodeData::Text { contents } => {
- let trimmed = contents.trim();
- if !trimmed.is_empty() {
- result.push_str(trimmed);
- }
+ append_readable_text_segment(&mut result, &mut pending_space, contents);
}
NodeData::Element { name, .. } => {
let tag = name.local.as_ref();
@@ -1495,6 +1516,7 @@ fn extract_readable_text(dom: &obscura_dom::DomTree, node_id: obscura_dom::NodeI
if is_block {
result.push('\n');
+ pending_space = false;
// Processed after all children (stack is LIFO): the trailing newline.
stack.push(Work::Newline);
}
diff --git a/crates/obscura-cli/tests/mcp_client.rs b/crates/obscura-cli/tests/mcp_client.rs
index b9266a48..5058d6ca 100644
--- a/crates/obscura-cli/tests/mcp_client.rs
+++ b/crates/obscura-cli/tests/mcp_client.rs
@@ -16,6 +16,12 @@ const QUEUED_NAVIGATION_SELECTOR: &str = "#queued";
const QUEUED_NAVIGATION_TITLE: &str = "queued-task-finished";
const TIMER_TEST_INITIAL_PAGE: &str = "data:text/html,<title>initial</title>";
const TIMER_TEST_TIMEOUT_SECONDS: u64 = 1;
+const INLINE_TEXT_URL: &str = "data:text/html,\
+<html><body>\
+<h1><span>H</span><span>e</span><span>l</span><span>l</span><span>o</span>%20\
+<span>w</span><span>o</span><span>r</span><span>l</span><span>d</span><span>.</span></h1>\
+<p><span>Hello</span><span>,</span>%20<span>world</span><span>!</span></p>\
+</body></html>";
/// A loopback fixture keeps protocol tests independent of public-site bot
/// policy, DNS, and content changes. The previous example.com dependency can
@@ -202,6 +208,27 @@ fn test_initialize() {
assert_eq!(resp["result"]["serverInfo"]["name"], "obscura-mcp");
}
+#[test]
+fn snapshot_preserves_whitespace_between_inline_spans() {
+ let mut client = McpClient::spawn();
+ let navigation = client.tool(
+ "browser_navigate",
+ serde_json::json!({ "url": INLINE_TEXT_URL }),
+ );
+ assert!(
+ navigation.get("error").is_none(),
+ "navigation failed: {navigation}"
+ );
+
+ let snapshot = client.tool("browser_snapshot", serde_json::json!({}));
+ let text = content_text(&snapshot);
+ assert!(
+ text.contains("Hello world.\n\nHello, world!"),
+ "snapshot mangled inline text: {text}"
+ );
+ assert!(!text.contains("H e l l o"), "snapshot inserted spaces: {text}");
+}
+
#[test]
fn test_ping() {
let mut c = McpClient::spawn();
diff --git a/crates/obscura-cli/tests/text_whitespace.rs b/crates/obscura-cli/tests/text_whitespace.rs
new file mode 100644
index 00000000..39dbfbfb
--- /dev/null
+++ b/crates/obscura-cli/tests/text_whitespace.rs
@@ -0,0 +1,34 @@
+use std::process::Command;
+
+const INLINE_TEXT_URL: &str = "data:text/html,\
+<html><body>\
+<h1><span>H</span><span>e</span><span>l</span><span>l</span><span>o</span>%20\
+<span>w</span><span>o</span><span>r</span><span>l</span><span>d</span><span>.</span></h1>\
+<p><span>Hello</span><span>,</span>%20<span>world</span><span>!</span></p>\
+</body></html>";
+
+#[test]
+fn dump_text_preserves_whitespace_between_inline_spans() {
+ let output = Command::new(env!("CARGO_BIN_EXE_obscura"))
+ .args([
+ "fetch",
+ INLINE_TEXT_URL,
+ "--dump",
+ "text",
+ "--quiet",
+ ])
+ .output()
+ .expect("run obscura fetch");
+
+ assert!(
+ output.status.success(),
+ "obscura fetch failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert_eq!(
+ String::from_utf8(output.stdout)
+ .expect("UTF-8 text dump")
+ .trim(),
+ "Hello world.\n\nHello, world!",
+ );
+}
diff --git a/crates/obscura-mcp/src/lib.rs b/crates/obscura-mcp/src/lib.rs
index 24aa3d75..2b342920 100644
--- a/crates/obscura-mcp/src/lib.rs
+++ b/crates/obscura-mcp/src/lib.rs
@@ -1825,52 +1825,94 @@ fn tool_tab_close(args: &Value, state: &mut BrowserState) -> Result<String, Stri
Ok(summary)
}
+fn is_html_whitespace(c: char) -> bool {
+ matches!(c, '\t' | '\n' | '\x0C' | '\r' | ' ')
+}
+
+fn append_text_segment(result: &mut String, pending_space: &mut bool, contents: &str) {
+ let trimmed = contents.trim_matches(is_html_whitespace);
+ if trimmed.is_empty() {
+ if contents.chars().any(is_html_whitespace) {
+ *pending_space = true;
+ }
+ return;
+ }
+
+ let begins_with_space = contents.chars().next().is_some_and(is_html_whitespace);
+ let result_ends_with_space = result.chars().next_back().is_some_and(char::is_whitespace);
+ if (*pending_space || begins_with_space) && !result.is_empty() && !result_ends_with_space {
+ result.push(' ');
+ }
+ result.push_str(trimmed);
+ *pending_space = contents.chars().next_back().is_some_and(is_html_whitespace);
+}
+
fn extract_text(dom: &obscura_dom::DomTree, node_id: obscura_dom::NodeId) -> String {
use obscura_dom::NodeData;
+ enum Work {
+ Visit(obscura_dom::NodeId),
+ Newline,
+ }
+
+ const MAX_NODES: usize = 5_000_000;
+
let mut result = String::new();
- let node = match dom.get_node(node_id) {
- Some(n) => n,
- None => return result,
- };
+ let mut pending_space = false;
+ let mut stack = vec![Work::Visit(node_id)];
+ let mut visited = 0usize;
- match &node.data {
- NodeData::Text { contents } => {
- let trimmed = contents.trim();
- if !trimmed.is_empty() {
- result.push_str(trimmed);
- result.push(' ');
+ while let Some(work) = stack.pop() {
+ let id = match work {
+ Work::Newline => {
+ result.push('\n');
+ pending_space = false;
+ continue;
}
+ Work::Visit(id) => id,
+ };
+
+ visited += 1;
+ if visited > MAX_NODES {
+ break;
}
- NodeData::Element { name, .. } => {
- let tag = name.local.as_ref();
- if matches!(tag, "script" | "style" | "noscript") {
- return result;
- }
- let is_block = matches!(
- tag,
- "div" | "p" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6"
- | "li" | "tr" | "br" | "hr" | "section" | "article"
- | "header" | "footer" | "nav" | "main" | "aside"
- | "blockquote" | "pre" | "ul" | "ol" | "table"
- );
+ let node = match dom.get_node(id) {
+ Some(node) => node,
+ None => continue,
+ };
- if is_block {
- result.push('\n');
+ match &node.data {
+ NodeData::Text { contents } => {
+ append_text_segment(&mut result, &mut pending_space, contents);
}
+ NodeData::Element { name, .. } => {
+ let tag = name.local.as_ref();
+ if matches!(tag, "script" | "style" | "noscript") {
+ continue;
+ }
- for child in dom.children(node_id) {
- result.push_str(&extract_text(dom, child));
- }
+ let is_block = matches!(
+ tag,
+ "div" | "p" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6"
+ | "li" | "tr" | "br" | "hr" | "section" | "article"
+ | "header" | "footer" | "nav" | "main" | "aside"
+ | "blockquote" | "pre" | "ul" | "ol" | "table"
+ );
- if is_block {
- result.push('\n');
+ if is_block {
+ result.push('\n');
+ pending_space = false;
+ stack.push(Work::Newline);
+ }
+ for child in dom.children(id).into_iter().rev() {
+ stack.push(Work::Visit(child));
+ }
}
- }
- _ => {
- for child in dom.children(node_id) {
- result.push_str(&extract_text(dom, child));
+ _ => {
+ for child in dom.children(id).into_iter().rev() {
+ stack.push(Work::Visit(child));
+ }
}
}
}