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(agent-context): include thread attachments in mention prompts (#8121)
Wolf Mermelstein0327060f362a
diff --git a/crates/agent_harness/AGENTS.md b/crates/agent_harness/AGENTS.mdindex 3fa1c7a71e..4cce8e994e 100644--- a/crates/agent_harness/AGENTS.md+++ b/crates/agent_harness/AGENTS.md@@ -86,6 +86,15 @@ wakes; interrupted quiet batches return to the next real prompt.unset). Use CI's process isolation for the full database-backed suite so eachtest has its own process and runtime.+## Gotchas++- A session's first prompt carries static files from the mentioning message+ and the rest of its thread (mention first, then root and replies), capped+ at 8 and deduped by file id; follow-ups carry only their own files.+ Background channel messages are not attached. `trigger_router` fills each+ context attachment's `url` from `StaticFileLinks`, and `<m-agent-context>`+ lists them per message; ACP `resource_link`s are what vision models fetch.+## Related- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/security.md`diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rsindex 4f73204a13..d47fb775c6 100644--- a/crates/agent_harness/src/domain/model.rs+++ b/crates/agent_harness/src/domain/model.rs@@ -1,5 +1,7 @@//! Commands and values used by the harness domain.+use std::collections::HashSet;+use agent_client_protocol::schema::v1::{HttpHeader, McpServer as AcpMcpServer, McpServerHttp};use agent_egress::domain::model::{CUSTOM_MCP_PATH_PREFIX, CustomMcpServerKey, CustomMcpServerListing, McpServerSlug, RepoSlug,@@ -39,6 +41,9 @@ impl StaticFileLinks {const STATIC_IMAGE: &str = "static/image";/// Channel attachment entity type for a video stored as a static file.const STATIC_VIDEO: &str = "static/video";+ /// How many files ride a prompt as ACP resource links. Matches the MCP+ /// channel-image budget so a long thread cannot flood the first turn.+ const MAX_PROMPT_ATTACHMENTS: usize = 8;/// Links under the static file service at `base_url`.#[must_use]@@ -50,36 +55,83 @@ impl StaticFileLinks {Self { base_url }}- /// The prompt attachment for a channel attachment, or `None` for one that- /// is not a static file - documents reach the agent through mentions,- /// and have no URL an agent could fetch unauthenticated.+ /// The prompt attachment for a static file, or `None` for one that is not+ /// a static file - documents reach the agent through mentions, and have+ /// no URL an agent could fetch unauthenticated.////// Channel rows record only that a file is an image or a video, not its/// exact type, so the media type is the matching wildcard range.#[must_use]- pub fn prompt_attachment(- &self,- attachment: &MessageEventAttachment,- ) -> Option<PromptAttachment> {- let (kind, mime_type) = match attachment.entity_type.as_str() {+ fn file_link(&self, entity_type: &str, entity_id: &str) -> Option<PromptAttachment> {+ let (kind, mime_type) = match entity_type {Self::STATIC_IMAGE => ("image", "image/*"),Self::STATIC_VIDEO => ("video", "video/*"),_ => return None,};- let uri = format!("{}/file/{}", self.base_url, attachment.entity_id);+ let uri = format!("{}/file/{}", self.base_url, entity_id);Some(PromptAttachment::new(uri, kind).mime_type(mime_type))}- /// The prompt attachments for a message's attached files, in order.+ /// Files to send with a prompt: the mentioning message first, then the+ /// rest of its thread. Deduped by entity id and capped so a long thread+ /// cannot flood the first turn.#[must_use]- pub fn prompt_attachments(+ pub fn prompt_attachments_for(&self,- attachments: &[MessageEventAttachment],+ mention: &[MessageEventAttachment],+ context: Option<&TriggerContext>,) -> Vec<PromptAttachment> {- attachments- .iter()- .filter_map(|attachment| self.prompt_attachment(attachment))- .collect()+ let mut seen = HashSet::new();+ let mut out = Vec::new();+ for attachment in mention {+ self.push_prompt_attachment(+ &mut out,+ &mut seen,+ &attachment.entity_type,+ &attachment.entity_id,+ );+ }+ if let Some(discussion) = context.and_then(TriggerContext::discussion) {+ for attachment in discussion.prompt_thread_attachments() {+ self.push_prompt_attachment(+ &mut out,+ &mut seen,+ &attachment.entity_type,+ &attachment.entity_id,+ );+ }+ }+ out+ }++ /// Give every static file in the trigger's discussion the URL the agent+ /// fetches it from, so the prompt XML can name it.+ pub fn link_context_attachments(&self, context: Option<&mut TriggerContext>) {+ let Some(discussion) = context.and_then(TriggerContext::discussion_mut) else {+ return;+ };+ for attachment in discussion.attachments_mut() {+ attachment.url = self+ .file_link(&attachment.entity_type, &attachment.entity_id)+ .map(|link| link.uri);+ }+ }++ fn push_prompt_attachment(+ &self,+ out: &mut Vec<PromptAttachment>,+ seen: &mut HashSet<String>,+ entity_type: &str,+ entity_id: &str,+ ) {+ if out.len() >= Self::MAX_PROMPT_ATTACHMENTS || seen.contains(entity_id) {+ return;+ }+ let Some(link) = self.file_link(entity_type, entity_id) else {+ return;+ };+ seen.insert(entity_id.to_owned());+ out.push(link);}}diff --git a/crates/agent_harness/src/domain/trigger_router.rs b/crates/agent_harness/src/domain/trigger_router.rsindex 4e0c31572c..07816c8029 100644--- a/crates/agent_harness/src/domain/trigger_router.rs+++ b/crates/agent_harness/src/domain/trigger_router.rs@@ -72,6 +72,10 @@ pub fn route_agent_trigger(.as_user().cloned().ok_or(Skipped::NotFromUser)?;+ let mut context = event.context;+ links.link_context_attachments(context.as_mut());+ let attachments =+ links.prompt_attachments_for(&event.message.attachments, context.as_ref());Ok(RoutedTrigger::Command(event.session_id,HarnessCommand::ConversationMessage(OpenSession {@@ -84,8 +88,8 @@ pub fn route_agent_trigger(message_id: event.message.message_id,sender,content: event.message.content,- attachments: links.prompt_attachments(&event.message.attachments),- context: event.context,+ attachments,+ context,}),}),))@@ -119,7 +123,7 @@ pub fn route_agent_trigger(let Some(OpeningMention {bot_id,message,- context,+ mut context,}) = event.mention()else {return Err(Skipped::Unrecognized);@@ -132,6 +136,8 @@ pub fn route_agent_trigger(.as_user().cloned().ok_or(Skipped::NotFromUser)?;+ links.link_context_attachments(context.as_mut());+ let attachments = links.prompt_attachments_for(&message.attachments, context.as_ref());Ok(RoutedTrigger::Command(AgentSessionId::new(),HarnessCommand::Open(OpenSession {@@ -146,7 +152,7 @@ pub fn route_agent_trigger(message_id: message.message_id,sender,content: message.content,- attachments: links.prompt_attachments(&message.attachments),+ attachments,context,}),}),@@ -158,7 +164,7 @@ pub fn route_agent_trigger(session_id,kind: _,message,- context,+ mut context,}) = event.session_message()else {return Err(Skipped::Unrecognized);@@ -173,16 +179,16 @@ pub fn route_agent_trigger(let kind = runtime.as_ref().map_or(AgentKind::External, |runtime| runtime.kind);+ links.link_context_attachments(context.as_mut());if kind.is_managed() {+ // The session already saw its thread's files on its first turn.+ let attachments = links.prompt_attachments_for(&message.attachments, None);return Ok(RoutedTrigger::Command(session_id,HarnessCommand::Deliver(DeliverAction {context,..DeliverAction::prompt(- AgentAction::prompt_with_attachments(- message.content,- links.prompt_attachments(&message.attachments),- ),+ AgentAction::prompt_with_attachments(message.content, attachments),message.sender.as_user().cloned(),Some(origin),)diff --git a/crates/agent_harness/src/inbound/kafka/test.rs b/crates/agent_harness/src/inbound/kafka/test.rsindex d7b5fdb740..2a28660ba2 100644--- a/crates/agent_harness/src/inbound/kafka/test.rs+++ b/crates/agent_harness/src/inbound/kafka/test.rs@@ -15,8 +15,9 @@ use macro_uuid::Uuid;use messages::domain::events::MessagePostedMetadata;use messages::domain::models::MessageParent;use trigger_context::{- AddressedBy, ContextPerson, DiscussionContext, DiscussionSurface, FollowUpContext, ReplyTarget,- TaskAssignedContext, TaskSnapshot, TriggerContext,+ AddressedBy, ContextAttachment, ContextMessage, ContextPerson, ContextThread,+ DiscussionContext, DiscussionSurface, FollowUpContext, ReplyTarget, TaskAssignedContext,+ TaskSnapshot, TriggerContext,};use super::*;@@ -571,6 +572,66 @@ fn message_with_files(sender: ChannelSender<'static>) -> ChannelMessagePostedMet}}+fn julia() -> ContextPerson {+ ContextPerson {+ id: "macro|[email protected]".to_owned(),+ name: "Julia".to_owned(),+ email: Some("[email protected]".to_owned()),+ }+}++fn context_message(id: u128, content: &str, attachments: Vec<ContextAttachment>) -> ContextMessage {+ ContextMessage {+ id: Uuid::from_u128(id),+ author: julia(),+ content: content.to_owned(),+ posted_at: Utc::now(),+ attachments,+ }+}++fn image_attachment(entity_id: &str) -> ContextAttachment {+ ContextAttachment {+ entity_type: "static/image".to_owned(),+ entity_id: entity_id.to_owned(),+ url: None,+ }+}++/// A mention whose own message has no files, on a thread whose root does.+fn thread_root_image_context(root_file: &str) -> TriggerContext {+ TriggerContext::Mentioned(DiscussionContext {+ surface: DiscussionSurface::Channel {+ id: Uuid::from_u128(1),+ name: Some("eng".to_owned()),+ channel_type: trigger_context::ChannelType::Public,+ },+ prompt_message_id: Uuid::from_u128(2),+ sender: julia(),+ reply_target: ReplyTarget::Thread {+ root_id: Uuid::from_u128(1),+ },+ thread: Some(ContextThread {+ root_id: Uuid::from_u128(1),+ messages: vec![+ context_message(+ 1,+ "We need agent templates",+ vec![image_attachment(root_file)],+ ),+ context_message(2, "@cursor look", vec![]),+ ],+ messages_omitted: false,+ }),+ channel: Vec::new(),+ })+}++fn image_link(entity_id: Uuid) -> PromptAttachment {+ PromptAttachment::new(format!("https://static.example/file/{entity_id}"), "image")+ .mime_type("image/*")+}+/// The files a message carries reach the agent with its words - as links/// it can fetch, since the static file service is where the bytes live.#[test]@@ -631,6 +692,119 @@ fn a_managed_channel_message_with_files_delivers_them_as_prompt_attachments() {assert_eq!(prompt.attachments[1].mime_type.as_deref(), Some("video/*"));}+#[test]+fn a_mention_without_files_still_carries_the_thread_root_image() {+ const ROOT_FILE: &str = "9ec21122-4bd8-473f-bfb0-21d2e6e5f03b";+ let event = AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(+ AgentBotMentionedEvent {+ bot_id: BotId::TEST_A,+ message: message(ChannelSender::new_from_user(user())),+ context: Some(thread_root_image_context(ROOT_FILE)),+ },+ ));+ let routed = route_agent_trigger(event, runtime(AgentKind::InMemory), &links()).unwrap();+ let RoutedTrigger::Command(_, HarnessCommand::Open(open)) = routed else {+ panic!("a new-session event should open");+ };+ assert_eq!(+ mention_origin(&open).attachments,+ vec![+ PromptAttachment::new(format!("https://static.example/file/{ROOT_FILE}"), "image",)+ .mime_type("image/*")+ ]+ );+}++#[test]+fn a_mention_image_is_listed_before_the_thread_root_and_deduped() {+ let mention_id = Uuid::from_u128(0x10);+ let root_id = Uuid::from_u128(0x20);+ let mut posted = message_with_files(ChannelSender::new_from_user(user()));+ posted.attachments.truncate(1);+ let mut context = thread_root_image_context(&root_id.to_string());+ if let TriggerContext::Mentioned(discussion) = &mut context {+ discussion.thread.as_mut().unwrap().messages[1]+ .attachments+ .push(image_attachment(&mention_id.to_string()));+ }+ let event = AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(+ AgentBotMentionedEvent {+ bot_id: BotId::TEST_A,+ message: posted,+ context: Some(context),+ },+ ));+ let routed = route_agent_trigger(event, runtime(AgentKind::InMemory), &links()).unwrap();+ let RoutedTrigger::Command(_, HarnessCommand::Open(open)) = routed else {+ panic!("a new-session event should open");+ };+ assert_eq!(+ mention_origin(&open).attachments,+ vec![image_link(mention_id), image_link(root_id)]+ );+}++/// The session saw its thread's files on its first turn; a follow-up only+/// sends its own, while the context still names every file by URL.+#[test]+fn a_follow_up_sends_only_its_own_files_and_links_the_thread_in_context() {+ const ROOT_FILE: &str = "9ec21122-4bd8-473f-bfb0-21d2e6e5f03b";+ let event = AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(+ ChannelEventMetadata {+ bot_id: MACRO_CODER_BOT_ID,+ session_id: AgentSessionId::TEST_A,+ kind: ThreadMessageKind::MentionThread,+ message: message(ChannelSender::new_from_user(user())),+ context: Some(thread_root_image_context(ROOT_FILE)),+ },+ ));+ let routed = route_agent_trigger(event, runtime(AgentKind::SandboxedCoder), &links()).unwrap();+ let RoutedTrigger::Command(_, HarnessCommand::Deliver(deliver)) = routed else {+ panic!("a managed existing-session event should deliver");+ };+ let AgentAction::Prompt(prompt) = deliver.action else {+ panic!("a channel message becomes a prompt");+ };+ assert_eq!(prompt.attachments, vec![]);+ let Some(TriggerContext::Mentioned(discussion)) = deliver.context else {+ panic!("the context travels with the prompt");+ };+ assert_eq!(+ discussion.thread.unwrap().messages[0].attachments,+ vec![ContextAttachment {+ entity_type: "static/image".to_owned(),+ entity_id: ROOT_FILE.to_owned(),+ url: Some(format!("https://static.example/file/{ROOT_FILE}")),+ }]+ );+}++#[test]+fn thread_files_on_a_prompt_cap_at_eight() {+ let mut context = thread_root_image_context(&Uuid::from_u128(0).to_string());+ if let TriggerContext::Mentioned(discussion) = &mut context {+ discussion.thread.as_mut().unwrap().messages[0].attachments = (0..10)+ .map(|index| image_attachment(&Uuid::from_u128(index).to_string()))+ .collect();+ }+ let event = AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(+ AgentBotMentionedEvent {+ bot_id: BotId::TEST_A,+ message: message(ChannelSender::new_from_user(user())),+ context: Some(context),+ },+ ));+ let routed = route_agent_trigger(event, runtime(AgentKind::InMemory), &links()).unwrap();+ let RoutedTrigger::Command(_, HarnessCommand::Open(open)) = routed else {+ panic!("a new-session event should open");+ };+ assert_eq!(mention_origin(&open).attachments.len(), 8);+ assert_eq!(+ mention_origin(&open).attachments[0].uri,+ format!("https://static.example/file/{}", Uuid::from_u128(0))+ );+}+#[test]fn conversation_messages_route_to_every_configured_runtime() {let session_id = AgentSessionId::TEST_A;@@ -659,3 +833,28 @@ fn conversation_messages_route_to_every_configured_runtime() {assert_eq!(open.runtime.kind, kind);}}++#[test]+fn a_conversation_message_without_files_still_carries_the_thread_root_image() {+ const ROOT_FILE: &str = "9ec21122-4bd8-473f-bfb0-21d2e6e5f03b";+ let session_id = AgentSessionId::TEST_A;+ let event = AgentTriggerTopicEvent::New(NewAgentSessionEvent::ConversationMessage(+ AgentConversationMessageEvent {+ bot_id: BotId::TEST_A,+ session_id,+ message: document_message(ChannelSender::new_from_user(user())),+ context: Some(thread_root_image_context(ROOT_FILE)),+ },+ ));+ let routed = route_agent_trigger(event, runtime(AgentKind::InMemory), &links()).unwrap();+ let RoutedTrigger::Command(_, HarnessCommand::ConversationMessage(open)) = routed else {+ panic!("a conversation message should reach its reserved session");+ };+ assert_eq!(+ mention_origin(&open).attachments,+ vec![+ PromptAttachment::new(format!("https://static.example/file/{ROOT_FILE}"), "image")+ .mime_type("image/*")+ ]+ );+}diff --git a/crates/agent_trigger/AGENTS.md b/crates/agent_trigger/AGENTS.mdindex 217a5f6546..8d7bdb1a6b 100644--- a/crates/agent_trigger/AGENTS.md+++ b/crates/agent_trigger/AGENTS.md@@ -14,7 +14,9 @@ session that results.- `src/domain/sources.rs`: the trigger sources (explicit mention, implicitreply, task/project assignment).- `src/domain/context.rs`: structured context assembled for the agent- prompt (thread history, people, discussion).+ prompt (thread history, people, discussion). Message attachments travel on+ each `ContextMessage` so the prompt XML and ACP file links can see files+ that were not on the mentioning message.- `src/domain/task_assignment.rs` / `src/domain/project_assignment.rs`:non-message trigger paths.- `src/outbound/fast_model_judge.rs`: the Haiku-class implicit-triggerdiff --git a/crates/agent_trigger/src/domain/broker_events/test.rs b/crates/agent_trigger/src/domain/broker_events/test.rsindex d906121ceb..1fcbc08283 100644--- a/crates/agent_trigger/src/domain/broker_events/test.rs+++ b/crates/agent_trigger/src/domain/broker_events/test.rs@@ -394,6 +394,7 @@ fn a_conversation_turn_carries_its_trigger_without_the_channel() {author: person,content: "an earlier turn".to_owned(),posted_at: Utc::now(),+ attachments: Vec::new(),}],messages_omitted: false,}],diff --git a/crates/agent_trigger/src/outbound/discussion_context.rs b/crates/agent_trigger/src/outbound/discussion_context.rsindex 7066803d22..0ee0bcee29 100644--- a/crates/agent_trigger/src/outbound/discussion_context.rs+++ b/crates/agent_trigger/src/outbound/discussion_context.rs@@ -24,8 +24,8 @@ use messages::domain::{service::MessageView,};use trigger_context::{- ChannelType, CommentAnchor, ContextMessage, ContextPerson, ContextThread, DiscussionContext,- DiscussionSurface, MarkedPassage, ReplyTarget,+ ChannelType, CommentAnchor, ContextAttachment, ContextMessage, ContextPerson, ContextThread,+ DiscussionContext, DiscussionSurface, MarkedPassage, ReplyTarget,};use crate::domain::{@@ -665,6 +665,15 @@ impl Authors {author: self.author(message),content: message.content.trim().to_owned(),posted_at: message.created_at,+ attachments: message+ .attachments+ .iter()+ .map(|attachment| ContextAttachment {+ entity_type: attachment.entity_type.clone(),+ entity_id: attachment.entity_id.clone(),+ url: None,+ })+ .collect(),}}diff --git a/crates/agent_trigger/src/outbound/discussion_context/test.rs b/crates/agent_trigger/src/outbound/discussion_context/test.rsindex 9dfdb15bb9..7b305790f1 100644--- a/crates/agent_trigger/src/outbound/discussion_context/test.rs+++ b/crates/agent_trigger/src/outbound/discussion_context/test.rs@@ -4,8 +4,9 @@ use entity_access::domain::models::{AccessLevel, Entity, EntityPermission};use macro_user_id::user_id::MacroUserIdStr;use messages::domain::{api::MockMessageReader,- models::{BotSenderProfile, ImportedAuthor, MessageThread, ThreadState},+ models::{BotSenderProfile, ImportedAuthor, MessageAttachment, MessageThread, ThreadState},};+use trigger_context::ContextAttachment;/// The lexical service's lookups, each answering one fixed result.struct Lexical {@@ -149,6 +150,15 @@ fn entry(message: &Message) -> ContextMessage {author: person(message.sender_id.as_user().unwrap().email_str()),content: message.content.clone(),posted_at: message.created_at,+ attachments: message+ .attachments+ .iter()+ .map(|attachment| ContextAttachment {+ entity_type: attachment.entity_type.clone(),+ entity_id: attachment.entity_id.clone(),+ url: None,+ })+ .collect(),}}@@ -276,6 +286,7 @@ async fn a_document_comment_carries_its_whole_thread_through_the_prompt() {},content: "is this right?".to_owned(),posted_at: at(0),+ attachments: Vec::new(),},ContextMessage {id: Uuid::from_u128(2),@@ -286,6 +297,7 @@ async fn a_document_comment_carries_its_whole_thread_through_the_prompt() {},content: "@agent explain this paragraph".to_owned(),posted_at: at(5),+ attachments: Vec::new(),},],messages_omitted: false,@@ -295,6 +307,49 @@ async fn a_document_comment_carries_its_whole_thread_through_the_prompt() {);}+#[tokio::test]+async fn a_thread_root_image_travels_on_its_context_message() {+ let parent = document();+ let mut root = posted(&parent, 1, None, "[email protected]", "is this right?", 0);+ root.attachments = vec![MessageAttachment {+ id: Uuid::from_u128(9),+ entity_type: "static/image".to_owned(),+ entity_id: "9ec21122-4bd8-473f-bfb0-21d2e6e5f03b".to_owned(),+ width: None,+ height: None,+ created_at: at(0),+ }];+ let prompt = comment(&parent);+ let mut source = MockMessageReader::new();+ let prompt_message = prompt.clone();+ source+ .expect_get()+ .withf(|_, id| *id == Uuid::from_u128(2))+ .returning(move |_, _| Ok(prompt_message.clone()));+ source.expect_preceding().never();+ let expected = parent.entity_id();+ let thread_replies = vec![prompt.clone()];+ source+ .expect_get_thread()+ .once()+ .withf(move |access, root_id| {+ access.entity().entity_id == expected && *root_id == Uuid::from_u128(1)+ })+ .return_once(move |_, _| Ok(discussion(root, thread_replies, None)));++ let context = context_from(source, document_names(), Lexical::none(), &prompt).await;+ let thread = context.thread.expect("a comment has a thread");+ assert_eq!(+ thread.messages[0].attachments,+ [ContextAttachment {+ entity_type: "static/image".to_owned(),+ entity_id: "9ec21122-4bd8-473f-bfb0-21d2e6e5f03b".to_owned(),+ url: None,+ }]+ );+ assert!(thread.messages[1].attachments.is_empty());+}+/// "please fix" in thread A, posted while another thread was busier. The/// agent must get thread A whole and be told the rest is background, not a/// flat list whose last entry is someone else's bug.@@ -537,6 +592,7 @@ async fn deleted_blank_imported_and_bot_messages_read_as_their_authors_wrote_the},content: "from slack".to_owned(),posted_at: at(2),+ attachments: Vec::new(),}],messages_omitted: false,},@@ -551,6 +607,7 @@ async fn deleted_blank_imported_and_bot_messages_read_as_their_authors_wrote_the},content: "deployed v2".to_owned(),posted_at: at(3),+ attachments: Vec::new(),}],messages_omitted: false,},@@ -629,6 +686,7 @@ async fn a_quote_reply_carries_the_quoted_message_even_outside_the_window() {},content: "the spinner never stops".to_owned(),posted_at: at(0),+ attachments: Vec::new(),}),});diff --git a/crates/scheduled_action/src/outbound/event_content/routine_event.rs b/crates/scheduled_action/src/outbound/event_content/routine_event.rsindex ad851de66f..6ba083f20b 100644--- a/crates/scheduled_action/src/outbound/event_content/routine_event.rs+++ b/crates/scheduled_action/src/outbound/event_content/routine_event.rs@@ -18,9 +18,9 @@ use properties::EntityPropertyInfo;use rootcause::Report;use system_properties::SystemPropertyKey;use trigger_context::{- CallSnapshot, CallStartedSnapshot, ChannelType, ContextMessage, ContextPerson, ContextThread,- DiscussionContext, DiscussionSurface, DocumentSnapshot, EmailSnapshot, ReplyTarget,- RoutineEvent, TaskSnapshot, TranscriptLine,+ CallSnapshot, CallStartedSnapshot, ChannelType, ContextAttachment, ContextMessage,+ ContextPerson, ContextThread, DiscussionContext, DiscussionSurface, DocumentSnapshot,+ EmailSnapshot, ReplyTarget, RoutineEvent, TaskSnapshot, TranscriptLine,};use super::{@@ -396,6 +396,15 @@ fn context_message(message: &Message) -> ContextMessage {author: author(message),content: truncate(&message.content),posted_at: message.created_at,+ attachments: message+ .attachments+ .iter()+ .map(|attachment| ContextAttachment {+ entity_type: attachment.entity_type.clone(),+ entity_id: attachment.entity_id.clone(),+ url: None,+ })+ .collect(),}}diff --git a/crates/scheduled_action/src/outbound/event_content/routine_event/test.rs b/crates/scheduled_action/src/outbound/event_content/routine_event/test.rsindex dbc6ad6a2b..64eceb33b5 100644--- a/crates/scheduled_action/src/outbound/event_content/routine_event/test.rs+++ b/crates/scheduled_action/src/outbound/event_content/routine_event/test.rs@@ -568,6 +568,7 @@ fn a_channel_reply_carries_its_thread_through_the_message() {author: ana.clone(),content: "Login crashes on Safari".into(),posted_at: at(1),+ attachments: Vec::new(),},ContextMessage {id: answer_id,@@ -578,12 +579,14 @@ fn a_channel_reply_carries_its_thread_through_the_message() {},content: "Fixed in #812".into(),posted_at: at(2),+ attachments: Vec::new(),},ContextMessage {id: prompt_id,author: ana,content: "Still broken on Safari 17, can someone look?".into(),posted_at: at(4),+ attachments: Vec::new(),},],messages_omitted: false,diff --git a/crates/trigger_context/src/lib.rs b/crates/trigger_context/src/lib.rsindex 2c5c54bb02..541459058c 100644--- a/crates/trigger_context/src/lib.rs+++ b/crates/trigger_context/src/lib.rs@@ -63,6 +63,19 @@ pub struct ContextPerson {pub email: Option<String>,}+/// A file attached to a context message.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub struct ContextAttachment {+ /// What was attached, such as `static/image`, `static/video`, or `document`.+ pub entity_type: String,+ /// Its id. For a static file, the file id used in `/file/{id}`.+ pub entity_id: String,+ /// Where the agent can fetch it. Only static files have one, filled in by+ /// the harness from its static file service address.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub url: Option<String>,+}+/// A message the agent may read.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct ContextMessage {@@ -74,6 +87,9 @@ pub struct ContextMessage {pub content: String,/// When it was posted.pub posted_at: DateTime<Utc>,+ /// Files attached to this message. Empty is omitted on the wire.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub attachments: Vec<ContextAttachment>,}/// Messages of one discussion, oldest first.@@ -109,6 +125,76 @@ pub struct DiscussionContext {pub channel: Vec<ContextThread>,}+impl DiscussionContext {+ /// Files attached to the prompt's own thread, the prompting message first.+ ///+ /// Background channel activity is not included: those files are not what+ /// the prompt is about.+ #[must_use]+ pub fn prompt_thread_attachments(&self) -> Vec<&ContextAttachment> {+ let Some(thread) = &self.thread else {+ return Vec::new();+ };+ let (prompt, rest): (Vec<&ContextMessage>, Vec<&ContextMessage>) = thread+ .messages+ .iter()+ .partition(|message| message.id == self.prompt_message_id);+ prompt+ .into_iter()+ .chain(rest)+ .flat_map(|message| message.attachments.iter())+ .collect()+ }++ /// Every attachment the agent will read about: the quoted message, the+ /// prompt's thread, and background channel activity.+ pub fn attachments_mut(&mut self) -> impl Iterator<Item = &mut ContextAttachment> {+ let quoted = match &mut self.reply_target {+ ReplyTarget::Quote {+ message: Some(message),+ ..+ } => Some(message),+ ReplyTarget::Quote { message: None, .. }+ | ReplyTarget::Thread { .. }+ | ReplyTarget::None => None,+ };+ quoted+ .into_iter()+ .chain(+ self.thread+ .iter_mut()+ .chain(self.channel.iter_mut())+ .flat_map(|thread| thread.messages.iter_mut()),+ )+ .flat_map(|message| message.attachments.iter_mut())+ }+}++impl TriggerContext {+ /// The discussion this trigger was posted in, when it was one.+ #[must_use]+ pub fn discussion(&self) -> Option<&DiscussionContext> {+ match self {+ Self::Mentioned(discussion) | Self::Conversation(discussion) => Some(discussion),+ Self::FollowUp(follow_up) => Some(&follow_up.discussion),+ Self::TaskAssigned(_) | Self::Requested(_) | Self::Dispatched(_) | Self::Routine(_) => {+ None+ }+ }+ }++ /// The discussion this trigger was posted in, mutably.+ pub fn discussion_mut(&mut self) -> Option<&mut DiscussionContext> {+ match self {+ Self::Mentioned(discussion) | Self::Conversation(discussion) => Some(discussion),+ Self::FollowUp(follow_up) => Some(&mut follow_up.discussion),+ Self::TaskAssigned(_) | Self::Requested(_) | Self::Dispatched(_) | Self::Routine(_) => {+ None+ }+ }+ }+}+/// Where a discussion lives. Each carries its name, so the agent is never/// handed a bare id.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]diff --git a/crates/trigger_context/src/test.rs b/crates/trigger_context/src/test.rsindex c86a38372a..230f63e218 100644--- a/crates/trigger_context/src/test.rs+++ b/crates/trigger_context/src/test.rs@@ -36,6 +36,7 @@ fn a_channel_follow_up_has_a_stable_wire_shape() {},content: "please fix".to_owned(),posted_at: Utc.with_ymd_and_hms(2026, 10, 8, 14, 2, 0).unwrap(),+ attachments: Vec::new(),}],messages_omitted: false,}),@@ -251,3 +252,105 @@ fn a_task_assignment_has_a_stable_wire_shape() {context);}++fn julia() -> ContextPerson {+ ContextPerson {+ id: "macro|[email protected]".to_owned(),+ name: "Julia".to_owned(),+ email: Some("[email protected]".to_owned()),+ }+}++fn message(id: u128, content: &str, attachments: Vec<ContextAttachment>) -> ContextMessage {+ ContextMessage {+ id: Uuid::from_u128(id),+ author: julia(),+ content: content.to_owned(),+ posted_at: Utc.with_ymd_and_hms(2026, 10, 8, 14, 0, 0).unwrap(),+ attachments,+ }+}++fn image(entity_id: &str) -> ContextAttachment {+ ContextAttachment {+ entity_type: "static/image".to_owned(),+ entity_id: entity_id.to_owned(),+ url: None,+ }+}++#[test]+fn a_message_attachment_has_a_stable_wire_shape() {+ let message = message(+ 1,+ "We need agent templates",+ vec![image("9ec21122-4bd8-473f-bfb0-21d2e6e5f03b")],+ );+ let wire = json!({+ "id": "00000000-0000-0000-0000-000000000001",+ "author": {+ "id": "macro|[email protected]",+ "name": "Julia",+ "email": "[email protected]"+ },+ "content": "We need agent templates",+ "posted_at": "2026-10-08T14:00:00Z",+ "attachments": [{+ "entity_type": "static/image",+ "entity_id": "9ec21122-4bd8-473f-bfb0-21d2e6e5f03b"+ }]+ });+ assert_eq!(serde_json::to_value(&message).unwrap(), wire);+ assert_eq!(+ serde_json::from_value::<ContextMessage>(wire).unwrap(),+ message+ );+}++#[test]+fn prompt_thread_attachments_put_the_prompt_message_first() {+ let root = image("root-file");+ let prompt = image("prompt-file");+ let later = image("later-file");+ let discussion = DiscussionContext {+ surface: DiscussionSurface::Channel {+ id: Uuid::from_u128(0xc1),+ name: Some("eng".to_owned()),+ channel_type: ChannelType::Public,+ },+ prompt_message_id: Uuid::from_u128(2),+ sender: julia(),+ reply_target: ReplyTarget::Thread {+ root_id: Uuid::from_u128(1),+ },+ thread: Some(ContextThread {+ root_id: Uuid::from_u128(1),+ messages: vec![+ message(1, "screenshot", vec![root.clone()]),+ message(2, "@cursor look", vec![prompt.clone()]),+ message(3, "and this", vec![later.clone()]),+ ],+ messages_omitted: false,+ }),+ channel: vec![ContextThread {+ root_id: Uuid::from_u128(9),+ messages: vec![message(9, "unrelated", vec![image("background-file")])],+ messages_omitted: false,+ }],+ };++ assert_eq!(+ discussion+ .prompt_thread_attachments()+ .into_iter()+ .map(|attachment| attachment.entity_id.as_str())+ .collect::<Vec<_>>(),+ ["prompt-file", "root-file", "later-file"]+ );+ assert_eq!(+ TriggerContext::Mentioned(discussion)+ .discussion()+ .map(|discussion| discussion.prompt_thread_attachments().len()),+ Some(3)+ );+}diff --git a/docs/agent-guide/channels.md b/docs/agent-guide/channels.mdindex f0f7a61def..906f067278 100644--- a/docs/agent-guide/channels.md+++ b/docs/agent-guide/channels.md@@ -433,6 +433,12 @@ bot asks before scheduling a specific clock time. Within the rollout, `@Macro``@cursor` / `@codex` when available — opensan agent session; follow-up`@` mentions of that bot in the same thread route to it.+An agent mentioned in a thread reply gets, on its first turn, the images and+videos on the mentioning message and then on the thread root and earlier+replies (at most 8, no duplicates); follow-ups carry only their own files.+Files elsewhere in the channel appear only as `<attachment>` entries in its+context. To check, post an image on a thread root, mention an agent in a+reply without attaching anything, and confirm it describes the image.Macro Coding Agent (`@coder`) is unavailable in mention suggestions, includingwhen it appears among existing participants or bots. Check with the agentsrollout both enabled and disabled.diff --git a/packages/lexical-core/tests/agent-trigger-context.test.ts b/packages/lexical-core/tests/agent-trigger-context.test.tsindex 5538c9779e..3e7e977ee6 100644--- a/packages/lexical-core/tests/agent-trigger-context.test.ts+++ b/packages/lexical-core/tests/agent-trigger-context.test.ts@@ -95,6 +95,87 @@ describe('composeAgentContextPrompt with a trigger', () => {);});+ it('lists a thread-root image on its message so the agent can fetch it', () => {+ const fileId = '9ec21122-4bd8-473f-bfb0-21d2e6e5f03b';+ const markdown = composeAgentContextPrompt({+ promptMarkdown: 'see screenshot and create a task',+ trigger: {+ kind: 'mentioned',+ surface: {+ type: 'channel',+ id: 'c1',+ name: 'eng',+ channel_type: 'public',+ },+ prompt_message_id: 'm2',+ sender: {+ id: 'macro|[email protected]',+ name: 'Julia',+ email: '[email protected]',+ },+ reply_target: { kind: 'thread', root_id: 'm1' },+ thread: {+ root_id: 'm1',+ messages: [+ {+ id: 'm1',+ author: {+ id: 'macro|[email protected]',+ name: 'Teo',+ email: '[email protected]',+ },+ content: 'We need agent templates',+ posted_at: '2026-10-08T14:00:00Z',+ attachments: [+ {+ entity_type: 'static/image',+ entity_id: fileId,+ url: `https://static.example/file/${fileId}`,+ },+ { entity_type: 'document', entity_id: 'doc-1' },+ ],+ },+ {+ id: 'm2',+ author: {+ id: 'macro|[email protected]',+ name: 'Julia',+ email: '[email protected]',+ },+ content: 'see screenshot and create a task',+ posted_at: '2026-10-08T14:02:00Z',+ },+ ],+ messages_omitted: false,+ },+ },+ });++ expect(hiddenContext(markdown)).toBe(+ [+ '<trigger kind="mentioned">',+ ' <note>Julia mentioned you, and that mention opened this session. Their message is the prompt.</note>',+ ' <discussion>',+ ' <channel id="c1" name="eng" type="public"/>',+ ' <origin>This prompt was posted in a channel thread, not the agent session view. Your reply is posted back into that thread, and it is where the user will answer anything you ask.</origin>',+ ' <sender name="Julia" email="[email protected]" id="macro|[email protected]"/>',+ ' <reply_target kind="thread" thread="m1">',+ ' <note>The prompt was posted as a reply in the thread below. It is about that thread.</note>',+ ' </reply_target>',+ ' <note>Attachments are listed on each message and can be fetched by their url.</note>',+ ' <thread root="m1">',+ ` <message id="m1" author="Teo" author_email="[email protected]" author_id="macro|[email protected]" at="2026-10-08T14:00:00Z">We need agent templates`,+ ` <attachment type="static/image" id="${fileId}" url="https://static.example/file/${fileId}"/>`,+ ' <attachment type="document" id="doc-1"/>',+ ' </message>',+ ' <message id="m2" author="Julia" author_email="[email protected]" author_id="macro|[email protected]" at="2026-10-08T14:02:00Z" mentioned_you="true">see screenshot and create a task</message>',+ ' </thread>',+ ' </discussion>',+ '</trigger>',+ ].join('\n')+ );+ });+it('renders an inferred follow-up after the session block and warns the inference can be wrong', () => {const markdown = composeAgentContextPrompt({promptMarkdown: 'and the popover one too',diff --git a/packages/lexical-core/utils/agent-context.ts b/packages/lexical-core/utils/agent-context.tsindex d0cf1f5216..06f7e12947 100644--- a/packages/lexical-core/utils/agent-context.ts+++ b/packages/lexical-core/utils/agent-context.ts@@ -35,6 +35,16 @@ export type ContextPerson = {email?: string;};+/** A file attached to a context message. */+export type ContextAttachment = {+ /** What was attached, such as `static/image`, `static/video`, or `document`. */+ entity_type: string;+ /** Its id. For a static file, the file id used in `/file/{id}`. */+ entity_id: string;+ /** Where the agent can fetch it; only static files have one. */+ url?: string;+};+/** A message the agent may read. */export type ContextMessage = {id: string;@@ -42,6 +52,8 @@ export type ContextMessage = {/** Internal markdown. */content: string;posted_at: string;+ /** Absent when empty. */+ attachments?: ContextAttachment[];};/** Messages of one discussion, oldest first. */@@ -709,13 +721,29 @@ type DiscussionReading = {type MessageMarker = { attribute: string; messageId: string };+function attachmentNodes(+ attachments: ContextAttachment[] | undefined+): FxpNode[] {+ return (attachments ?? []).map((attachment) =>+ el(+ 'attachment',+ [],+ present({+ type: attachment.entity_type,+ id: attachment.entity_id,+ url: attachment.url,+ })+ )+ );+}+function contextMessageNode(message: ContextMessage,marker: MessageMarker): FxpNode {return el('message',- [text(readable(message.content))],+ [text(readable(message.content)), ...attachmentNodes(message.attachments)],present({id: message.id,...personAttributes(message.author, 'author'),@@ -725,6 +753,23 @@ function contextMessageNode();}+function discussionHasAttachments(discussion: DiscussionContext): boolean {+ const quoted =+ discussion.reply_target.kind === 'quote'+ ? discussion.reply_target.message+ : undefined;+ const threads = [+ ...(discussion.thread ? [discussion.thread] : []),+ ...(discussion.channel ?? []),+ ];+ return (+ (quoted?.attachments?.length ?? 0) > 0 ||+ threads.some((thread) =>+ thread.messages.some((message) => (message.attachments?.length ?? 0) > 0)+ )+ );+}+function contextThreadNode(thread: ContextThread,marker: MessageMarker@@ -951,6 +996,13 @@ function discussionNode(: []),personNode('sender', discussion.sender),contextReplyTargetNode(discussion.reply_target, marker, reading.subject),+ ...(discussionHasAttachments(discussion)+ ? [+ note(+ 'Attachments are listed on each message and can be fetched by their url.'+ ),+ ]+ : []),...(discussion.thread? [contextThreadNode(discussion.thread, marker)]: []),diff --git a/services/lexical-service/src/endpoints/agent-context.ts b/services/lexical-service/src/endpoints/agent-context.tsindex 0f2d617ce5..762efd9f03 100644--- a/services/lexical-service/src/endpoints/agent-context.ts+++ b/services/lexical-service/src/endpoints/agent-context.ts@@ -91,11 +91,18 @@ const triggerPerson = z.object({email: z.string().optional(),});+const triggerAttachment = z.object({+ entity_type: z.string().min(1),+ entity_id: z.string().min(1),+ url: z.string().optional(),+});+const triggerMessage = z.object({id: z.string().min(1),author: triggerPerson,content: z.string(),posted_at: z.string().min(1),+ attachments: z.array(triggerAttachment).optional(),});const triggerThread = z.object({