Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(email): keep the reply when the attribution shares its element (#9148)
Jacob Beckermanbb3e8a9a8b1b
diff --git a/crates/email_utils/AGENTS.md b/crates/email_utils/AGENTS.mdindex 477d90c264..77ff612c8d 100644--- a/crates/email_utils/AGENTS.md+++ b/crates/email_utils/AGENTS.md@@ -46,6 +46,10 @@ sender/generic-address checks.- Outlook mobile and Outlook on the web start the quoted thread at `<hr>` plus`div#divRplyFwdMsg` (plaintext: a line of underscores, then `From:`). Cutthere. A later `border-top` "From:" block is a nested quote.+- "On [date] [sender] wrote:" can share an element, or a text node, with the+ reply in some clients. Cut at the text node, never the shared element, and+ never return an empty reply: an empty cut falls through to the next+ splitter. Gmail writes a narrow no-break space before AM/PM.- Sanitization is security-sensitive (XSS via email HTML): any allowlistchange needs a test proving the previously-dangerous input is now stripped,not just that benign input survives.diff --git a/crates/email_utils/src/body_replyless/constants.rs b/crates/email_utils/src/body_replyless/constants.rsindex c829e5a995..8ff266b475 100644--- a/crates/email_utils/src/body_replyless/constants.rs+++ b/crates/email_utils/src/body_replyless/constants.rs@@ -6,9 +6,26 @@ use scraper::Selector;lazy_static! {// --- Regexes ---- // Regex for "On [Date], [Sender] wrote:" lines. Case-insensitive.+ /// "On [Date] [Sender] wrote:" attribution lines (Gmail, Superhuman, Apple+ /// Mail, Macro). `\s` is Unicode-aware, so it also covers the narrow+ /// no-break space Gmail puts before AM/PM and ` `. The sender part may+ /// span lines (and the `<a>` around the address) but is bounded so a+ /// stray "wrote:" far below cannot pull in reply text.pub static ref ON_WROTE_RE: Regex = Regex::new(- r#"(?i)On (Mon|Tue|Wed|Thu|Fri|Sat|Sun), (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{1,2}, \d{4} at \d{1,2}:\d{2} (AM|PM),? .* wrote:"#+ r#"(?xi)+ \bOn\s++ (?:(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)[a-z]*\.?,?\s+)? # weekday+ (?:\d{1,2}\s+)? # 29 Oct (day first)+ (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\.?\s++ (?:\d{1,2},?\s+)? # Oct 29, (month first)+ \d{4},?\s++ (?:at\s+)?+ \d{1,2}:\d{2}(?::\d{2})?+ (?:\s*[AP]\.?M\.?)?+ ,?\s++ (?s:.{0,300}?)+ \bwrote:+ "#).unwrap();// Regex for "From: ... Sent: ..." blocks, common in Outlook.@@ -41,7 +58,7 @@ lazy_static! {^On\s+(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s+(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+- .*+ [^\n]*(?:\n[^\n]*)? # clients wrap long attributions oncewrote:)| # OR@@ -81,5 +98,6 @@ lazy_static! {pub static ref BLOCKQUOTE_SELECTOR: Selector = Selector::parse("blockquote").unwrap();pub static ref ANY_ELEMENT_SELECTOR: Selector = Selector::parse("*").unwrap();pub static ref BODY_SELECTOR: Selector = Selector::parse("body").unwrap();+ pub static ref IMG_SELECTOR: Selector = Selector::parse("img").unwrap();pub static ref BLOCK_LEVEL_ELEMENTS_SELECTOR: Selector = Selector::parse("p, div, li, h1, h2, h3, h4, h5, h6").unwrap();}diff --git a/crates/email_utils/src/body_replyless/html_parser.rs b/crates/email_utils/src/body_replyless/html_parser.rsindex ac9eb716b4..ef168cddae 100644--- a/crates/email_utils/src/body_replyless/html_parser.rs+++ b/crates/email_utils/src/body_replyless/html_parser.rs@@ -1,6 +1,7 @@use super::constants::*;-use scraper::{Element, ElementRef, Html};-use std::{collections::HashSet, ops::Deref};+use ego_tree::{NodeId, NodeRef};+use scraper::{ElementRef, Html, Node};+use std::ops::Deref;// --- Public API ---/// Parses an email's HTML content and returns the cleaned, latest reply.@@ -12,56 +13,60 @@ pub fn extract_reply_html(subject: Option<&str>, html_content: &str) -> String {return html_content.to_string();}- let splitter = find_splitter(&document);+ // A cut that leaves nothing visible is wrong (the reply itself sits inside+ // the splitter), so fall through to the next candidate. If every cut is+ // empty, assume the entire body is the reply.+ find_splitters(&document)+ .into_iter()+ .map(|cut| get_html_before_cut(&document, cut))+ .find(|reply| has_visible_content(reply))+ .unwrap_or_else(|| html_content.to_string())+}- if let Some(splitter_element) = splitter {- get_html_before_element(splitter_element)- } else {- // No splitter found, so assume the entire body is the reply.- html_content.to_string()+/// Where the quoted thread starts: a node, and for a text node optionally the+/// byte offset inside it (the attribution can share a text node with the+/// reply, e.g. `See you then!<br>On Thu, ... wrote:`).+#[derive(Clone, Copy)]+struct Cut {+ node: NodeId,+ text_offset: Option<usize>,+}++impl From<ElementRef<'_>> for Cut {+ fn from(element: ElementRef<'_>) -> Self {+ Cut {+ node: element.id(),+ text_offset: None,+ }}}// --- Core Logic & Orchestration ----/// Orchestrates the search for a splitter element by finding all potential-/// candidates and choosing the one that appears earliest in the document.-fn find_splitter(document: &Html) -> Option<ElementRef<'_>> {- // 1. Collect the NodeIds of all possible splitter candidates.- let candidate_ids: HashSet<_> = vec![- find_gmail_splitter(document),- find_outlook_splitter(document),- find_yahoo_splitter(document),- find_blockquote_splitter(document),- find_text_based_splitter(document),+/// Collects every splitter candidate and orders them by where they appear in+/// the document, earliest first.+fn find_splitters(document: &Html) -> Vec<Cut> {+ let candidates: Vec<Cut> = [+ find_gmail_splitter(document).map(Cut::from),+ find_outlook_splitter(document).map(Cut::from),+ find_yahoo_splitter(document).map(Cut::from),+ find_blockquote_splitter(document).map(Cut::from),+ find_text_based_splitter(document).map(Cut::from),+ find_on_wrote_text_splitter(document),].into_iter().flatten()- // Map the ElementRefs to their NodeIds.- .map(|el| el.id()).collect();- // 2. If no candidates were found, there is no splitter.- if candidate_ids.is_empty() {- return None;- }-- // 3. Perform a single depth-first traversal of the entire document.- // The `find_map` method will stop and return the very first time our closure returns `Some`.-- document.root_element().traverse().find_map(|edge| {- // We only care about opening tags of nodes.+ // A single depth-first traversal gives document order; an ancestor opens+ // before its descendants, so it sorts first.+ let mut ordered: Vec<Cut> = Vec::with_capacity(candidates.len());+ for edge in document.tree.root().traverse() {if let ego_tree::iter::Edge::Open(node) = edge {- // Check if this node's ID is in our set of candidates.- if candidate_ids.contains(&node.id()) {- // It is! This must be the earliest one.- // Wrap it as an ElementRef and return it to stop the search.- return ElementRef::wrap(node);- }+ ordered.extend(candidates.iter().filter(|cut| cut.node == node.id()));}- // This node was not a candidate, continue the search.- None- })+ }+ ordered}// --- Specific Splitter-Finding Strategies ---@@ -113,9 +118,14 @@ fn find_outlook_splitter(document: &Html) -> Option<ElementRef<'_>> {fn find_blockquote_splitter(document: &Html) -> Option<ElementRef<'_>> {if let Some(blockquote) = document.select(&BLOCKQUOTE_SELECTOR).next() {- // Check if the node right before the blockquote is an "On... wrote:" line.+ // Check if the node right before the blockquote is an "On... wrote:"+ // line. Only take the whole element when the attribution opens it;+ // otherwise it also holds reply text and the cut belongs inside it+ // (`find_on_wrote_text_splitter`).if let Some(prev_el) = find_prev_significant_sibling(blockquote)- && ON_WROTE_RE.is_match(&prev_el.text().collect::<String>())+ && ON_WROTE_RE+ .find(prev_el.text().collect::<String>().trim_start())+ .is_some_and(|m| m.start() == 0){// If so, use that header as the splitter for a cleaner cut.return Some(prev_el);@@ -144,6 +154,49 @@ fn find_text_based_splitter(document: &Html) -> Option<ElementRef<'_>> {None}+/// Finds the first "On [date] [sender] wrote:" attribution anywhere in the body+/// and cuts at the text node where it starts. This catches attributions that+/// share an element with the reply, which element-level strategies cannot cut+/// without dropping the reply.+fn find_on_wrote_text_splitter(document: &Html) -> Option<Cut> {+ let body = document.select(&BODY_SELECTOR).next()?;++ let mut text = String::new();+ let mut spans: Vec<(usize, NodeId)> = Vec::new();+ for node in body.descendants() {+ let Some(node_text) = node.value().as_text() else {+ continue;+ };+ if is_inside_non_content(node) {+ continue;+ }+ // Separate nodes so words from adjacent blocks don't run together.+ text.push('\n');+ spans.push((text.len(), node.id()));+ text.push_str(node_text);+ }++ let start = ON_WROTE_RE.find(&text)?.start();+ let index = spans+ .partition_point(|(node_start, _)| *node_start <= start)+ .checked_sub(1)?;+ let (node_start, node) = *spans.get(index)?;+ let text_offset = start - node_start;+ Some(Cut {+ node,+ text_offset: (text_offset > 0).then_some(text_offset),+ })+}++fn is_inside_non_content(node: NodeRef<'_, Node>) -> bool {+ node.ancestors().any(|ancestor| {+ ancestor+ .value()+ .as_element()+ .is_some_and(|el| matches!(el.name(), "style" | "script" | "title" | "head"))+ })+}+/// The quoted thread starts at the horizontal rule when one sits directly/// above the reply header. Empty wrappers around that rule count; real reply/// text in between means the header itself is the cut.@@ -220,20 +273,18 @@ fn find_prev_significant_sibling(el: ElementRef) -> Option<ElementRef> {None}-/// Traverses the DOM to collect all HTML content that appears before the splitter element.-fn get_html_before_element(splitter: ElementRef) -> String {- let mut body_opt = None;- let mut current = Some(splitter);- while let Some(el) = current {- if el.value().name().eq_ignore_ascii_case("body") {- body_opt = Some(el);- break;- }- current = el.parent_element();- }+/// Traverses the DOM to collect all HTML content that appears before the cut.+fn get_html_before_cut(document: &Html, cut: Cut) -> String {+ let Some(splitter) = document.tree.get(cut.node) else {+ return String::new();+ };+ let body = std::iter::once(splitter)+ .chain(splitter.ancestors())+ .filter_map(ElementRef::wrap)+ .find(|el| el.value().name().eq_ignore_ascii_case("body"));- let result = if let Some(body) = body_opt {- get_previous_html_recursively(body, splitter)+ let result = if let Some(body) = body {+ get_previous_html_recursively(body, cut)} else {String::new()};@@ -242,30 +293,34 @@ fn get_html_before_element(splitter: ElementRef) -> String {}/// A recursive helper function that builds the HTML string by traversing the tree.-fn get_previous_html_recursively(current_element: ElementRef, splitter: ElementRef) -> String {+fn get_previous_html_recursively(current_element: ElementRef, cut: Cut) -> String {let mut reply_html_parts = Vec::new();for child in current_element.children() {// First, check if the child node IS the splitter itself.- if child.id() == splitter.id() {- // We have found the exact splitter element. Stop processing children at this level.- // Do not add anything to the parts and break the loop.+ if child.id() == cut.node {+ // Keep the part of a text node before the attribution.+ if let (Some(offset), Some(text)) = (cut.text_offset, child.value().as_text())+ && let Some(before) = text.get(..offset)+ {+ reply_html_parts.push(escape_text(before));+ }break;}// If the child is not the splitter, check if it CONTAINS the splitter.- let contains_splitter = child.descendants().any(|d| d.id() == splitter.id());+ let contains_splitter = child.descendants().any(|d| d.id() == cut.node);if contains_splitter {if let Some(child_el) = ElementRef::wrap(child) {- reply_html_parts.push(get_previous_html_recursively(child_el, splitter));+ reply_html_parts.push(get_previous_html_recursively(child_el, cut));}break;} else {let html_part = if let Some(element) = ElementRef::wrap(child) {element.html()} else if let Some(text) = child.value().as_text() {- text.to_string()+ escape_text(text)} else if let Some(comment) = child.value().as_comment() {format!("<!--{}-->", comment.deref())} else {@@ -277,3 +332,24 @@ fn get_previous_html_recursively(current_element: ElementRef, splitter: ElementRreply_html_parts.join("")}++/// Text nodes hold decoded text; re-escape it so `<addr>` doesn't turn+/// into markup.+fn escape_text(text: &str) -> String {+ text.replace('&', "&")+ .replace('<', "<")+ .replace('>', ">")+ .replace('\u{a0}', " ")+}++/// Whether a reply has anything a reader would see: text or an image.+fn has_visible_content(html: &str) -> bool {+ let fragment = Html::parse_fragment(html);+ fragment.select(&IMG_SELECTOR).next().is_some()+ || fragment+ .root_element()+ .descendants()+ .filter(|node| !is_inside_non_content(*node))+ .filter_map(|node| node.value().as_text())+ .any(|text| !text.trim().is_empty())+}diff --git a/crates/email_utils/src/body_replyless/test.rs b/crates/email_utils/src/body_replyless/test.rsindex 03ccc986c9..f014eb4e29 100644--- a/crates/email_utils/src/body_replyless/test.rs+++ b/crates/email_utils/src/body_replyless/test.rs@@ -202,3 +202,78 @@ fn test_email_extraction(full_email: &str, expected_reply: &str, test_name: &strtest_name);}++const NNBSP: &str = "\u{202f}";++/// Superhuman-style reply: the attribution shares an element with the reply+/// text, and Gmail-style times use a narrow no-break space before PM. Cutting+/// at the shared element dropped the whole reply.+#[test]+fn attribution_sharing_an_element_with_the_reply_keeps_the_reply() {+ let html = format!(+ r#"<div>Sorry for the slow reply, that works. See you then!<br><br>On Thu, Oct 29, 2026 at 7:22{NNBSP}PM, Curtis <<a href="mailto:[email protected]">[email protected]</a>> wrote:<br></div><blockquote><div>Hey all, just checking in.</div></blockquote><div>--<br><b>Jacob</b></div>"#+ );+ let sanitized = crate::sanitize_email_html(&html);+ let reply = compute_body_replyless(Some("Re: visit"), Some(&sanitized), None).expect("html");++ assert!(reply.contains("See you then!"), "{reply}");+ assert!(!reply.contains("wrote:"), "{reply}");+ assert!(!reply.contains("checking in"), "{reply}");+ assert!(!reply.contains("Jacob"), "{reply}");+}++/// The same text node can hold both the reply and the attribution.+#[test]+fn attribution_inside_the_reply_text_node_is_cut_mid_node() {+ let html = "<div>See you then! On Mon, Oct 26, 2026 at 9:58 AM Curtis <[email protected]> wrote: older</div>";+ let reply = compute_body_replyless(None, Some(html), None).expect("html");++ assert_eq!(reply, "See you then!");+}++#[test]+fn attribution_with_narrow_no_break_space_cuts_at_the_header() {+ let html = format!(+ r#"<p>Works for me.</p><p>On Wed, Oct 28, 2026 at 12:09{NNBSP}PM Curtis <[email protected]> wrote:</p><blockquote>Let's do 3pm?</blockquote>"#+ );+ let reply = compute_body_replyless(None, Some(&html), None).expect("html");++ assert_eq!(reply, "<p>Works for me.</p>");+}++/// Apple Mail writes "On Oct 29, 2026, at 19:22, Name <addr> wrote:".+#[test]+fn apple_mail_attribution_without_a_blockquote_is_cut() {+ let html = "<div>Sounds good.</div><div>On Oct 29, 2026, at 19:22, Curtis <[email protected]>\nwrote:</div><div>Older</div>";+ let reply = compute_body_replyless(None, Some(html), None).expect("html");++ assert_eq!(reply, "<div>Sounds good.</div>");+}++/// A splitter that wraps the reply would leave nothing; a later one is used.+#[test]+fn a_cut_that_empties_the_reply_falls_through() {+ let html = r#"<div style="border:1px solid">Reply text<div>From: a<br>Sent: b<br>To: c<br>Subject: d</div><blockquote>Quoted</blockquote></div>"#;+ let reply = compute_body_replyless(None, Some(html), None).expect("html");++ assert!(reply.contains("Reply text"), "{reply}");+ assert!(!reply.contains("Quoted"), "{reply}");+}++/// Kept text nodes are re-escaped rather than emitted as markup.+#[test]+fn kept_text_stays_escaped() {+ let html = "Use <b> tags<blockquote>Quoted</blockquote>";+ let reply = compute_body_replyless(None, Some(html), None).expect("html");++ assert_eq!(reply, "Use <b> tags");+}++#[test]+fn plaintext_cuts_at_a_wrapped_attribution() {+ let text = "See you then!\n\nOn Thu, Oct 29, 2026 at 7:22 PM, Curtis <[email protected]>\nwrote:\n\n> Hey all";+ assert_eq!(+ compute_body_replyless(None, None, Some(text)).as_deref(),+ Some("See you then!")+ );+}