Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(notifications): show mentions by name in agent session alerts (#9379)

teocf35e571b7e8
diff --git a/crates/mention_utils/src/parse.rs b/crates/mention_utils/src/parse.rs
index c9408117ad..393e3c5ec0 100644
--- a/crates/mention_utils/src/parse.rs
+++ b/crates/mention_utils/src/parse.rs
@@ -5,9 +5,9 @@ use nom::{
branch::alt,
bytes::complete::{tag, tag_no_case, take_till1, take_while1},
character::complete::anychar,
- combinator::{eof, peek, recognize, verify},
+ combinator::{eof, not, peek, recognize, verify},
multi::{many_till, many0},
- sequence::{delimited, preceded},
+ sequence::{delimited, preceded, terminated},
};
use serde::Deserialize;
use std::{
@@ -320,19 +320,53 @@ pub struct ParsedXmlText<'de>(pub Vec<TextSegment<'de>>);
#[error(transparent)]
pub struct ParseErr(#[from] nom::error::Error<String>);
+/// One piece of message markup: a recognized tag, a run of text up to the next
+/// `<`, or an unrecognized `<m-*>` tag, which is dropped.
+fn parse_segment(s: &str) -> IResult<&str, Option<TextSegment<'_>>> {
+ alt((
+ parse_xml_tag.map(|xml| Some(TextSegment::Xml(xml))),
+ take_till1(|c| c == '<').map(|text| Some(TextSegment::Plain(text))),
+ parse_unknown_xml_tag.map(|()| None),
+ ))
+ .parse(s)
+}
+
impl<'de> ParsedXmlText<'de> {
pub fn parse(s: &'de str) -> Result<Self, ParseErr> {
- let (_, (out, _)) = many0(alt((
- parse_xml_tag.map(|xml| Some(TextSegment::Xml(xml))),
- take_till1(|c| c == '<').map(|text| Some(TextSegment::Plain(text))),
- parse_unknown_xml_tag.map(|()| None),
- )))
- .and(eof)
- .parse(s)
- .finish()
- .map_err(|e| e.cloned())?;
+ let (_, (out, _)) = many0(parse_segment)
+ .and(eof)
+ .parse(s)
+ .finish()
+ .map_err(|e| e.cloned())?;
Ok(ParsedXmlText(out.into_iter().flatten().collect()))
}
+
+ /// Parses text that need not be valid message markup, such as an agent's
+ /// Markdown reply, where `Vec<String>` or `a < b` is ordinary prose. A `<`
+ /// that does not open an `<m-*>` tag stays as plain text instead of failing
+ /// the whole input, so the tags around it are still recognized.
+ ///
+ /// From the first `<m-*>` tag that does not parse, the rest is kept as
+ /// plain text. Retrying after it would rescan the remaining input for a
+ /// closing tag at every such tag, which is quadratic in a long reply.
+ pub fn parse_lenient(s: &'de str) -> Self {
+ let stray_lt = terminated(tag("<"), not(tag_no_case("m-")));
+ let parsed = many0(alt((
+ parse_segment,
+ stray_lt.map(|lt| Some(TextSegment::Plain(lt))),
+ )))
+ .parse(s);
+ let Ok((rest, out)) = parsed else {
+ // Every alternative consumes input or fails recoverably, so this is
+ // not reached; keep the text rather than lose it if it ever is.
+ return ParsedXmlText(vec![TextSegment::Plain(s)]);
+ };
+ let mut segments: Vec<_> = out.into_iter().flatten().collect();
+ if !rest.is_empty() {
+ segments.push(TextSegment::Plain(rest));
+ }
+ ParsedXmlText(segments)
+ }
}
pub struct ReformattedXmlText<T>(pub String, PhantomData<T>);
diff --git a/crates/mention_utils/src/tests.rs b/crates/mention_utils/src/tests.rs
index 3d4e9a1a25..f64e0b0539 100644
--- a/crates/mention_utils/src/tests.rs
+++ b/crates/mention_utils/src/tests.rs
@@ -935,3 +935,47 @@ fn parse_unknown_tag_mixed_with_recognized() {
]
);
}
+
+// =============================================================================
+// Lenient parsing (prose that need not be valid markup)
+// =============================================================================
+
+fn lenient_plain_text(input: &str) -> String {
+ PlainTextFormatter::format_xml_text(ParsedXmlText::parse_lenient(input)).0
+}
+
+#[test]
+fn lenient_parse_unwraps_mentions_beside_stray_angle_brackets() {
+ let input = r#"Fixed Vec<String> for <m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention> when 5 < 10 in <m-document-mention>{"documentId":"doc-1","documentName":"the request","blockName":"channel","blockParams":{}}</m-document-mention>"#;
+ assert!(ParsedXmlText::parse(input).is_err());
+ assert_eq!(
+ lenient_plain_text(input),
+ "Fixed Vec<String> for [email protected] when 5 < 10 in the request"
+ );
+}
+
+#[test]
+fn lenient_parse_drops_unknown_tags_like_strict_parse() {
+ let input = r#"<m-await>{"text":"thinking"}</m-await>Done <m-await/>"#;
+ assert_eq!(lenient_plain_text(input), "Done ");
+}
+
+#[test]
+fn lenient_parse_keeps_a_malformed_mention_as_text() {
+ let input = r#"Hi <m-user-mention>invalid</m-user-mention>"#;
+ assert_eq!(lenient_plain_text(input), input);
+}
+
+#[test]
+fn lenient_parse_keeps_text_after_an_unclosed_tag_as_written() {
+ // One scan per unclosed tag would make this input quadratic to parse.
+ let input = "<m-link>x ".repeat(16 * 1024);
+ assert_eq!(lenient_plain_text(&input), input);
+}
+
+#[test]
+fn lenient_parse_of_valid_markup_matches_strict_parse() {
+ let input = r#"<m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention> see <m-link>{"text":"docs","url":"https://example.com"}</m-link>"#;
+ let strict = PlainTextFormatter::format_xml_text(ParsedXmlText::parse(input).unwrap()).0;
+ assert_eq!(lenient_plain_text(input), strict);
+}
diff --git a/crates/model_notifications/src/metadata.rs b/crates/model_notifications/src/metadata.rs
index 288369fa09..1f3cb65e30 100644
--- a/crates/model_notifications/src/metadata.rs
+++ b/crates/model_notifications/src/metadata.rs
@@ -1896,9 +1896,12 @@ impl Notification for AgentSessionMentionedMetadata {
const TYPE_NAME: &'static str = "agent_session_mentioned";
}
-/// The first `AGENT_EXCERPT_MAX_CHARS` of an agent's prose, on one line.
+/// The first `AGENT_EXCERPT_MAX_CHARS` of an agent's prose, on one line, with
+/// its Macro mention tags replaced by the names they show, as channel alerts
+/// do for messages.
fn agent_excerpt(text: &str) -> String {
- let flat = text.split_whitespace().collect::<Vec<_>>().join(" ");
+ let plain = PlainTextFormatter::format_xml_text(ParsedXmlText::parse_lenient(text)).0;
+ let flat = plain.split_whitespace().collect::<Vec<_>>().join(" ");
if flat.chars().count() <= AGENT_EXCERPT_MAX_CHARS {
return flat;
}
@@ -1919,10 +1922,12 @@ impl NotificationTitle for AgentSessionSettledMetadata {
&self,
_sender_id: Option<MacroUserIdStr<'_>>,
) -> Result<String, rootcause::Report> {
- Ok(match self.excerpt.as_deref().map(str::trim) {
- Some(excerpt) if !excerpt.is_empty() => agent_excerpt(excerpt),
- _ => self.session.session_name.clone(),
- })
+ Ok(self
+ .excerpt
+ .as_deref()
+ .map(agent_excerpt)
+ .filter(|excerpt| !excerpt.is_empty())
+ .unwrap_or_else(|| self.session.session_name.clone()))
}
}
diff --git a/crates/model_notifications/src/metadata/test.rs b/crates/model_notifications/src/metadata/test.rs
index 30e59b884f..5edb5beb50 100644
--- a/crates/model_notifications/src/metadata/test.rs
+++ b/crates/model_notifications/src/metadata/test.rs
@@ -1298,6 +1298,46 @@ fn agent_excerpt_flattens_whitespace_and_truncates() {
assert!(excerpt.ends_with('…'));
}
+#[test]
+fn agent_session_alerts_show_mentions_by_name() {
+ let settled = AgentSessionSettledMetadata {
+ session: agent_session_ref(),
+ turn: 0,
+ actor: None,
+ stop_reason: "end_turn".to_string(),
+ excerpt: Some(
+ r#"The most recent one was <m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention>, posted in <m-document-mention>{"documentId":"0195c94f-3b0c-79f0-8558-e5e509ac9dd8","documentName":"the request","blockName":"channel","blockParams":{}}</m-document-mention>; it returns Option<String>."#
+ .to_string(),
+ ),
+ };
+ assert_eq!(
+ settled.format_body(None).unwrap(),
+ "The most recent one was [email protected], posted in the request; it returns Option<String>."
+ );
+
+ let waiting = AgentSessionWaitingForInputMetadata {
+ session: agent_session_ref(),
+ turn: 0,
+ question: r#"Should I ask <m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention>?"#.to_string(),
+ };
+ assert_eq!(
+ waiting.format_body(None).unwrap(),
+ "Should I ask [email protected]?"
+ );
+}
+
+#[test]
+fn agent_session_settled_with_only_hidden_tags_falls_back_to_the_session_name() {
+ let metadata = AgentSessionSettledMetadata {
+ session: agent_session_ref(),
+ turn: 0,
+ actor: None,
+ stop_reason: "end_turn".to_string(),
+ excerpt: Some(r#"<m-await>{"text":"thinking"}</m-await>"#.to_string()),
+ };
+ assert_eq!(metadata.format_body(None).unwrap(), "Fix the flaky test");
+}
+
#[test]
fn calendar_email_reminder_escapes_content_and_limits_each_distinct_alarm() {
use notification::domain::models::NotificationExtEmail;