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(channels): name each message sender in the agent's channel reads (#8744)
gbirman7e8f8b1ace9d
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.tsindex f107c95be6..a049298b0f 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts@@ -12173,6 +12173,7 @@ export const ReadChannelMessageContextResponse = z.object({id: z.string().uuid(),channelId: z.string().uuid(),senderId: z.string(),+ senderName: z.union([z.string(), z.null()]).optional(),content: z.string(),contentTruncated: z.boolean(),createdAt: z.string().datetime({ offset: true }),@@ -12196,6 +12197,7 @@ export const ReadChannelMessageContextResponse = z.object({id: z.string().uuid(),threadId: z.string().uuid(),senderId: z.string(),+ senderName: z.union([z.string(), z.null()]).optional(),content: z.string(),contentTruncated: z.boolean(),createdAt: z.string().datetime({ offset: true }),@@ -12238,6 +12240,7 @@ export const ReadChannelMessageContextResponse = z.object({id: z.string().uuid(),channelId: z.string().uuid(),senderId: z.string(),+ senderName: z.union([z.string(), z.null()]).optional(),content: z.string(),contentTruncated: z.boolean(),createdAt: z.string().datetime({ offset: true }),@@ -12261,6 +12264,7 @@ export const ReadChannelMessageContextResponse = z.object({id: z.string().uuid(),threadId: z.string().uuid(),senderId: z.string(),+ senderName: z.union([z.string(), z.null()]).optional(),content: z.string(),contentTruncated: z.boolean(),createdAt: z.string().datetime({ offset: true }),@@ -12303,6 +12307,7 @@ export const ReadChannelMessageContextResponse = z.object({id: z.string().uuid(),channelId: z.string().uuid(),senderId: z.string(),+ senderName: z.union([z.string(), z.null()]).optional(),content: z.string(),contentTruncated: z.boolean(),createdAt: z.string().datetime({ offset: true }),@@ -12326,6 +12331,7 @@ export const ReadChannelMessageContextResponse = z.object({id: z.string().uuid(),threadId: z.string().uuid(),senderId: z.string(),+ senderName: z.union([z.string(), z.null()]).optional(),content: z.string(),contentTruncated: z.boolean(),createdAt: z.string().datetime({ offset: true }),@@ -12373,6 +12379,7 @@ export const ReadChannelMessageContextResponse = z.object({id: z.string().uuid(),channelId: z.string().uuid(),senderId: z.string(),+ senderName: z.union([z.string(), z.null()]).optional(),content: z.string(),contentTruncated: z.boolean(),createdAt: z.string().datetime({ offset: true }),@@ -12396,6 +12403,7 @@ export const ReadChannelMessageContextResponse = z.object({id: z.string().uuid(),threadId: z.string().uuid(),senderId: z.string(),+ senderName: z.union([z.string(), z.null()]).optional(),content: z.string(),contentTruncated: z.boolean(),createdAt: z.string().datetime({ offset: true }),@@ -12441,6 +12449,7 @@ export const ReadChannelMessageContextResponse = z.object({id: z.string().uuid(),threadId: z.string().uuid(),senderId: z.string(),+ senderName: z.union([z.string(), z.null()]).optional(),content: z.string(),contentTruncated: z.boolean(),createdAt: z.string().datetime({ offset: true }),@@ -12467,6 +12476,7 @@ export const ReadChannelMessageContextResponse = z.object({id: z.string().uuid(),threadId: z.string().uuid(),senderId: z.string(),+ senderName: z.union([z.string(), z.null()]).optional(),content: z.string(),contentTruncated: z.boolean(),createdAt: z.string().datetime({ offset: true }),@@ -12494,6 +12504,7 @@ export const ReadChannelMessageContextResponse = z.object({id: z.string().uuid(),threadId: z.string().uuid(),senderId: z.string(),+ senderName: z.union([z.string(), z.null()]).optional(),content: z.string(),contentTruncated: z.boolean(),createdAt: z.string().datetime({ offset: true }),@@ -12594,6 +12605,7 @@ export const ReadChannelMessagesResponse = z.object({id: z.string().uuid(),channelId: z.string().uuid(),senderId: z.string(),+ senderName: z.union([z.string(), z.null()]).optional(),content: z.string(),contentTruncated: z.boolean(),createdAt: z.string().datetime({ offset: true }),@@ -12617,6 +12629,7 @@ export const ReadChannelMessagesResponse = z.object({id: z.string().uuid(),threadId: z.string().uuid(),senderId: z.string(),+ senderName: z.union([z.string(), z.null()]).optional(),content: z.string(),contentTruncated: z.boolean(),createdAt: z.string().datetime({ offset: true }),@@ -12740,6 +12753,7 @@ export const ReadChannelThreadResponse = z.object({id: z.string().uuid(),channelId: z.string().uuid(),senderId: z.string(),+ senderName: z.union([z.string(), z.null()]).optional(),content: z.string(),contentTruncated: z.boolean(),createdAt: z.string().datetime({ offset: true }),@@ -12763,6 +12777,7 @@ export const ReadChannelThreadResponse = z.object({id: z.string().uuid(),threadId: z.string().uuid(),senderId: z.string(),+ senderName: z.union([z.string(), z.null()]).optional(),content: z.string(),contentTruncated: z.boolean(),createdAt: z.string().datetime({ offset: true }),@@ -12810,6 +12825,7 @@ export const ReadChannelThreadResponse = z.object({id: z.string().uuid(),threadId: z.string().uuid(),senderId: z.string(),+ senderName: z.union([z.string(), z.null()]).optional(),content: z.string(),contentTruncated: z.boolean(),createdAt: z.string().datetime({ offset: true }),@@ -12837,6 +12853,7 @@ export const ReadChannelThreadResponse = z.object({id: z.string().uuid(),channelId: z.string().uuid(),senderId: z.string(),+ senderName: z.union([z.string(), z.null()]).optional(),content: z.string(),contentTruncated: z.boolean(),createdAt: z.string().datetime({ offset: true }),@@ -12860,6 +12877,7 @@ export const ReadChannelThreadResponse = z.object({id: z.string().uuid(),threadId: z.string().uuid(),senderId: z.string(),+ senderName: z.union([z.string(), z.null()]).optional(),content: z.string(),contentTruncated: z.boolean(),createdAt: z.string().datetime({ offset: true }),diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.tsindex 234948f1dd..cf9c50eafb 100644--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts@@ -13433,9 +13433,14 @@ export interface ToolChannelMessage {*/channelId: string;/**- * Sender user id.+ * Sender id: `macro|<email>` for a person, `bot|<id>` for a bot.*/senderId: string;+ /**+ * The sender's name as the app shows it, for the same sender as+ * `senderId`. Absent when a person has no profile name.+ */+ senderName?: string | null;/*** Message content, possibly truncated.*/@@ -13508,9 +13513,14 @@ export interface ToolThreadReply {*/threadId: string;/**- * Sender user id.+ * Sender id: `macro|<email>` for a person, `bot|<id>` for a bot.*/senderId: string;+ /**+ * The sender's name as the app shows it, for the same sender as+ * `senderId`. Absent when a person has no profile name.+ */+ senderName?: string | null;/*** Reply content, possibly truncated.*/diff --git a/crates/channels/AGENTS.md b/crates/channels/AGENTS.mdindex 07de2ad35b..eaae7a913b 100644--- a/crates/channels/AGENTS.md+++ b/crates/channels/AGENTS.md@@ -47,6 +47,7 @@ DMs, and the shared message store other domains discuss things on.## Tool contracts- `ShareWithChannel` exposes agent sessions and omits legacy chat targets; the domain retains historical entity support.+- The channel read tools return `senderName` beside `senderId`: the name the app shows (imported author, bot, call guest, or the person's profile name from `get_user_display_names`). One lookup per call; a failed lookup omits names instead of failing the read.## Checksdiff --git a/crates/channels/src/domain/ports.rs b/crates/channels/src/domain/ports.rsindex 8ee3b7889c..c2c3e5e5d9 100644--- a/crates/channels/src/domain/ports.rs+++ b/crates/channels/src/domain/ports.rs@@ -28,9 +28,7 @@ use chrono::{DateTime, Utc};use entity_access::domain::models::{EntityAccessReceipt, MemberParticipantRole};use macro_user_id::user_id::MacroUserIdStr;use models_pagination::{CreatedAt, Query};-#[cfg(feature = "list")]-use std::collections::HashMap;-use std::collections::HashSet;+use std::collections::{HashMap, HashSet};use uuid::Uuid;/// Verified channel participation required to change a channel picture.@@ -262,6 +260,13 @@ pub trait ChannelRepo: Send + Sync + 'static {viewer_user_id: MacroUserIdStr<'static>,) -> impl Future<Output = Result<String, Self::Err>> + Send;+ /// Profile names (`first last`) for the given users, as the app shows+ /// them. Users without a name are absent from the map.+ fn get_user_display_names(+ &self,+ user_ids: &[MacroUserIdStr<'static>],+ ) -> impl Future<Output = Result<HashMap<MacroUserIdStr<'static>, String>, Self::Err>> + Send;+/// Check whether a user belongs to a team.fn user_has_team(&self,@@ -442,6 +447,13 @@ pub trait ChannelService: Send + Sync + 'static {channel_id: Uuid,) -> impl Future<Output = Result<Vec<ChannelParticipant>, ChannelMessagesErr>> + Send;+ /// Profile names (`first last`) for the given users, as the app shows+ /// them. Users without a name are absent from the map.+ fn get_user_display_names(+ &self,+ user_ids: Vec<MacroUserIdStr<'static>>,+ ) -> impl Future<Output = Result<HashMap<MacroUserIdStr<'static>, String>, ChannelMessagesErr>> + Send;+/// Fetch channel metadata (type + resolved display name) from the viewer's perspective.fn get_channel_metadata(&self,diff --git a/crates/channels/src/domain/service.rs b/crates/channels/src/domain/service.rsindex 0bdd0a08c0..7dfed55d54 100644--- a/crates/channels/src/domain/service.rs+++ b/crates/channels/src/domain/service.rs@@ -22,7 +22,7 @@ use entity_access::domain::models::{};use macro_user_id::user_id::MacroUserIdStr;use models_pagination::{CreatedAt, PaginateOn, Query};-use std::collections::HashSet;+use std::collections::{HashMap, HashSet};use std::sync::Arc;use uuid::Uuid;@@ -963,6 +963,20 @@ whereOk(participants)}+ #[tracing::instrument(err, skip_all, fields(user_count = user_ids.len()))]+ async fn get_user_display_names(+ &self,+ user_ids: Vec<MacroUserIdStr<'static>>,+ ) -> Result<HashMap<MacroUserIdStr<'static>, String>, ChannelMessagesErr> {+ let names = self+ .repo+ .get_user_display_names(&user_ids)+ .await+ .map_err(anyhow::Error::from)?;++ Ok(names)+ }+#[tracing::instrument(err, skip(self))]async fn get_channel_metadata(&self,diff --git a/crates/channels/src/domain/service/test.rs b/crates/channels/src/domain/service/test.rsindex 59bf57c9cb..1b5f9bfba3 100644--- a/crates/channels/src/domain/service/test.rs+++ b/crates/channels/src/domain/service/test.rs@@ -208,6 +208,13 @@ impl ChannelRepo for FakeMutationRepo {Ok("Project".to_string())}+ async fn get_user_display_names(+ &self,+ _user_ids: &[MacroUserIdStr<'static>],+ ) -> Result<std::collections::HashMap<MacroUserIdStr<'static>, String>, Self::Err> {+ Ok(std::collections::HashMap::new())+ }+async fn user_has_team(&self, _user_id: String, _team_id: Uuid) -> Result<bool, Self::Err> {Ok(true)}diff --git a/crates/channels/src/inbound/axum_router/test.rs b/crates/channels/src/inbound/axum_router/test.rsindex 6881af8279..7748b27aa9 100644--- a/crates/channels/src/inbound/axum_router/test.rs+++ b/crates/channels/src/inbound/axum_router/test.rs@@ -338,6 +338,14 @@ impl ChannelService for MockService {),])}++ async fn get_user_display_names(+ &self,+ _user_ids: Vec<MacroUserIdStr<'static>>,+ ) -> Result<std::collections::HashMap<MacroUserIdStr<'static>, String>, ChannelMessagesErr>+ {+ Ok(std::collections::HashMap::new())+ }}struct ErrorService;@@ -376,6 +384,14 @@ impl ChannelService for ErrorService {) -> Result<Vec<crate::domain::models::AttachmentEntityReference>, ChannelMessagesErr> {Err(ChannelMessagesErr::Repo(anyhow::anyhow!("database error")))}++ async fn get_user_display_names(+ &self,+ _user_ids: Vec<MacroUserIdStr<'static>>,+ ) -> Result<std::collections::HashMap<MacroUserIdStr<'static>, String>, ChannelMessagesErr>+ {+ Ok(std::collections::HashMap::new())+ }}struct ParticipantsService;@@ -425,6 +441,14 @@ impl ChannelService for ParticipantsService {])}+ async fn get_user_display_names(+ &self,+ _user_ids: Vec<MacroUserIdStr<'static>>,+ ) -> Result<std::collections::HashMap<MacroUserIdStr<'static>, String>, ChannelMessagesErr>+ {+ Ok(std::collections::HashMap::new())+ }+async fn get_attachment_references(&self,_entity_type: String,@@ -491,6 +515,14 @@ impl ChannelService for JoinLinkService {unimplemented!()}+ async fn get_user_display_names(+ &self,+ _user_ids: Vec<MacroUserIdStr<'static>>,+ ) -> Result<std::collections::HashMap<MacroUserIdStr<'static>, String>, ChannelMessagesErr>+ {+ Ok(std::collections::HashMap::new())+ }+async fn get_channel_join_code(&self,channel_id: Uuid,@@ -577,6 +609,14 @@ impl ChannelService for RecordingMutationService {})}+ async fn get_user_display_names(+ &self,+ _user_ids: Vec<MacroUserIdStr<'static>>,+ ) -> Result<std::collections::HashMap<MacroUserIdStr<'static>, String>, ChannelMessagesErr>+ {+ Ok(std::collections::HashMap::new())+ }+async fn get_or_create_dm(&self,_actor: Sender,@@ -1412,6 +1452,14 @@ impl ChannelService for ActivityService {Ok(vec![])}+ async fn get_user_display_names(+ &self,+ _user_ids: Vec<MacroUserIdStr<'static>>,+ ) -> Result<std::collections::HashMap<MacroUserIdStr<'static>, String>, ChannelMessagesErr>+ {+ Ok(std::collections::HashMap::new())+ }+async fn get_activities(&self, user_id: String) -> Result<Vec<Activity>, ChannelMessagesErr> {Ok(vec![Activity {id: Uuid::nil(),diff --git a/crates/channels/src/inbound/toolset.rs b/crates/channels/src/inbound/toolset.rsindex d041fb890c..4394a71268 100644--- a/crates/channels/src/inbound/toolset.rs+++ b/crates/channels/src/inbound/toolset.rs@@ -44,7 +44,8 @@ use messages::domain::{ports::MessageError,service::{MessageView, MessageWrite},};-use std::sync::Arc;+use std::{collections::HashSet, sync::Arc};+use types::SenderNames;use uuid::Uuid;pub use create_channel_media_upload::{@@ -194,6 +195,23 @@ where.map_err(channel_access_error)}+ /// Profile names for the people among `user_senders`, so the read tools+ /// name them as the app does. A failed lookup leaves the names out rather+ /// than failing the read.+ pub(crate) async fn sender_names(+ &self,+ user_senders: HashSet<MacroUserIdStr<'static>>,+ ) -> SenderNames {+ if user_senders.is_empty() {+ return SenderNames::new();+ }+ self.service+ .get_user_display_names(user_senders.into_iter().collect())+ .await+ .inspect_err(|error| tracing::warn!(error = ?error, "failed to resolve sender names"))+ .unwrap_or_default()+ }+/// Mint a member receipt before renaming a channel.pub async fn require_channel_rename(&self,diff --git a/crates/channels/src/inbound/toolset/read_channel_message_context.rs b/crates/channels/src/inbound/toolset/read_channel_message_context.rsindex ef48652025..f1a6ec0dac 100644--- a/crates/channels/src/inbound/toolset/read_channel_message_context.rs+++ b/crates/channels/src/inbound/toolset/read_channel_message_context.rs@@ -3,8 +3,8 @@ use messages::domain::ports::MessageTimelineQuery;use super::ChannelToolContext;use super::types::{- ToolChannelMessage, ToolOmission, ToolOmissionKind, ToolResolvedMessage, ToolThreadReply,- clamp_max_chars, content_truncation_omissions,+ SenderNames, ToolChannelMessage, ToolOmission, ToolOmissionKind, ToolResolvedMessage,+ ToolThreadReply, clamp_max_chars, content_truncation_omissions, user_senders,};use crate::domain::ports::ChannelService;use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};@@ -121,7 +121,12 @@ where{type Output = ReadChannelMessageContextResponse;- #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]+ #[tracing::instrument(+ name = "channels.tool.read_message_context",+ skip_all,+ fields(user_id=?request_context.user_id, channel_id=%self.channel_id),+ err+ )]async fn call(&self,service_context: ServiceContext<ChannelToolContext<Svc, AccessSvc>>,@@ -158,6 +163,26 @@ where.await.map_err(tool_err("failed to read channel context around message"))?;channel_page.items.reverse();+ let thread_replies = match resolved.thread_id {+ None => None,+ Some(_) => Some(+ service_context+ .messages+ .get_thread(access, resolved.root_id())+ .await+ .map_err(tool_err("failed to read thread"))?+ .replies,+ ),+ };++ let senders = user_senders(+ channel_page+ .items+ .iter()+ .flat_map(|item| std::iter::once(&item.message).chain(&item.thread.preview))+ .chain(thread_replies.iter().flatten()),+ );+ let names = service_context.sender_names(senders).await;let channel_messages: Vec<ToolChannelMessage> = channel_page.items.into_iter()@@ -167,6 +192,7 @@ whereself.channel_id,true,max_chars_per_message,+ &names,)}).collect();@@ -187,15 +213,10 @@ whereafter,};- let thread_context = match resolved.thread_id {+ let thread_context = match thread_replies {None => None,- Some(_) => Some(read_reply_context(- service_context- .messages- .get_thread(access, resolved.root_id())- .await- .map_err(tool_err("failed to read thread"))?- .replies,+ Some(replies) => Some(read_reply_context(+ replies,ReplyContextArgs {reply_id: self.message_id,thread_id: resolved.root_id(),@@ -203,6 +224,7 @@ wherebefore: self.thread_before,after: self.thread_after,max_chars_per_message,+ names: &names,},)?),};@@ -244,18 +266,19 @@ where}}-struct ReplyContextArgs {+struct ReplyContextArgs<'a> {reply_id: Uuid,thread_id: Uuid,parent: ToolChannelMessage,before: Option<u16>,after: Option<u16>,max_chars_per_message: usize,+ names: &'a SenderNames,}fn read_reply_context(replies: Vec<messages::domain::models::Message>,- args: ReplyContextArgs,+ args: ReplyContextArgs<'_>,) -> Result<ToolThreadReplyContextWindow, ToolCallError> {let before = usize::from(args.before.unwrap_or(10).min(50));let after = usize::from(args.after.unwrap_or(10).min(50));@@ -276,7 +299,14 @@ fn read_reply_context(.into_iter().skip(start).take(end - start)- .map(|reply| ToolThreadReply::from_reply(reply, args.thread_id, args.max_chars_per_message))+ .map(|reply| {+ ToolThreadReply::from_reply(+ reply,+ args.thread_id,+ args.max_chars_per_message,+ args.names,+ )+ }).collect();let anchor_offset = anchor_index - start;let replies_after = mapped.split_off(anchor_offset + 1);diff --git a/crates/channels/src/inbound/toolset/read_channel_messages.rs b/crates/channels/src/inbound/toolset/read_channel_messages.rsindex cb4f1663b0..92d1d7f7c3 100644--- a/crates/channels/src/inbound/toolset/read_channel_messages.rs+++ b/crates/channels/src/inbound/toolset/read_channel_messages.rs@@ -4,7 +4,7 @@ use messages::domain::ports::{MessageDirection, MessageTimelineQuery};use super::ChannelToolContext;use super::types::{PageDirection, ToolChannelMessage, ToolNavigation, ToolOmission, ToolOmissionKind, clamp_limit,- clamp_max_chars, content_truncation_omissions,+ clamp_max_chars, content_truncation_omissions, user_senders,};use crate::domain::ports::ChannelService;use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};@@ -144,7 +144,12 @@ where{type Output = ReadChannelMessagesResponse;- #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]+ #[tracing::instrument(+ name = "channels.tool.read_messages",+ skip_all,+ fields(user_id=?request_context.user_id, channel_id=%self.channel_id),+ err+ )]async fn call(&self,service_context: ServiceContext<ChannelToolContext<Svc, AccessSvc>>,@@ -215,6 +220,12 @@ whereolder_cursor: continuation(page.next_cursor, MessageDirection::Older),newer_cursor: continuation(page.previous_cursor, MessageDirection::Newer),};+ let senders = user_senders(+ page.items+ .iter()+ .flat_map(|item| std::iter::once(&item.message).chain(&item.thread.preview)),+ );+ let names = service_context.sender_names(senders).await;let messages: Vec<_> = page.items.into_iter()@@ -225,6 +236,7 @@ whereself.channel_id,self.include_thread_previews.unwrap_or(true),clamp_max_chars(self.max_chars_per_message),+ &names,)}).collect();diff --git a/crates/channels/src/inbound/toolset/read_channel_thread.rs b/crates/channels/src/inbound/toolset/read_channel_thread.rsindex 2923fe0cc4..b1d2c9dcb4 100644--- a/crates/channels/src/inbound/toolset/read_channel_thread.rs+++ b/crates/channels/src/inbound/toolset/read_channel_thread.rs@@ -4,7 +4,7 @@ use messages::domain::ports::MessageTimelineQuery;use super::ChannelToolContext;use super::types::{ToolChannelMessage, ToolOmission, ToolOmissionKind, ToolResolvedMessage, ToolThreadReply,- clamp_limit, clamp_max_chars, content_truncation_omissions,+ clamp_limit, clamp_max_chars, content_truncation_omissions, user_senders,};use crate::domain::ports::ChannelService;use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};@@ -128,7 +128,12 @@ where{type Output = ReadChannelThreadResponse;- #[tracing::instrument(skip_all, fields(user_id=?request_context.user_id), err)]+ #[tracing::instrument(+ name = "channels.tool.read_thread",+ skip_all,+ fields(user_id=?request_context.user_id, channel_id=%self.channel_id),+ err+ )]async fn call(&self,service_context: ServiceContext<ChannelToolContext<Svc, AccessSvc>>,@@ -164,8 +169,6 @@ wheredescription: "thread parent message not found".to_string(),internal_error: anyhow::anyhow!("thread parent not returned by channel service"),})?;- let parent =- ToolChannelMessage::from_message(parent, self.channel_id, true, max_chars_per_message);let all_replies = service_context.messages@@ -185,44 +188,64 @@ wherelimit,)?;+ let context_items = if self.include_channel_context.unwrap_or(false) {+ let mut page = service_context+ .messages+ .timeline(+ access.clone(),+ MessageTimelineQuery {+ around: Some(resolved.root_id()),+ limit: Some(7),+ ..Default::default()+ },+ )+ .await+ .map_err(tool_err("failed to read channel context around thread"))?;+ page.items.reverse();+ Some(page.items)+ } else {+ None+ };++ let senders = user_senders(+ std::iter::once(&parent.message)+ .chain(&parent.thread.preview)+ .chain(&reply_window)+ .chain(context_items.iter().flatten().map(|item| &item.message)),+ );+ let names = service_context.sender_names(senders).await;+ let parent = ToolChannelMessage::from_message(+ parent,+ self.channel_id,+ true,+ max_chars_per_message,+ &names,+ );let replies: Vec<ToolThreadReply> = reply_window.into_iter().map(|reply| {- ToolThreadReply::from_reply(reply, resolved.root_id(), max_chars_per_message)+ ToolThreadReply::from_reply(+ reply,+ resolved.root_id(),+ max_chars_per_message,+ &names,+ )}).collect();-- let channel_context: Option<Vec<ToolChannelMessage>> =- if self.include_channel_context.unwrap_or(false) {- let mut page = service_context- .messages- .timeline(- access.clone(),- MessageTimelineQuery {- around: Some(resolved.root_id()),- limit: Some(7),- ..Default::default()- },+ let channel_context: Option<Vec<ToolChannelMessage>> = context_items.map(|items| {+ items+ .into_iter()+ .map(|message| {+ ToolChannelMessage::from_message(+ message,+ self.channel_id,+ false,+ max_chars_per_message,+ &names,)- .await- .map_err(tool_err("failed to read channel context around thread"))?;- page.items.reverse();- Some(- page.items- .into_iter()- .map(|message| {- ToolChannelMessage::from_message(- message,- self.channel_id,- false,- max_chars_per_message,- )- })- .collect(),- )- } else {- None- };+ })+ .collect()+ });let mut omissions = Vec::new();if omitted_before > 0 {diff --git a/crates/channels/src/inbound/toolset/test.rs b/crates/channels/src/inbound/toolset/test.rsindex 8c63c3ae93..611356a219 100644--- a/crates/channels/src/inbound/toolset/test.rs+++ b/crates/channels/src/inbound/toolset/test.rs@@ -34,9 +34,12 @@ use entity_access::domain::{ports::{EntityAccessService, NoOpEntityAccessService},};use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId, user_id::MacroUserIdStr};-use std::sync::{- Arc, Mutex,- atomic::{AtomicUsize, Ordering},+use std::{+ collections::HashMap,+ sync::{+ Arc, Mutex,+ atomic::{AtomicUsize, Ordering},+ },};use uuid::Uuid;@@ -65,6 +68,8 @@ struct RecordingMessages {reacts: Arc<Mutex<Vec<RecordedReaction>>>,/// Error every mutation returns instead of succeeding.mutation_error: Option<fn() -> messages::domain::ports::MessageError>,+ /// Root messages every timeline read returns.+ timeline: Vec<messages::domain::models::MessageListItem>,}impl RecordingMessages {@@ -254,7 +259,11 @@ impl messages::domain::api::MessageReader for RecordingMessages {_: EntityAccessReceipt<messages::domain::service::MessageView>,_: messages::domain::ports::MessageTimelineQuery,) -> Result<messages::domain::ports::MessagePage, messages::domain::ports::MessageError> {- unimplemented!("read path unused by mutation tools")+ Ok(messages::domain::ports::MessagePage {+ items: self.timeline.clone(),+ next_cursor: None,+ previous_cursor: None,+ })}async fn timeline_entries(&self,@@ -318,6 +327,8 @@ struct ToolTestChannelService {metadata_name: Option<String>,shares: Arc<Mutex<Vec<(MacroUserIdStr<'static>, Uuid, Vec<ReferencedShareItem>)>>>,deny_share: bool,+ user_names: HashMap<MacroUserIdStr<'static>, String>,+ fail_user_names: bool,}impl ToolTestChannelService {@@ -410,6 +421,25 @@ impl ChannelService for ToolTestChannelService {})}+ async fn get_user_display_names(+ &self,+ user_ids: Vec<MacroUserIdStr<'static>>,+ ) -> Result<HashMap<MacroUserIdStr<'static>, String>, crate::domain::ports::ChannelMessagesErr>+ {+ if self.fail_user_names {+ return Err(crate::domain::ports::ChannelMessagesErr::Repo(+ anyhow::anyhow!("names unavailable"),+ ));+ }+ Ok(user_ids+ .into_iter()+ .filter_map(|user_id| {+ let name = self.user_names.get(&user_id)?.clone();+ Some((user_id, name))+ })+ .collect())+ }+async fn get_attachment_references(&self,_entity_type: String,@@ -1793,3 +1823,146 @@ async fn open_direct_message_needs_someone_besides_the_user() {assert!(error.description.contains("other than the user"));}++fn channel_message(+ channel_id: Uuid,+ sender: Sender,+ preview: Vec<messages::domain::models::Message>,+) -> messages::domain::models::MessageListItem {+ let message = RecordingMessages::default().stored_message(+ &channel_id.to_string(),+ Uuid::now_v7(),+ vec![],+ );+ let message = messages::domain::models::Message {+ sender_id: sender,+ ..message+ };+ messages::domain::models::MessageListItem {+ state: messages::domain::models::ThreadState {+ root_id: message.id,+ user_id: message.sender_id.as_ref().into(),+ created_at: message.created_at,+ updated_at: message.created_at,+ resolved: false,+ deleted_at: None,+ anchor: None,+ },+ thread: messages::domain::models::MessageThreadPreview {+ reply_count: preview.len() as i64,+ latest_reply_at: None,+ preview,+ },+ message,+ }+}++fn person(email: &str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from(format!("macro|{email}")).expect("valid macro user id")+}++fn read_latest(channel_id: Uuid) -> ReadChannelMessages {+ serde_json::from_value(serde_json::json!({+ "channelId": channel_id,+ "windowType": "latest",+ }))+ .expect("valid read")+}++#[tokio::test]+async fn read_channel_messages_names_each_sender_as_the_app_does() {+ let channel_id = Uuid::now_v7();+ let mut reply = RecordingMessages::default().stored_message(+ &channel_id.to_string(),+ Uuid::now_v7(),+ vec![],+ );+ reply.sender_id = Sender::new_from_user(person("[email protected]"));+ let mut bot_message = channel_message(+ channel_id,+ Sender::new_from_bot(bot_id::MACRO_AI_BOT_ID),+ vec![],+ );+ bot_message.message.bot_profile = Some(messages::domain::models::BotSenderProfile {+ name: "Release bot".to_string(),+ avatar_url: None,+ });+ // Newest first, as the timeline returns roots.+ let messages = RecordingMessages {+ timeline: vec![+ bot_message,+ channel_message(+ channel_id,+ Sender::new_from_user(person("[email protected]")),+ vec![],+ ),+ channel_message(+ channel_id,+ Sender::new_from_user(person("[email protected]")),+ vec![reply],+ ),+ ],+ ..Default::default()+ };+ let service = ToolTestChannelService {+ user_names: HashMap::from([(person("[email protected]"), "Pine Martin".to_string())]),+ ..Default::default()+ };+ let context = ChannelToolContext::new(+ Arc::new(messages),+ service,+ ToolTestAccessService::default(),+ );++ let response = read_latest(channel_id)+ .call(ServiceContext(context), RequestContext::new(user_id()))+ .await+ .expect("read");++ let json = serde_json::to_value(&response).expect("serializable");+ let named = &json["messages"][0];+ assert_eq!(named["senderId"], "macro|[email protected]");+ assert_eq!(named["senderName"], "Pine Martin");+ assert_eq!(+ named["thread"]["preview"][0]["senderName"], "Pine Martin",+ "a preview reply names its sender too"+ );+ let unnamed = &json["messages"][1];+ assert_eq!(unnamed["senderId"], "macro|[email protected]");+ assert!(+ unnamed.get("senderName").is_none(),+ "a person without a profile name is known by the id alone"+ );+ assert_eq!(json["messages"][2]["senderName"], "Release bot");+}++#[tokio::test]+async fn read_channel_messages_reads_without_names_when_the_lookup_fails() {+ let channel_id = Uuid::now_v7();+ let messages = RecordingMessages {+ timeline: vec![channel_message(+ channel_id,+ Sender::new_from_user(person("[email protected]")),+ vec![],+ )],+ ..Default::default()+ };+ let service = ToolTestChannelService {+ user_names: HashMap::from([(person("[email protected]"), "Pine Martin".to_string())]),+ fail_user_names: true,+ ..Default::default()+ };+ let context = ChannelToolContext::new(+ Arc::new(messages),+ service,+ ToolTestAccessService::default(),+ );++ let response = read_latest(channel_id)+ .call(ServiceContext(context), RequestContext::new(user_id()))+ .await+ .expect("a failed name lookup does not fail the read");++ assert_eq!(response.messages.len(), 1);+ assert_eq!(response.messages[0].sender_name, None);+}diff --git a/crates/channels/src/inbound/toolset/types.rs b/crates/channels/src/inbound/toolset/types.rsindex d025a4dc60..b4774ab394 100644--- a/crates/channels/src/inbound/toolset/types.rs+++ b/crates/channels/src/inbound/toolset/types.rs@@ -7,8 +7,10 @@ use messages::domain::{use crate::domain::media_upload::ChannelMediaKind;use chrono::{DateTime, Utc};+use macro_user_id::user_id::MacroUserIdStr;use schemars::JsonSchema;use serde::{Deserialize, Serialize};+use std::collections::{HashMap, HashSet};use uuid::Uuid;/// Default number of messages/replies returned by channel AI tools.@@ -20,6 +22,36 @@ pub(crate) const DEFAULT_MAX_CHARS_PER_MESSAGE: usize = 4_000;/// Maximum allowed content length per message.pub(crate) const MAX_CHARS_PER_MESSAGE: usize = 16_000;+/// Profile names of the people who sent a set of messages, keyed by user id.+pub(crate) type SenderNames = HashMap<MacroUserIdStr<'static>, String>;++/// The name the app shows for a message's sender: an imported author's, the+/// bot's, a call guest's, or the person's profile name.+fn sender_name(message: &Message, names: &SenderNames) -> Option<String> {+ message+ .imported_author+ .as_ref()+ .map(|author| author.name.clone())+ .or_else(|| message.bot_profile.as_ref().map(|bot| bot.name.clone()))+ .or_else(|| message.guest_name.clone())+ .or_else(|| {+ message+ .sender_id+ .as_user()+ .and_then(|user| names.get(user).cloned())+ })+}++/// The people among the senders of `messages`, for one name lookup.+pub(crate) fn user_senders<'a>(+ messages: impl IntoIterator<Item = &'a Message>,+) -> HashSet<MacroUserIdStr<'static>> {+ messages+ .into_iter()+ .filter_map(|message| message.sender_id.as_user().cloned())+ .collect()+}+/// Direction for reading more messages around a cursor.#[allow(missing_docs)]#[derive(Debug, Clone, Copy, Deserialize, Serialize, JsonSchema, PartialEq, Eq)]@@ -151,8 +183,12 @@ pub struct ToolThreadReply {pub id: Uuid,/// Parent thread id.pub thread_id: Uuid,- /// Sender user id.+ /// Sender id: `macro|<email>` for a person, `bot|<id>` for a bot.pub sender_id: String,+ /// The sender's name as the app shows it, for the same sender as+ /// `senderId`. Absent when a person has no profile name.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub sender_name: Option<String>,/// Reply content, possibly truncated.pub content: String,/// Whether the reply content was truncated.@@ -174,7 +210,9 @@ impl ToolThreadReply {reply: Message,thread_id: Uuid,max_chars_per_message: usize,+ names: &SenderNames,) -> Self {+ let sender_name = sender_name(&reply, names);let TruncatedContent {content,content_truncated,@@ -184,6 +222,7 @@ impl ToolThreadReply {id: reply.id,thread_id,sender_id: reply.sender_id.into(),+ sender_name,content,content_truncated,created_at: reply.created_at,@@ -227,8 +266,12 @@ pub struct ToolChannelMessage {pub id: Uuid,/// Channel id.pub channel_id: Uuid,- /// Sender user id.+ /// Sender id: `macro|<email>` for a person, `bot|<id>` for a bot.pub sender_id: String,+ /// The sender's name as the app shows it, for the same sender as+ /// `senderId`. Absent when a person has no profile name.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub sender_name: Option<String>,/// Message content, possibly truncated.pub content: String,/// Whether message content was truncated.@@ -255,8 +298,10 @@ impl ToolChannelMessage {channel_id: Uuid,include_thread_preview: bool,max_chars_per_message: usize,+ names: &SenderNames,) -> Self {let message = item.message;+ let sender_name = sender_name(&message, names);let thread_id = message.id;let TruncatedContent {content,@@ -271,7 +316,9 @@ impl ToolChannelMessage {let preview = include_thread_preview.then(|| {preview_replies.into_iter()- .map(|reply| ToolThreadReply::from_reply(reply, thread_id, max_chars_per_message))+ .map(|reply| {+ ToolThreadReply::from_reply(reply, thread_id, max_chars_per_message, names)+ }).collect()});@@ -279,6 +326,7 @@ impl ToolChannelMessage {id: message.id,channel_id,sender_id: message.sender_id.into(),+ sender_name,content,content_truncated,created_at: message.created_at,diff --git a/crates/channels/src/inbound/toolset/types/test.rs b/crates/channels/src/inbound/toolset/types/test.rsindex 6e45acf289..c809e859ed 100644--- a/crates/channels/src/inbound/toolset/types/test.rs+++ b/crates/channels/src/inbound/toolset/types/test.rs@@ -51,7 +51,8 @@ fn message_with_thread(reply_count: i64, preview: Vec<Message>) -> MessageListItfn omitted_reply_count_includes_hidden_previews_when_preview_is_disabled() {let message = message_with_thread(5, vec![reply(2), reply(3), reply(4)]);- let tool_message = ToolChannelMessage::from_message(message, Uuid::nil(), false, 4_000);+ let tool_message =+ ToolChannelMessage::from_message(message, Uuid::nil(), false, 4_000, &SenderNames::new());assert!(tool_message.thread.preview.is_none());assert_eq!(tool_message.thread.omitted_reply_count, 5);@@ -61,7 +62,8 @@ fn omitted_reply_count_includes_hidden_previews_when_preview_is_disabled() {fn omitted_reply_count_excludes_included_previews_when_preview_is_enabled() {let message = message_with_thread(5, vec![reply(2), reply(3), reply(4)]);- let tool_message = ToolChannelMessage::from_message(message, Uuid::nil(), true, 4_000);+ let tool_message =+ ToolChannelMessage::from_message(message, Uuid::nil(), true, 4_000, &SenderNames::new());assert_eq!(tool_message.thread.preview.as_ref().unwrap().len(), 3);assert_eq!(tool_message.thread.omitted_reply_count, 2);diff --git a/crates/channels/src/outbound/pg_channels_repo.rs b/crates/channels/src/outbound/pg_channels_repo.rsindex 0466ee2557..c4aa93dc56 100644--- a/crates/channels/src/outbound/pg_channels_repo.rs+++ b/crates/channels/src/outbound/pg_channels_repo.rs@@ -2390,6 +2390,13 @@ impl ChannelRepo for PgChannelsRepo {resolve_channel_display_name(&self.pool, info, viewer_user_id).await}+ async fn get_user_display_names(+ &self,+ user_ids: &[MacroUserIdStr<'static>],+ ) -> Result<NameLookup, Self::Err> {+ Ok(load_user_display_names(&self.pool, user_ids).await?)+ }+async fn user_has_team(&self, user_id: String, team_id: Uuid) -> Result<bool, Self::Err> {let has_team = sqlx::query_scalar!(r#"diff --git a/crates/teams/src/domain/team_service/test.rs b/crates/teams/src/domain/team_service/test.rsindex af235390c7..46a055712f 100644--- a/crates/teams/src/domain/team_service/test.rs+++ b/crates/teams/src/domain/team_service/test.rs@@ -1267,6 +1267,14 @@ impl ChannelService for RecordingChannelService {async move { unimplemented!("not needed for team service tests") }}+ async fn get_user_display_names(+ &self,+ _user_ids: Vec<MacroUserIdStr<'static>>,+ ) -> Result<std::collections::HashMap<MacroUserIdStr<'static>, String>, ChannelMessagesErr>+ {+ Ok(std::collections::HashMap::new())+ }+fn create_channel(&self,actor: Sender,