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(channel-bot): stop conflating ambient channel context with the triggering mention (#3988)
teo8dafe8adfe40
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 98deaa39b0..b43571912f 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -2105,6 +2105,7 @@ dependencies = ["futures","macro_user_id","models_pagination",+ "prompt","tokio","tracing","uuid",diff --git a/rust/cloud-storage/channel_bots/Cargo.toml b/rust/cloud-storage/channel_bots/Cargo.tomlindex dd0550d676..febf7eed80 100644--- a/rust/cloud-storage/channel_bots/Cargo.toml+++ b/rust/cloud-storage/channel_bots/Cargo.toml@@ -14,6 +14,7 @@ bot_id = { path = "../bot_id" }channels = { path = "../channels", features = ["inbound", "outbound"] }futures = { workspace = true }macro_user_id = { path = "../macro_user_id" }+prompt = { path = "../prompt" }tokio = { workspace = true, features = ["rt", "sync"] }tracing = { workspace = true }uuid = { workspace = true }diff --git a/rust/cloud-storage/channel_bots/src/domain/service.rs b/rust/cloud-storage/channel_bots/src/domain/service.rsindex 687167ee59..411c2de508 100644--- a/rust/cloud-storage/channel_bots/src/domain/service.rs+++ b/rust/cloud-storage/channel_bots/src/domain/service.rs@@ -1,11 +1,10 @@//! Domain service for built-in channel bots.+use std::collections::HashSet;use std::fmt::Write as _;use std::sync::Arc;-use channels::domain::models::{- ChannelContextMessage, ParticipantRole, PatchMessageRequest, PostMessageRequest, Sender,-};+use channels::domain::models::{ParticipantRole, PatchMessageRequest, PostMessageRequest, Sender};use channels::domain::ports::ChannelService;use uuid::Uuid;@@ -19,6 +18,21 @@ use super::ports::AgentResponder;const CONTEXT_MESSAGES_BEFORE: i64 = 4;const CONTEXT_MESSAGES_AFTER: i64 = 4;+/// Inline marker appended to the sender label of the triggering message so the+/// model can tell it apart from surrounding context.+const TRIGGER_MARKER: &str = " [this message mentioned you]";++const THREAD_INSTRUCTION: &str = "This is the thread you were mentioned in (oldest to newest). \+Interpret the mention in the context of this thread: words like \"this\" or \"it\" in the \+mention refer to this thread unless the mention says otherwise.";++const CHANNEL_BACKGROUND_INSTRUCTION: &str = "Other recent messages in the same channel, outside \+the thread above (oldest to newest). Background only — do not treat these as the subject of the \+mention.";++const CHANNEL_CONTEXT_INSTRUCTION: &str = "Recent messages in the channel around the mention \+(oldest to newest).";+/// Human-readable label for a message sender storage id.fn sender_label(sender_id: &str) -> String {if let Ok(bot) = bot_id::BotId::parse_storage_str(sender_id) {@@ -39,30 +53,37 @@ fn sender_label(sender_id: &str) -> String {.to_string()}-fn append_messages(- prompt: &mut String,- heading: &str,- messages: &[ChannelContextMessage],- skip: Uuid,-) {- let mut wrote_heading = false;- for message in messages {- if message.id == skip || message.deleted_at.is_some() || message.content.trim().is_empty() {- continue;- }- if !wrote_heading {- let _ = write!(prompt, "\n{heading}\n");- wrote_heading = true;- }- let _ = writeln!(- prompt,- "{}: {}",- sender_label(&message.sender_id),- message.content- );+/// A single message rendered into the prompt.+struct PromptLine {+ sender: String,+ content: String,+ is_trigger: bool,+}++/// The triggering message rendered from the event itself, used when the+/// trigger is missing from fetched context (e.g. a fetch failed).+fn trigger_line(event: &BotEvent) -> PromptLine {+ PromptLine {+ sender: sender_label(event.requesting_user.as_ref()),+ content: event.message.content.trim().to_string(),+ is_trigger: true,}}+/// Write a tagged context block: an instruction line followed by one message+/// per line, labeled by sender. Skipped entirely when there are no messages.+fn append_block(prompt: &mut String, tag: &str, instruction: &str, lines: &[PromptLine]) {+ if lines.is_empty() {+ return;+ }+ let _ = write!(prompt, "\n<{tag}>\n{instruction}\n\n");+ for line in lines {+ let marker = if line.is_trigger { TRIGGER_MARKER } else { "" };+ let _ = writeln!(prompt, "{}{marker}: {}", line.sender, line.content);+ }+ let _ = writeln!(prompt, "</{tag}>");+}+/// Message Macro posts immediately, then replaces with its answer.////// Rendered by the channel markdown as the existing pulsing AwaitNode.@@ -92,8 +113,67 @@ where}}- /// Build the prompt: who mentioned the agent, local channel context around- /// the triggering message, and the triggering message itself.+ /// Load the thread the mention belongs to as prompt lines: the top-level+ /// parent followed by all replies in order, with the triggering message+ /// marked inline. Also returns the ids of every message known to belong to+ /// the thread so they can be excluded from the channel background.+ async fn thread_lines(+ &self,+ event: &BotEvent,+ parent_id: Uuid,+ ) -> (Vec<PromptLine>, HashSet<Uuid>) {+ let mut thread_ids = HashSet::from([parent_id, event.message.id]);+ let mut lines = Vec::new();++ let parent = self+ .channels+ .get_message_context(event.channel_id, parent_id, 0, 0)+ .await+ .inspect_err(|err| tracing::warn!(error=?err, "failed to load thread parent"))+ .unwrap_or_default()+ .into_iter()+ .find(|message| message.id == parent_id);+ if let Some(parent) = parent+ && parent.deleted_at.is_none()+ && !parent.content.trim().is_empty()+ {+ lines.push(PromptLine {+ sender: sender_label(&parent.sender_id),+ content: parent.content.trim().to_string(),+ is_trigger: false,+ });+ }++ let replies = self+ .channels+ .get_thread_replies(event.channel_id, parent_id)+ .await+ .inspect_err(|err| tracing::warn!(error=?err, "failed to load thread replies"))+ .unwrap_or_default();+ for reply in replies {+ thread_ids.insert(reply.id);+ if reply.content.trim().is_empty() {+ continue;+ }+ lines.push(PromptLine {+ sender: sender_label(&reply.sender_id),+ content: reply.content.trim().to_string(),+ is_trigger: reply.id == event.message.id,+ });+ }+ if !lines.iter().any(|line| line.is_trigger) {+ lines.push(trigger_line(event));+ }+ (lines, thread_ids)+ }++ /// Build the prompt for a mention.+ ///+ /// When the mention is a thread reply, the thread (parent + replies) is the+ /// primary context and nearby channel messages are demoted to a clearly+ /// labeled background block. For a top-level mention, the chronological+ /// channel slice is the primary context. In both cases the triggering+ /// message is marked inline rather than repeated at the end.async fn build_prompt(&self, event: &BotEvent) -> String {let mentioner = sender_label(event.requesting_user.as_ref());let trigger_id = event.message.id;@@ -111,18 +191,59 @@ where.unwrap_or_default();let mut prompt = String::new();- let _ = writeln!(prompt, "{mentioner} mentioned you (@macro) in a channel.");- append_messages(- &mut prompt,- "Channel messages around the mention (oldest to newest):",- &nearby,- trigger_id,- );- let _ = write!(- prompt,- "\n{mentioner} said:\n{}\n\nReply to {mentioner}.",- event.message.content.trim()- );+ if let Some(parent_id) = event.message.thread_id {+ let _ = writeln!(+ prompt,+ "{mentioner} mentioned you (@macro) in a channel thread."+ );+ let (thread, thread_ids) = self.thread_lines(event, parent_id).await;+ append_block(&mut prompt, "thread", THREAD_INSTRUCTION, &thread);++ let background: Vec<PromptLine> = nearby+ .iter()+ .filter(|message| {+ message.deleted_at.is_none()+ && !message.content.trim().is_empty()+ && !thread_ids.contains(&message.id)+ && message.thread_id != Some(parent_id)+ })+ .map(|message| PromptLine {+ sender: sender_label(&message.sender_id),+ content: message.content.trim().to_string(),+ is_trigger: false,+ })+ .collect();+ append_block(+ &mut prompt,+ "channel_background",+ CHANNEL_BACKGROUND_INSTRUCTION,+ &background,+ );+ } else {+ let _ = writeln!(prompt, "{mentioner} mentioned you (@macro) in a channel.");+ let mut lines: Vec<PromptLine> = nearby+ .iter()+ .filter(|message| {+ message.deleted_at.is_none() && !message.content.trim().is_empty()+ })+ .map(|message| PromptLine {+ sender: sender_label(&message.sender_id),+ content: message.content.trim().to_string(),+ is_trigger: message.id == trigger_id,+ })+ .collect();+ if !lines.iter().any(|line| line.is_trigger) {+ lines.push(trigger_line(event));+ }+ append_block(+ &mut prompt,+ "channel_context",+ CHANNEL_CONTEXT_INSTRUCTION,+ &lines,+ );+ }++ let _ = write!(prompt, "\nReply to {mentioner}.");prompt}diff --git a/rust/cloud-storage/channel_bots/src/domain/service/tests.rs b/rust/cloud-storage/channel_bots/src/domain/service/tests.rsindex 7bbaa2563c..854ca0653f 100644--- a/rust/cloud-storage/channel_bots/src/domain/service/tests.rs+++ b/rust/cloud-storage/channel_bots/src/domain/service/tests.rs@@ -23,6 +23,7 @@ use crate::domain::{struct TestChannelService {around_args: Mutex<Option<(Uuid, Uuid, i64, i64)>>,around_messages: Vec<ChannelContextMessage>,+ thread_replies: Vec<ThreadReply>,}impl ChannelService for TestChannelService {@@ -62,7 +63,11 @@ impl ChannelService for TestChannelService {before: i64,after: i64,) -> impl Future<Output = Result<Vec<ChannelContextMessage>, ChannelMessagesErr>> + Send {- *self.around_args.lock().unwrap() = Some((channel_id, message_id, before, after));+ // Record only the wide context fetch; the thread-parent lookup uses+ // a zero-width window.+ if before > 0 || after > 0 {+ *self.around_args.lock().unwrap() = Some((channel_id, message_id, before, after));+ }let messages = self.around_messages.clone();async move { Ok(messages) }}@@ -91,7 +96,8 @@ impl ChannelService for TestChannelService {_channel_id: Uuid,_message_id: Uuid,) -> impl Future<Output = Result<Vec<ThreadReply>, ChannelMessagesErr>> + Send {- async move { unimplemented!("not needed for prompt tests") }+ let replies = self.thread_replies.clone();+ async move { Ok(replies) }}fn resolve_message(@@ -137,8 +143,49 @@ fn context_message(}}+fn thread_reply(id: Uuid, sender_id: &str, content: &str) -> ThreadReply {+ let now = Utc::now();+ ThreadReply {+ id,+ sender_id: sender_id.to_string(),+ bot_profile: None,+ content: content.to_string(),+ created_at: now,+ updated_at: now,+ edited_at: None,+ reactions: Vec::new(),+ attachments: Vec::new(),+ }+}++fn mention_event(+ channel_id: Uuid,+ trigger_id: Uuid,+ thread_id: Option<Uuid>,+ sender_email: &str,+ content: &str,+) -> BotEvent {+ BotEvent {+ trigger: BotTrigger::Mention,+ channel_id,+ message: MutatedMessage {+ id: trigger_id,+ channel_id,+ thread_id,+ sender_id: Sender::User(user_id(sender_email)),+ content: content.to_string(),+ created_at: Utc::now(),+ updated_at: Utc::now(),+ edited_at: None,+ deleted_at: None,+ },+ reply_thread_id: thread_id.unwrap_or(trigger_id),+ requesting_user: user_id(sender_email),+ }+}+#[tokio::test]-async fn prompt_uses_local_context_around_trigger() {+async fn top_level_prompt_marks_trigger_inline_in_channel_context() {let channel_id = Uuid::new_v4();let trigger_id = Uuid::new_v4();let before_id = Uuid::new_v4();@@ -155,25 +202,16 @@ async fn prompt_uses_local_context_around_trigger() {),context_message(channel_id, after_id, "macro|[email protected]", "after"),],+ thread_replies: Vec::new(),});let handler = MacroAiHandler::new(channels.clone(), Arc::new(TestResponder));- let event = BotEvent {- trigger: BotTrigger::Mention,+ let event = mention_event(channel_id,- message: MutatedMessage {- id: trigger_id,- channel_id,- thread_id: None,- sender_id: Sender::User(user_id("[email protected]")),- content: "@macro help".to_string(),- created_at: Utc::now(),- updated_at: Utc::now(),- edited_at: None,- deleted_at: None,- },- reply_thread_id: trigger_id,- requesting_user: user_id("[email protected]"),- };+ trigger_id,+ None,+ "[email protected]",+ "@macro help",+ );let prompt = handler.build_prompt(&event).await;@@ -186,11 +224,131 @@ async fn prompt_uses_local_context_around_trigger() {CONTEXT_MESSAGES_AFTER)));- assert!(prompt.contains("Channel messages around the mention"));+ assert!(prompt.contains("mentioned you (@macro) in a channel."));+ assert!(prompt.contains("<channel_context>"));+ assert!(prompt.contains("</channel_context>"));assert!(prompt.contains("alice: before"));assert!(prompt.contains("bob: after"));- assert!(!prompt.contains("teo: @macro help"));- assert!(prompt.contains("teo said:\n@macro help"));- assert!(!prompt.contains("Recent channel messages"));- assert!(!prompt.contains("Messages in the thread"));+ assert!(prompt.contains("teo [this message mentioned you]: @macro help"));+ // The trigger appears once, inline, not repeated at the end.+ assert_eq!(prompt.matches("@macro help").count(), 1);+ assert!(!prompt.contains("<thread>"));+ assert!(prompt.ends_with("Reply to teo."));+}++#[tokio::test]+async fn thread_prompt_puts_thread_first_and_demotes_channel_noise() {+ let channel_id = Uuid::new_v4();+ let parent_id = Uuid::new_v4();+ let trigger_id = Uuid::new_v4();+ let unrelated_id = Uuid::new_v4();++ let mut trigger_context = context_message(+ channel_id,+ trigger_id,+ "macro|[email protected]",+ "@macro can you make a task out of this?",+ );+ trigger_context.thread_id = Some(parent_id);++ let channels = Arc::new(TestChannelService {+ around_args: Mutex::new(None),+ around_messages: vec![+ context_message(+ channel_id,+ parent_id,+ "macro|[email protected]",+ "We stopped persisting filter/sort across refresh",+ ),+ context_message(+ channel_id,+ unrelated_id,+ "macro|[email protected]",+ "unrelated tasks view chatter",+ ),+ trigger_context,+ ],+ thread_replies: vec![thread_reply(+ trigger_id,+ "macro|[email protected]",+ "@macro can you make a task out of this?",+ )],+ });+ let handler = MacroAiHandler::new(channels.clone(), Arc::new(TestResponder));+ let event = mention_event(+ channel_id,+ trigger_id,+ Some(parent_id),+ "[email protected]",+ "@macro can you make a task out of this?",+ );++ let prompt = handler.build_prompt(&event).await;++ assert!(prompt.contains("austin mentioned you (@macro) in a channel thread."));++ // Thread block comes first and contains parent + marked trigger.+ let thread_start = prompt.find("<thread>").expect("thread block");+ let thread_end = prompt.find("</thread>").expect("thread block end");+ let thread_block = &prompt[thread_start..thread_end];+ assert!(thread_block.contains("peter: We stopped persisting filter/sort across refresh"));+ assert!(+ thread_block.contains(+ "austin [this message mentioned you]: @macro can you make a task out of this?"+ )+ );+ assert!(!thread_block.contains("carol"));++ // Channel noise is demoted to the background block, with thread messages excluded.+ let background_start = prompt+ .find("<channel_background>")+ .expect("background block");+ assert!(background_start > thread_end);+ let background_end = prompt+ .find("</channel_background>")+ .expect("background end");+ let background_block = &prompt[background_start..background_end];+ assert!(background_block.contains("carol: unrelated tasks view chatter"));+ assert!(!background_block.contains("peter:"));+ assert!(!background_block.contains("austin"));++ // The trigger appears exactly once across the whole prompt.+ assert_eq!(+ prompt+ .matches("@macro can you make a task out of this?")+ .count(),+ 1+ );+ assert!(prompt.ends_with("Reply to austin."));+}++#[tokio::test]+async fn thread_prompt_includes_trigger_when_reply_fetch_fails_to_return_it() {+ let channel_id = Uuid::new_v4();+ let parent_id = Uuid::new_v4();+ let trigger_id = Uuid::new_v4();++ let channels = Arc::new(TestChannelService {+ around_args: Mutex::new(None),+ around_messages: vec![context_message(+ channel_id,+ parent_id,+ "macro|[email protected]",+ "parent message",+ )],+ thread_replies: Vec::new(),+ });+ let handler = MacroAiHandler::new(channels.clone(), Arc::new(TestResponder));+ let event = mention_event(+ channel_id,+ trigger_id,+ Some(parent_id),+ "[email protected]",+ "@macro help with this",+ );++ let prompt = handler.build_prompt(&event).await;++ assert!(prompt.contains("peter: parent message"));+ assert!(prompt.contains("austin [this message mentioned you]: @macro help with this"));}diff --git a/rust/cloud-storage/channel_bots/src/outbound/agent_loop_responder.rs b/rust/cloud-storage/channel_bots/src/outbound/agent_loop_responder.rsindex 4acfd7e1fe..92ce9b7ad1 100644--- a/rust/cloud-storage/channel_bots/src/outbound/agent_loop_responder.rs+++ b/rust/cloud-storage/channel_bots/src/outbound/agent_loop_responder.rs@@ -10,12 +10,6 @@ use macro_user_id::user_id::MacroUserIdStr;use crate::domain::ports::AgentResponder;-const CHANNEL_SYSTEM_PROMPT: &str = "You are Macro, a helpful assistant participating in a Macro channel. \-You were mentioned in a message and are replying in a thread. The prompt includes channel \-messages around the mention for context, labeled by sender. \-Be concise and directly useful. Use your tools to look things up when helpful. \-Respond in Markdown.";-/// [`AgentResponder`] backed by the in-process agent loop and AI toolset.pub struct AgentLoopResponder {agent_loop: AgentLoop,@@ -31,7 +25,7 @@ impl AgentLoopResponder {agent_loop: AgentLoop::new(),tool_context: Arc::new(tool_context),toolset: tools.toolset,- system_prompt: format!("{CHANNEL_SYSTEM_PROMPT}\n\n{}", tools.prompt),+ system_prompt: format!("{}{}", prompt::channel_mention::PROMPT, tools.prompt),}}}diff --git a/rust/cloud-storage/channels/src/domain/models.rs b/rust/cloud-storage/channels/src/domain/models.rsindex 331b4b5c15..0e30f1ec61 100644--- a/rust/cloud-storage/channels/src/domain/models.rs+++ b/rust/cloud-storage/channels/src/domain/models.rs@@ -266,7 +266,7 @@ pub struct ThreadInfo {}/// A reply shown in a thread preview.-#[derive(Debug)]+#[derive(Debug, Clone)]pub struct ThreadReply {/// Reply id.pub id: Uuid,diff --git a/rust/cloud-storage/prompt/src/channel_mention.rs b/rust/cloud-storage/prompt/src/channel_mention.rsnew file mode 100644index 0000000000..3ca6f205f7--- /dev/null+++ b/rust/cloud-storage/prompt/src/channel_mention.rs@@ -0,0 +1,23 @@+//! Behavior for the Macro channel bot when it is `@`-mentioned.++use crate::types::StaticPrompt;++static TITLE: &str = "Channel Mentions";++static INSTRUCTIONS: &str = r##"You are Macro, a helpful assistant participating in a Macro channel. You were mentioned in a message and are replying in a thread. The message that mentioned you is marked inline in the prompt.++Context is grouped into tagged blocks:++- `<thread>` is the conversation the mention belongs to and is authoritative for interpreting the request.+- `<channel_background>` is unrelated nearby channel activity, for background only.+- `<channel_context>` (when there is no thread) is the recent channel conversation around the mention.++Be concise and directly useful. Use your tools to look things up when helpful.+Respond in Markdown.+"##;++static INTENT: &str = "The model replies to the marked mention, treats the <thread> block as \+authoritative over <channel_background> noise, and answers concisely in Markdown.";++/// The channel-mention prompt for the Macro channel bot.+pub static PROMPT: StaticPrompt<'static> = StaticPrompt::borrowed(TITLE, INSTRUCTIONS, INTENT);diff --git a/rust/cloud-storage/prompt/src/lib.rs b/rust/cloud-storage/prompt/src/lib.rsindex 406748aaf5..601a3aa8c8 100644--- a/rust/cloud-storage/prompt/src/lib.rs+++ b/rust/cloud-storage/prompt/src/lib.rs@@ -6,6 +6,7 @@#![deny(missing_docs)]pub mod about_macro;+pub mod channel_mention;pub mod citations;pub mod do_not;pub mod math;