Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(bots): bot profile support in channels (#3931)

Will Hutchinsonf9ba04ceacad
diff --git a/js/app/packages/channel/Message/BotIcon.tsx b/js/app/packages/channel/Message/BotIcon.tsx
new file mode 100644
index 0000000000..9ce7ebb2fe
--- /dev/null
+++ b/js/app/packages/channel/Message/BotIcon.tsx
@@ -0,0 +1,54 @@
+import { staticFileSizedUrl } from '@core/constant/servers';
+import { Avatar, type AvatarSize } from '@ui';
+import { Show } from 'solid-js';
+
+type BotIconProps = {
+ /** Bot display name, used for the fallback initial. */
+ name?: string | null;
+ /** Bot avatar URL. */
+ avatarUrl?: string | null;
+ size?: AvatarSize;
+ class?: string;
+};
+
+/**
+ * Bot avatar: the bot's avatar image with an initial fallback. Unlike
+ * `UserIcon`, it carries no DM-on-click or user tooltip behavior since
+ * those only make sense for people.
+ */
+export function BotIcon(props: BotIconProps) {
+ const initial = () => props.name?.trim().charAt(0).toUpperCase() || 'B';
+
+ return (
+ <Avatar size={props.size ?? 'md'} class={props.class}>
+ <Show
+ when={props.avatarUrl}
+ fallback={
+ <Avatar.Fallback class="font-semibold">{initial()}</Avatar.Fallback>
+ }
+ keyed
+ >
+ {(url) => {
+ // Fall back from the sized URL to the original at most once, so a
+ // broken original doesn't retrigger onError in a loop.
+ let triedFallback = false;
+ return (
+ <Avatar.Image
+ // Solid surface circle behind the picture so a transparent avatar
+ // shows surface color rather than what's behind it.
+ class="bg-surface"
+ src={staticFileSizedUrl(url, 'small')}
+ alt={props.name ?? 'Bot'}
+ onError={(e) => {
+ if (!triedFallback) {
+ triedFallback = true;
+ e.currentTarget.src = url;
+ }
+ }}
+ />
+ );
+ }}
+ </Show>
+ </Avatar>
+ );
+}
diff --git a/js/app/packages/channel/Message/SenderIcon.tsx b/js/app/packages/channel/Message/SenderIcon.tsx
index ea7a592729..ebdaf8eaee 100644
--- a/js/app/packages/channel/Message/SenderIcon.tsx
+++ b/js/app/packages/channel/Message/SenderIcon.tsx
@@ -1,5 +1,10 @@
import { UserIcon } from '@core/component/UserIcon';
+import { isMacroAgentId } from '@core/constant/macroAgent';
+import { senderFromStorageId } from '@queries/channel/message-sender';
+import type { ApiMessageSender } from '@service-storage/generated/schemas/apiMessageSender';
import { cn } from '@ui';
+import { Show } from 'solid-js';
+import { BotIcon } from './BotIcon';
import { useMessage } from './context';
type SenderIconProps = {
@@ -10,6 +15,14 @@ type SenderIconProps = {
export function SenderIcon(props: SenderIconProps) {
const message = useMessage();
+ // Bot senders render their own avatar; Macro AI keeps its dedicated logo
+ // rendering inside UserIcon.
+ const botSender = (): ApiMessageSender | undefined => {
+ const sender = message().sender ?? senderFromStorageId(message().sender_id);
+ if (sender.type !== 'bot' || isMacroAgentId(sender.id)) return undefined;
+ return sender;
+ };
+
return (
<div
class={cn('shrink-0 size-(--user-icon-width)', props.class, {
@@ -17,7 +30,20 @@ export function SenderIcon(props: SenderIconProps) {
})}
aria-hidden={props.hidden ? 'true' : undefined}
>
- {!props.hidden && <UserIcon id={message().sender_id} size="fill" />}
+ {!props.hidden && (
+ <Show
+ when={botSender()}
+ fallback={<UserIcon id={message().sender_id} size="fill" />}
+ >
+ {(bot) => (
+ <BotIcon
+ name={bot().name}
+ avatarUrl={bot().avatar_url}
+ size="fill"
+ />
+ )}
+ </Show>
+ )}
</div>
);
}
diff --git a/js/app/packages/channel/Message/SenderName.tsx b/js/app/packages/channel/Message/SenderName.tsx
index 5dc18e2674..109e841019 100644
--- a/js/app/packages/channel/Message/SenderName.tsx
+++ b/js/app/packages/channel/Message/SenderName.tsx
@@ -1,5 +1,6 @@
import { tryMacroId, useDisplayName } from '@core/user';
import { senderFromStorageId } from '@queries/channel/message-sender';
+import type { ApiMessageSender } from '@service-storage/generated/schemas/apiMessageSender';
import { cn } from '@ui';
import { Show } from 'solid-js';
import { MACRO_AI_BOT_ID, MACRO_AI_NAME } from '../macroAi';
@@ -11,17 +12,21 @@ type SenderNameProps = {
};
/** Resolve a bot sender's display name, or `undefined` for user senders. */
-function botName(senderId: string): string | undefined {
- const sender = senderFromStorageId(senderId);
- if (sender.type !== 'bot') return undefined;
- return sender.id === MACRO_AI_BOT_ID ? MACRO_AI_NAME : 'Bot';
+function botName(
+ senderId: string,
+ sender: ApiMessageSender | undefined
+): string | undefined {
+ const parsed = sender ?? senderFromStorageId(senderId);
+ if (parsed.type !== 'bot') return undefined;
+ if (parsed.name) return parsed.name;
+ return parsed.id === MACRO_AI_BOT_ID ? MACRO_AI_NAME : 'Bot';
}
export function SenderName(props: SenderNameProps) {
const message = useMessage();
const macroId = () => tryMacroId(message().sender_id);
const [displayName] = useDisplayName(macroId());
- const agentName = () => botName(message().sender_id);
+ const agentName = () => botName(message().sender_id, message().sender);
return (
<Show when={!props.hidden}>
diff --git a/js/app/packages/channel/Message/types.ts b/js/app/packages/channel/Message/types.ts
index c1e56b281b..846df03eb2 100644
--- a/js/app/packages/channel/Message/types.ts
+++ b/js/app/packages/channel/Message/types.ts
@@ -1,10 +1,13 @@
import type { ApiCountedReaction } from '@service-storage/generated/schemas/apiCountedReaction';
import type { ApiMessageAttachment } from '@service-storage/generated/schemas/apiMessageAttachment';
+import type { ApiMessageSender } from '@service-storage/generated/schemas/apiMessageSender';
export type MessageData = {
id: string;
content: string;
sender_id: string;
+ /** Structured sender identity; carries bot name/avatar for bot senders. */
+ sender?: ApiMessageSender;
created_at: string;
updated_at: string;
deleted_at?: string | null;
diff --git a/js/app/packages/queries/channel/tests/message-sender.test.ts b/js/app/packages/queries/channel/tests/message-sender.test.ts
index 6b8621631e..1dd462bb8d 100644
--- a/js/app/packages/queries/channel/tests/message-sender.test.ts
+++ b/js/app/packages/queries/channel/tests/message-sender.test.ts
@@ -60,4 +60,25 @@ describe('message sender normalization', () => {
id: '00000000-0000-0000-0000-000000000001',
});
});
+
+ it('keeps enriched bot name and avatar from the API sender', () => {
+ const enriched = {
+ ...legacyMessage('bot|00000000-0000-0000-0000-000000000001'),
+ sender: {
+ type: 'bot' as const,
+ id: '00000000-0000-0000-0000-000000000001',
+ name: 'Deploy Bot',
+ avatar_url: 'https://example.com/bot.png',
+ },
+ };
+
+ const message = normalizeChannelMessageSender(enriched);
+
+ expect(message.sender).toEqual({
+ type: 'bot',
+ id: '00000000-0000-0000-0000-000000000001',
+ name: 'Deploy Bot',
+ avatar_url: 'https://example.com/bot.png',
+ });
+ });
});
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiMessageSender.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiMessageSender.ts
index b5e85e8c33..b2817c0a4f 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/apiMessageSender.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiMessageSender.ts
@@ -4,14 +4,20 @@
* document_storage_service
* OpenAPI spec version: 0.1.0
*/
+import type { ApiMessageSenderAvatarUrl } from './apiMessageSenderAvatarUrl';
+import type { ApiMessageSenderName } from './apiMessageSenderName';
import type { ApiMessageSenderType } from './apiMessageSenderType';
/**
* Public sender identity for channel messages.
*/
export interface ApiMessageSender {
+ /** Avatar URL for bot senders. */
+ avatar_url?: ApiMessageSenderAvatarUrl;
/** Sender id without the storage namespace prefix. */
id: string;
+ /** Display name for bot senders. */
+ name?: ApiMessageSenderName;
/** Sender type. */
type: ApiMessageSenderType;
}
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiMessageSenderAvatarUrl.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiMessageSenderAvatarUrl.ts
new file mode 100644
index 0000000000..1cd44e5c31
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiMessageSenderAvatarUrl.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Avatar URL for bot senders.
+ */
+export type ApiMessageSenderAvatarUrl = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiMessageSenderName.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiMessageSenderName.ts
new file mode 100644
index 0000000000..65847db680
--- /dev/null
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiMessageSenderName.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Display name for bot senders.
+ */
+export type ApiMessageSenderName = string | null;
diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
index 004742cb77..9b7e1a2d1a 100644
--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts
@@ -80,6 +80,8 @@ export * from './apiMessageAttachment';
export * from './apiMessageAttachmentHeight';
export * from './apiMessageAttachmentWidth';
export * from './apiMessageSender';
+export * from './apiMessageSenderAvatarUrl';
+export * from './apiMessageSenderName';
export * from './apiMessageSenderType';
export * from './apiParticipantRole';
export * from './apiResolvedChannelMessage';
diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.ts
index 44cd1580a7..b4268d14f3 100644
--- a/js/app/packages/service-clients/service-storage/generated/zod.ts
+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts
@@ -1648,9 +1648,17 @@ export const getChannelResponse = zod
.describe('Reactions on this message.'),
sender: zod
.object({
+ avatar_url: zod
+ .string()
+ .nullish()
+ .describe('Avatar URL for bot senders.'),
id: zod
.string()
.describe('Sender id without the storage namespace prefix.'),
+ name: zod
+ .string()
+ .nullish()
+ .describe('Display name for bot senders.'),
type: zod.enum(['user', 'bot']).describe('Public sender type.'),
})
.describe('Public sender identity for channel messages.'),
@@ -1716,11 +1724,19 @@ export const getChannelResponse = zod
.describe('Reactions on this reply.'),
sender: zod
.object({
+ avatar_url: zod
+ .string()
+ .nullish()
+ .describe('Avatar URL for bot senders.'),
id: zod
.string()
.describe(
'Sender id without the storage namespace prefix.'
),
+ name: zod
+ .string()
+ .nullish()
+ .describe('Display name for bot senders.'),
type: zod
.enum(['user', 'bot'])
.describe('Public sender type.'),
@@ -2075,9 +2091,17 @@ export const getChannelMessagesResponse = zod
.describe('Reactions on this message.'),
sender: zod
.object({
+ avatar_url: zod
+ .string()
+ .nullish()
+ .describe('Avatar URL for bot senders.'),
id: zod
.string()
.describe('Sender id without the storage namespace prefix.'),
+ name: zod
+ .string()
+ .nullish()
+ .describe('Display name for bot senders.'),
type: zod.enum(['user', 'bot']).describe('Public sender type.'),
})
.describe('Public sender identity for channel messages.'),
@@ -2143,11 +2167,19 @@ export const getChannelMessagesResponse = zod
.describe('Reactions on this reply.'),
sender: zod
.object({
+ avatar_url: zod
+ .string()
+ .nullish()
+ .describe('Avatar URL for bot senders.'),
id: zod
.string()
.describe(
'Sender id without the storage namespace prefix.'
),
+ name: zod
+ .string()
+ .nullish()
+ .describe('Display name for bot senders.'),
type: zod
.enum(['user', 'bot'])
.describe('Public sender type.'),
@@ -2319,9 +2351,17 @@ export const postChannelMessagesResponse = zod
.describe('Reactions on this message.'),
sender: zod
.object({
+ avatar_url: zod
+ .string()
+ .nullish()
+ .describe('Avatar URL for bot senders.'),
id: zod
.string()
.describe('Sender id without the storage namespace prefix.'),
+ name: zod
+ .string()
+ .nullish()
+ .describe('Display name for bot senders.'),
type: zod.enum(['user', 'bot']).describe('Public sender type.'),
})
.describe('Public sender identity for channel messages.'),
@@ -2387,11 +2427,19 @@ export const postChannelMessagesResponse = zod
.describe('Reactions on this reply.'),
sender: zod
.object({
+ avatar_url: zod
+ .string()
+ .nullish()
+ .describe('Avatar URL for bot senders.'),
id: zod
.string()
.describe(
'Sender id without the storage namespace prefix.'
),
+ name: zod
+ .string()
+ .nullish()
+ .describe('Display name for bot senders.'),
type: zod
.enum(['user', 'bot'])
.describe('Public sender type.'),
@@ -2469,9 +2517,17 @@ export const getMessageWithContextResponse = zod
id: zod.uuid().describe('Message id.'),
sender: zod
.object({
+ avatar_url: zod
+ .string()
+ .nullish()
+ .describe('Avatar URL for bot senders.'),
id: zod
.string()
.describe('Sender id without the storage namespace prefix.'),
+ name: zod
+ .string()
+ .nullish()
+ .describe('Display name for bot senders.'),
type: zod.enum(['user', 'bot']).describe('Public sender type.'),
})
.describe('Public sender identity for channel messages.'),
@@ -2541,9 +2597,14 @@ export const getThreadRepliesResponseItem = zod
.describe('Reactions on this reply.'),
sender: zod
.object({
+ avatar_url: zod
+ .string()
+ .nullish()
+ .describe('Avatar URL for bot senders.'),
id: zod
.string()
.describe('Sender id without the storage namespace prefix.'),
+ name: zod.string().nullish().describe('Display name for bot senders.'),
type: zod.enum(['user', 'bot']).describe('Public sender type.'),
})
.describe('Public sender identity for channel messages.'),
diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.json
index 0c76537959..4a271f5fe3 100644
--- a/js/app/packages/service-clients/service-storage/openapi.json
+++ b/js/app/packages/service-clients/service-storage/openapi.json
@@ -9387,10 +9387,18 @@
"description": "Public sender identity for channel messages.",
"required": ["type", "id"],
"properties": {
+ "avatar_url": {
+ "type": ["string", "null"],
+ "description": "Avatar URL for bot senders."
+ },
"id": {
"type": "string",
"description": "Sender id without the storage namespace prefix."
},
+ "name": {
+ "type": ["string", "null"],
+ "description": "Display name for bot senders."
+ },
"type": {
"$ref": "#/components/schemas/ApiMessageSenderType",
"description": "Sender type."
diff --git a/rust/cloud-storage/.sqlx/query-827d839ae763a24c7faac855046d760a9d51f927e073bd9b2f07c690882fac03.json b/rust/cloud-storage/.sqlx/query-827d839ae763a24c7faac855046d760a9d51f927e073bd9b2f07c690882fac03.json
new file mode 100644
index 0000000000..dea09841c7
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-827d839ae763a24c7faac855046d760a9d51f927e073bd9b2f07c690882fac03.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, name, avatar_url\n FROM bots\n WHERE id = ANY($1)\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "avatar_url",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "827d839ae763a24c7faac855046d760a9d51f927e073bd9b2f07c690882fac03"
+}
diff --git a/rust/cloud-storage/.sqlx/query-cf156bbe38f634e623a39ae1d388cad0a5e18597f640111861f469e273e56e88.json b/rust/cloud-storage/.sqlx/query-cf156bbe38f634e623a39ae1d388cad0a5e18597f640111861f469e273e56e88.json
new file mode 100644
index 0000000000..09ef7d3137
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-cf156bbe38f634e623a39ae1d388cad0a5e18597f640111861f469e273e56e88.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT name, avatar_url\n FROM bots\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "avatar_url",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ true
+ ]
+ },
+ "hash": "cf156bbe38f634e623a39ae1d388cad0a5e18597f640111861f469e273e56e88"
+}
diff --git a/rust/cloud-storage/channel_bots/src/domain/service/tests.rs b/rust/cloud-storage/channel_bots/src/domain/service/tests.rs
index a9536fb325..7bbaa2563c 100644
--- a/rust/cloud-storage/channel_bots/src/domain/service/tests.rs
+++ b/rust/cloud-storage/channel_bots/src/domain/service/tests.rs
@@ -133,6 +133,7 @@ fn context_message(
updated_at: now,
edited_at: None,
deleted_at: None,
+ bot_profile: None,
}
}
diff --git a/rust/cloud-storage/channels/src/domain/models.rs b/rust/cloud-storage/channels/src/domain/models.rs
index 00daf858e3..331b4b5c15 100644
--- a/rust/cloud-storage/channels/src/domain/models.rs
+++ b/rust/cloud-storage/channels/src/domain/models.rs
@@ -93,6 +93,15 @@ impl Serialize for Sender {
}
}
+/// Public bot profile attached to bot-authored messages.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
+pub struct BotSenderProfile {
+ /// Bot display name.
+ pub name: String,
+ /// Bot avatar URL.
+ pub avatar_url: Option<String>,
+}
+
/// Request to fetch a page of channel messages.
#[derive(Debug)]
pub struct GetChannelMessagesRequest {
@@ -208,6 +217,8 @@ pub struct ChannelMessage {
pub channel_id: Uuid,
/// User who sent the message.
pub sender_id: String,
+ /// Bot profile when the sender is a bot.
+ pub bot_profile: Option<BotSenderProfile>,
/// Message body.
pub content: String,
/// When the message was created.
@@ -261,6 +272,8 @@ pub struct ThreadReply {
pub id: Uuid,
/// User who sent the reply.
pub sender_id: String,
+ /// Bot profile when the sender is a bot.
+ pub bot_profile: Option<BotSenderProfile>,
/// Reply body.
pub content: String,
/// When the reply was created.
@@ -396,6 +409,8 @@ pub struct ChannelContextMessage {
pub thread_id: Option<Uuid>,
/// User who sent the message.
pub sender_id: String,
+ /// Bot profile when the sender is a bot.
+ pub bot_profile: Option<BotSenderProfile>,
/// Message content.
pub content: String,
/// When the message was created.
diff --git a/rust/cloud-storage/channels/src/domain/ports.rs b/rust/cloud-storage/channels/src/domain/ports.rs
index 87556cf046..44c92c95dc 100644
--- a/rust/cloud-storage/channels/src/domain/ports.rs
+++ b/rust/cloud-storage/channels/src/domain/ports.rs
@@ -1,15 +1,15 @@
use crate::domain::events::ChannelEvent;
use crate::domain::models::{
- Activity, ActivityType, AddParticipantsRequest, AttachmentEntityReference, ChannelAttachment,
- ChannelAttachmentType, ChannelContextMessage, ChannelInfo, ChannelMessageFilters,
- ChannelMetadata, ChannelParticipant, ChannelPreview, ChannelPreviewRow, CountedReaction,
- CreateChannelRequest, CreateChannelResponse, CreateEntityMentionOptions, DeleteMessageQuery,
- EntityMention, GetOrCreateChannelResponse, GetOrCreateDmRequest, GetOrCreatePrivateRequest,
- MessageAttachment, MessagePageDirection, MutatedAttachment, MutatedMessage,
- NewChannelAttachment, PatchChannelRequest, PatchMessageRequest, PostMessageRequest,
- PostMessageResponse, PostReactionRequest, PostTypingRequest, ReferencedShareItem,
- RemoveParticipantsRequest, ResolvedChannelMessage, Sender, SimpleMention, ThreadData,
- ThreadReply, ThreadReplyRow, TopLevelMessageRow,
+ Activity, ActivityType, AddParticipantsRequest, AttachmentEntityReference, BotId,
+ BotSenderProfile, ChannelAttachment, ChannelAttachmentType, ChannelContextMessage, ChannelInfo,
+ ChannelMessageFilters, ChannelMetadata, ChannelParticipant, ChannelPreview, ChannelPreviewRow,
+ CountedReaction, CreateChannelRequest, CreateChannelResponse, CreateEntityMentionOptions,
+ DeleteMessageQuery, EntityMention, GetOrCreateChannelResponse, GetOrCreateDmRequest,
+ GetOrCreatePrivateRequest, MessageAttachment, MessagePageDirection, MutatedAttachment,
+ MutatedMessage, NewChannelAttachment, PatchChannelRequest, PatchMessageRequest,
+ PostMessageRequest, PostMessageResponse, PostReactionRequest, PostTypingRequest,
+ ReferencedShareItem, RemoveParticipantsRequest, ResolvedChannelMessage, Sender, SimpleMention,
+ ThreadData, ThreadReply, ThreadReplyRow, TopLevelMessageRow,
};
use crate::domain::side_effects::{
ChannelDocumentMention, ChannelNotificationEffect, ChannelRealtimeEffect,
@@ -369,6 +369,13 @@ pub trait ChannelRepo: Send + Sync + 'static {
channel_id: Uuid,
message_id: Uuid,
) -> impl Future<Output = Result<Vec<CountedReaction>, Self::Err>> + Send;
+
+ /// Batch-fetch public bot profiles by bot id. Includes soft-deleted bots so
+ /// historical messages keep their sender identity.
+ fn get_bot_profiles(
+ &self,
+ bot_ids: &[BotId],
+ ) -> impl Future<Output = Result<HashMap<BotId, BotSenderProfile>, Self::Err>> + Send;
}
/// Service for channel reads and mutations.
@@ -825,6 +832,12 @@ pub trait ChannelSideEffectContext: Send + Sync + 'static {
&self,
sender_id: MacroUserIdStr<'static>,
) -> impl Future<Output = Option<String>> + Send;
+
+ /// Load a bot's public profile for realtime payload enrichment.
+ fn get_bot_sender_profile(
+ &self,
+ bot_id: BotId,
+ ) -> impl Future<Output = Option<BotSenderProfile>> + Send;
}
/// Handler for durable channel events.
diff --git a/rust/cloud-storage/channels/src/domain/service.rs b/rust/cloud-storage/channels/src/domain/service.rs
index ac29eab815..43db90ace8 100644
--- a/rust/cloud-storage/channels/src/domain/service.rs
+++ b/rust/cloud-storage/channels/src/domain/service.rs
@@ -1,16 +1,16 @@
use crate::domain::{
events::ChannelEvent,
models::{
- Activity, ActivityType, AddParticipantsRequest, AttachmentEntityReference,
- ChannelAttachmentType, ChannelContextMessage, ChannelMessage, ChannelMessageFilters,
- ChannelMetadata, ChannelParticipant, ChannelPreview, ChannelPreviewData, ChannelType,
- CreateEntityMentionOptions, DeleteMessageQuery, EntityMention, GetOrCreateAction,
- GetOrCreateChannelResponse, GetOrCreateDmRequest, GetOrCreatePrivateRequest,
- MessagePageDirection, NewChannelAttachment, ParticipantRole, PatchChannelRequest,
- PatchMessageRequest, PostMessageRequest, PostMessageResponse, PostReactionRequest,
- PostTypingRequest, ReactionAction, ReferencedShareItem, RemoveParticipantsRequest,
- ResolvedChannelMessage, Sender, SimpleMention, ThreadInfo, ThreadReply, TopLevelMessageRow,
- WithChannelId,
+ Activity, ActivityType, AddParticipantsRequest, AttachmentEntityReference, BotId,
+ BotSenderProfile, ChannelAttachmentType, ChannelContextMessage, ChannelMessage,
+ ChannelMessageFilters, ChannelMetadata, ChannelParticipant, ChannelPreview,
+ ChannelPreviewData, ChannelType, CreateEntityMentionOptions, DeleteMessageQuery,
+ EntityMention, GetOrCreateAction, GetOrCreateChannelResponse, GetOrCreateDmRequest,
+ GetOrCreatePrivateRequest, MessagePageDirection, NewChannelAttachment, ParticipantRole,
+ PatchChannelRequest, PatchMessageRequest, PostMessageRequest, PostMessageResponse,
+ PostReactionRequest, PostTypingRequest, ReactionAction, ReferencedShareItem,
+ RemoveParticipantsRequest, ResolvedChannelMessage, Sender, SimpleMention, ThreadInfo,
+ ThreadReply, TopLevelMessageRow, WithChannelId,
},
ports::{
ChannelAttachmentsPage, ChannelEventDispatcher, ChannelMessagesErr,
@@ -20,6 +20,7 @@ use crate::domain::{
};
use macro_user_id::user_id::MacroUserIdStr;
use models_pagination::{CreatedAt, PaginateOn, Query};
+use std::collections::{HashMap, HashSet};
use uuid::Uuid;
#[cfg(test)]
@@ -109,19 +110,23 @@ where
.map_err(anyhow::Error::from)?;
let mut all_ids: Vec<Uuid> = parent_ids.clone();
+ let mut sender_ids: Vec<&str> = rows.iter().map(|r| r.sender_id.as_str()).collect();
for td in thread_data.values() {
for reply in &td.preview_replies {
all_ids.push(reply.id);
+ sender_ids.push(reply.sender_id.as_str());
}
}
- let (reactions, attachments) = tokio::join!(
+ let (reactions, attachments, bot_profiles) = tokio::join!(
self.repo.get_reactions_batch(&all_ids),
self.repo.get_attachments_batch(&all_ids),
+ self.get_bot_profiles_for_senders(sender_ids),
);
let reactions = reactions.map_err(anyhow::Error::from)?;
let attachments = attachments.map_err(anyhow::Error::from)?;
+ let bot_profiles = bot_profiles?;
let messages: Vec<ChannelMessage> = rows
.into_iter()
@@ -133,6 +138,7 @@ where
.iter()
.map(|r| ThreadReply {
id: r.id,
+ bot_profile: bot_profile_for(&bot_profiles, &r.sender_id),
sender_id: r.sender_id.clone(),
content: r.content.clone(),
created_at: r.created_at,
@@ -148,6 +154,7 @@ where
ChannelMessage {
id: row.id,
channel_id: row.channel_id,
+ bot_profile: bot_profile_for(&bot_profiles, &row.sender_id),
sender_id: row.sender_id,
content: row.content,
created_at: row.created_at,
@@ -167,6 +174,36 @@ where
Ok(messages)
}
+
+ /// Batch-fetch public bot profiles for any bot senders among `sender_ids`.
+ async fn get_bot_profiles_for_senders(
+ &self,
+ sender_ids: impl IntoIterator<Item = &str>,
+ ) -> Result<HashMap<BotId, BotSenderProfile>, ChannelMessagesErr> {
+ let bot_ids: HashSet<BotId> = sender_ids
+ .into_iter()
+ .filter_map(|id| BotId::parse_storage_str(id).ok())
+ .collect();
+ if bot_ids.is_empty() {
+ return Ok(HashMap::new());
+ }
+
+ let bot_ids: Vec<BotId> = bot_ids.into_iter().collect();
+ self.repo
+ .get_bot_profiles(&bot_ids)
+ .await
+ .map_err(anyhow::Error::from)
+ .map_err(ChannelMessagesErr::Repo)
+ }
+}
+
+/// Resolve the bot profile for a sender id, if the sender is a known bot.
+fn bot_profile_for(
+ profiles: &HashMap<BotId, BotSenderProfile>,
+ sender_id: &str,
+) -> Option<BotSenderProfile> {
+ let bot_id = BotId::parse_storage_str(sender_id).ok()?;
+ profiles.get(&bot_id).cloned()
}
fn lower_macro_users(users: &[String]) -> Vec<String> {
@@ -1337,11 +1374,21 @@ where
before: i64,
after: i64,
) -> Result<Vec<ChannelContextMessage>, ChannelMessagesErr> {
- self.repo
+ let mut messages = self
+ .repo
.get_messages_with_context(channel_id, message_id, before.max(0), after.max(0))
.await
.map_err(anyhow::Error::from)
- .map_err(ChannelMessagesErr::Repo)
+ .map_err(ChannelMessagesErr::Repo)?;
+
+ let bot_profiles = self
+ .get_bot_profiles_for_senders(messages.iter().map(|m| m.sender_id.as_str()))
+ .await?;
+ for message in &mut messages {
+ message.bot_profile = bot_profile_for(&bot_profiles, &message.sender_id);
+ }
+
+ Ok(messages)
}
#[tracing::instrument(err, skip(self, user_id))]
@@ -1435,18 +1482,21 @@ where
}
let reply_ids: Vec<Uuid> = reply_rows.iter().map(|row| row.id).collect();
- let (reactions, attachments) = tokio::join!(
+ let (reactions, attachments, bot_profiles) = tokio::join!(
self.repo.get_reactions_batch(&reply_ids),
self.repo.get_attachments_batch(&reply_ids),
+ self.get_bot_profiles_for_senders(reply_rows.iter().map(|row| row.sender_id.as_str())),
);
let reactions = reactions.map_err(anyhow::Error::from)?;
let attachments = attachments.map_err(anyhow::Error::from)?;
+ let bot_profiles = bot_profiles?;
let replies = reply_rows
.into_iter()
.map(|row| ThreadReply {
id: row.id,
+ bot_profile: bot_profile_for(&bot_profiles, &row.sender_id),
sender_id: row.sender_id,
content: row.content,
created_at: row.created_at,
diff --git a/rust/cloud-storage/channels/src/domain/service/test.rs b/rust/cloud-storage/channels/src/domain/service/test.rs
index 751bb5badd..6319d8b75d 100644
--- a/rust/cloud-storage/channels/src/domain/service/test.rs
+++ b/rust/cloud-storage/channels/src/domain/service/test.rs
@@ -2,7 +2,7 @@ use super::*;
use crate::domain::{
events::ChannelEvent,
models::{
- Activity, ActivityType, BotId, ChannelAttachment, ChannelAttachmentType,
+ Activity, ActivityType, BotId, BotSenderProfile, ChannelAttachment, ChannelAttachmentType,
ChannelContextMessage, ChannelInfo, ChannelMessageFilters, ChannelMetadata,
ChannelParticipant, ChannelType, CountedReaction, CreateEntityMentionOptions,
EntityMention, MessageAttachment, MessagePageDirection, MutatedAttachment, MutatedMessage,
@@ -181,6 +181,97 @@ async fn returns_messages_with_thread_info() {
assert!(page.next_cursor.is_none());
}
+#[tokio::test]
+async fn attaches_bot_profiles_to_bot_authored_messages() {
+ let seeded_bot = BotId::from_uuid(Uuid::new_v4());
+ let unseeded_bot = bot_id::MACRO_AI_BOT_ID;
+ let parent_id = Uuid::new_v4();
+ let macro_ai_msg_id = Uuid::new_v4();
+
+ let mut bot_row = make_row(parent_id, 10);
+ bot_row.sender_id = seeded_bot.to_storage_string();
+ let mut macro_ai_row = make_row(macro_ai_msg_id, 5);
+ macro_ai_row.sender_id = unseeded_bot.to_storage_string();
+
+ let reply_row = ThreadReplyRow {
+ id: Uuid::new_v4(),
+ thread_id: parent_id,
+ sender_id: seeded_bot.to_storage_string(),
+ content: "reply".into(),
+ created_at: Utc::now(),
+ updated_at: Utc::now(),
+ edited_at: None,
+ };
+
+ let profile = BotSenderProfile {
+ name: "Deploy Bot".to_string(),
+ avatar_url: Some("https://example.com/bot.png".to_string()),
+ };
+
+ let mut repo = MockChannelRepo::new();
+ let rows = vec![bot_row, macro_ai_row];
+ repo.expect_get_top_level_messages()
+ .returning(move |_, _, _, _, _, _| {
+ let rows = rows.clone();
+ Box::pin(async move {
+ Ok(TopLevelMessagesQueryResult {
+ rows,
+ has_more_newer: false,
+ })
+ })
+ });
+ let reply_clone = reply_row.clone();
+ repo.expect_get_thread_data().returning(move |_, _| {
+ let mut map = HashMap::new();
+ map.insert(
+ parent_id,
+ ThreadData {
+ reply_count: 1,
+ latest_reply_at: None,
+ preview_replies: vec![reply_clone.clone()],
+ },
+ );
+ Box::pin(async move { Ok(map) })
+ });
+ repo.expect_get_reactions_batch()
+ .returning(|_| Box::pin(async { Ok(HashMap::new()) }));
+ repo.expect_get_attachments_batch()
+ .returning(|_| Box::pin(async { Ok(HashMap::new()) }));
+ let profile_clone = profile.clone();
+ repo.expect_get_bot_profiles().returning(move |bot_ids| {
+ assert_eq!(bot_ids.len(), 2, "bot senders should be deduplicated");
+ assert!(bot_ids.contains(&seeded_bot));
+ assert!(bot_ids.contains(&unseeded_bot));
+ let mut map = HashMap::new();
+ map.insert(seeded_bot, profile_clone.clone());
+ Box::pin(async move { Ok(map) })
+ });
+
+ let svc = ChannelServiceImpl::new(repo);
+ let page = svc
+ .get_channel_messages(
+ Uuid::nil(),
+ Query::Sort(CreatedAt, ()),
+ MessagePageDirection::Older,
+ 50,
+ &ChannelMessageFilters::default(),
+ None,
+ )
+ .await
+ .unwrap()
+ .page;
+
+ assert_eq!(page.items.len(), 2);
+ let bot_msg = page.items.iter().find(|m| m.id == parent_id).unwrap();
+ assert_eq!(bot_msg.bot_profile, Some(profile.clone()));
+ assert_eq!(bot_msg.thread.preview[0].bot_profile, Some(profile));
+
+ // The Macro AI system bot has no `bots` row, so it stays unenriched and the
+ // frontend falls back to its built-in special case.
+ let macro_ai_msg = page.items.iter().find(|m| m.id == macro_ai_msg_id).unwrap();
+ assert!(macro_ai_msg.bot_profile.is_none());
+}
+
#[derive(Clone)]
struct FakeMutationRepo {
state: Arc<Mutex<FakeMutationRepoState>>,
@@ -650,6 +741,13 @@ impl ChannelRepo for FakeMutationRepo {
users: vec!["macro|[email protected]".to_string()],
}])
}
+
+ async fn get_bot_profiles(
+ &self,
+ _bot_ids: &[BotId],
+ ) -> Result<HashMap<BotId, BotSenderProfile>, Self::Err> {
+ Ok(HashMap::new())
+ }
}
#[derive(Clone, Default)]
diff --git a/rust/cloud-storage/channels/src/domain/side_effects.rs b/rust/cloud-storage/channels/src/domain/side_effects.rs
index 1a307c3400..a030c5378a 100644
--- a/rust/cloud-storage/channels/src/domain/side_effects.rs
+++ b/rust/cloud-storage/channels/src/domain/side_effects.rs
@@ -3,7 +3,7 @@
use crate::domain::{
events::ChannelEvent,
models::{
- BotId, ChannelMetadata, ChannelParticipant, ChannelType, CountedReaction,
+ BotId, BotSenderProfile, ChannelMetadata, ChannelParticipant, ChannelType, CountedReaction,
MutatedAttachment, MutatedMessage, Sender, SimpleMention, TypingAction,
},
ports::{
@@ -71,6 +71,8 @@ pub enum ChannelRealtimeEffect {
recipients: Vec<MacroUserIdStr<'static>>,
/// Persisted message payload.
message: MutatedMessage,
+ /// Public bot profile when the sender is a bot.
+ bot_profile: Option<BotSenderProfile>,
/// Client mutation nonce echoed to listeners.
nonce: Option<String>,
},
@@ -415,9 +417,11 @@ where
..
} => {
let message_id = message.id;
+ let bot_profile = self.bot_profile_for_message(&message).await;
self.publish_realtime(ChannelRealtimeEffect::Message {
recipients,
message,
+ bot_profile,
nonce,
})
.await;
@@ -431,9 +435,11 @@ where
..
} => {
let message_id = message.id;
+ let bot_profile = self.bot_profile_for_message(&message).await;
self.publish_realtime(ChannelRealtimeEffect::Message {
recipients,
message,
+ bot_profile,
nonce,
})
.await;
@@ -527,9 +533,11 @@ where
nonce,
} = event;
let recipients = participant_ids(&participants);
+ let bot_profile = self.bot_profile_for_message(&message).await;
self.publish_realtime(ChannelRealtimeEffect::Message {
recipients: recipients.clone(),
message: message.clone(),
+ bot_profile,
nonce: nonce.clone(),
})
.await;
@@ -561,6 +569,14 @@ where
.await;
}
+ /// Resolve the public bot profile when the message sender is a bot.
+ async fn bot_profile_for_message(&self, message: &MutatedMessage) -> Option<BotSenderProfile> {
+ match &message.sender_id {
+ Sender::Bot(bot_id) => self.context.get_bot_sender_profile(*bot_id).await,
+ Sender::User(_) => None,
+ }
+ }
+
async fn publish_realtime(&self, effect: ChannelRealtimeEffect) {
if let Err(err) = self.realtime.publish(effect).await {
let err: anyhow::Error = err.into();
@@ -1079,6 +1095,13 @@ mod tests {
) -> Option<String> {
Some("https://example.com/avatar.png".to_string())
}
+
+ async fn get_bot_sender_profile(&self, _bot_id: BotId) -> Option<BotSenderProfile> {
+ Some(BotSenderProfile {
+ name: "Test Bot".to_string(),
+ avatar_url: Some("https://example.com/bot.png".to_string()),
+ })
+ }
}
#[derive(Clone, Default)]
@@ -1219,6 +1242,7 @@ mod tests {
recipients,
message,
nonce,
+ ..
} = &realtime_effects[0]
else {
panic!("expected message realtime effect");
diff --git a/rust/cloud-storage/channels/src/inbound/axum_router.rs b/rust/cloud-storage/channels/src/inbound/axum_router.rs
index 9c8f01cfa6..63a6d81d87 100644
--- a/rust/cloud-storage/channels/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/channels/src/inbound/axum_router.rs
@@ -3,10 +3,10 @@ mod test;
use crate::domain::models::{
Activity, ActivityType, AttachmentChannelReference, AttachmentEntityReference,
- AttachmentGenericReference, ChannelAttachment, ChannelAttachmentType, ChannelContextMessage,
- ChannelMessage, ChannelMessageKind, ChannelParticipant, ChannelType, CountedReaction,
- CreateEntityMentionOptions, MessageAttachment, MessagePageDirection, ParticipantRole,
- ResolvedChannelMessage, Sender, ThreadInfo, ThreadReply,
+ AttachmentGenericReference, BotSenderProfile, ChannelAttachment, ChannelAttachmentType,
+ ChannelContextMessage, ChannelMessage, ChannelMessageKind, ChannelParticipant, ChannelType,
+ CountedReaction, CreateEntityMentionOptions, MessageAttachment, MessagePageDirection,
+ ParticipantRole, ResolvedChannelMessage, Sender, ThreadInfo, ThreadReply,
};
pub use crate::domain::models::{
AddParticipantsRequest, ChannelPreview, ChannelPreviewData, CreateChannelRequest,
@@ -1603,6 +1603,12 @@ pub struct ApiMessageSender {
sender_type: ApiMessageSenderType,
/// Sender id without the storage namespace prefix.
id: String,
+ /// Display name for bot senders.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ name: Option<String>,
+ /// Avatar URL for bot senders.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ avatar_url: Option<String>,
}
/// Public sender type.
@@ -1621,17 +1627,35 @@ impl ApiMessageSender {
Ok(Sender::Bot(bot_id)) => Self {
sender_type: ApiMessageSenderType::Bot,
id: bot_id.as_uuid().to_string(),
+ name: None,
+ avatar_url: None,
},
Ok(Sender::User(user_id)) => Self {
sender_type: ApiMessageSenderType::User,
id: user_id.to_string(),
+ name: None,
+ avatar_url: None,
},
Err(_) => Self {
sender_type: ApiMessageSenderType::User,
id: sender_id.to_string(),
+ name: None,
+ avatar_url: None,
},
}
}
+
+ /// Build a sender identity, attaching the bot profile for bot senders.
+ fn from_message_sender(sender_id: &str, bot_profile: Option<BotSenderProfile>) -> Self {
+ let mut sender = Self::from_storage_string(sender_id);
+ if matches!(sender.sender_type, ApiMessageSenderType::Bot)
+ && let Some(profile) = bot_profile
+ {
+ sender.name = Some(profile.name);
+ sender.avatar_url = profile.avatar_url;
+ }
+ sender
+ }
}
/// A top-level channel message with thread info.
@@ -1668,7 +1692,7 @@ impl From<ChannelMessage> for ApiChannelMessage {
Self {
id: m.id,
channel_id: m.channel_id,
- sender: ApiMessageSender::from_storage_string(&m.sender_id),
+ sender: ApiMessageSender::from_message_sender(&m.sender_id, m.bot_profile),
sender_id: m.sender_id,
content: m.content,
created_at: m.created_at,
@@ -1728,7 +1752,7 @@ impl From<ChannelContextMessage> for ApiChannelContextMessage {
id: message.id,
channel_id: message.channel_id,
thread_id: message.thread_id,
- sender: ApiMessageSender::from_storage_string(&message.sender_id),
+ sender: ApiMessageSender::from_message_sender(&message.sender_id, message.bot_profile),
sender_id: message.sender_id,
content: message.content,
created_at: message.created_at,
@@ -1883,7 +1907,7 @@ impl From<ThreadReply> for ApiThreadReply {
fn from(r: ThreadReply) -> Self {
Self {
id: r.id,
- sender: ApiMessageSender::from_storage_string(&r.sender_id),
+ sender: ApiMessageSender::from_message_sender(&r.sender_id, r.bot_profile),
sender_id: r.sender_id,
content: r.content,
created_at: r.created_at,
diff --git a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
index 0266c2afb3..f92fdfaa16 100644
--- a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
+++ b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs
@@ -264,6 +264,7 @@ impl ChannelService for MockService {
channel_id,
thread_id: None,
sender_id: "macro|[email protected]".to_string(),
+ bot_profile: None,
content: "message context".to_string(),
created_at: now,
updated_at: now,
@@ -1054,6 +1055,7 @@ impl ChannelService for AroundHasItemsService {
id: Uuid::new_v4(),
channel_id,
sender_id: "macro|[email protected]".to_string(),
+ bot_profile: None,
content: "hello".to_string(),
created_at: now,
updated_at: now,
diff --git a/rust/cloud-storage/channels/src/inbound/toolset/types.rs b/rust/cloud-storage/channels/src/inbound/toolset/types.rs
index 1946d77b38..1d944b1272 100644
--- a/rust/cloud-storage/channels/src/inbound/toolset/types.rs
+++ b/rust/cloud-storage/channels/src/inbound/toolset/types.rs
@@ -403,6 +403,7 @@ mod tests {
ThreadReply {
id: Uuid::new_v4(),
sender_id: "macro|[email protected]".to_string(),
+ bot_profile: None,
content: "reply".to_string(),
created_at: dt(seconds),
updated_at: dt(seconds),
@@ -418,6 +419,7 @@ mod tests {
id,
channel_id: Uuid::new_v4(),
sender_id: "macro|[email protected]".to_string(),
+ bot_profile: None,
content: "parent".to_string(),
created_at: dt(1),
updated_at: dt(1),
diff --git a/rust/cloud-storage/channels/src/outbound/connection_gateway_realtime.rs b/rust/cloud-storage/channels/src/outbound/connection_gateway_realtime.rs
index c7d545e5a1..1709e933c9 100644
--- a/rust/cloud-storage/channels/src/outbound/connection_gateway_realtime.rs
+++ b/rust/cloud-storage/channels/src/outbound/connection_gateway_realtime.rs
@@ -1,7 +1,12 @@
//! Connection-gateway realtime adapter for channel side effects.
+#[cfg(test)]
+mod test;
+
use crate::domain::{
- models::{CountedReaction, MutatedAttachment, TypingAction},
+ models::{
+ BotSenderProfile, CountedReaction, MutatedAttachment, MutatedMessage, Sender, TypingAction,
+ },
ports::ChannelRealtimePublisher,
side_effects::ChannelRealtimeEffect,
};
@@ -55,12 +60,14 @@ impl ChannelRealtimePublisher for ConnectionGatewayChannelRealtimePublisher {
ChannelRealtimeEffect::Message {
recipients,
message,
+ bot_profile,
nonce,
} => {
+ let sender = MessageRealtimeSender::new(&message.sender_id, bot_profile);
self.send_update(
"comms_message",
WithNonce {
- data: message,
+ data: MessageRealtimeData { message, sender },
nonce,
},
recipients,
@@ -144,6 +151,44 @@ struct WithNonce<T: Serialize> {
nonce: Option<String>,
}
+#[derive(Serialize)]
+struct MessageRealtimeData {
+ #[serde(flatten)]
+ message: MutatedMessage,
+ /// Structured sender identity, shaped like the REST `ApiMessageSender`.
+ sender: MessageRealtimeSender,
+}
+
+#[derive(Serialize)]
+struct MessageRealtimeSender {
+ #[serde(rename = "type")]
+ sender_type: &'static str,
+ id: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ name: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ avatar_url: Option<String>,
+}
+
+impl MessageRealtimeSender {
+ fn new(sender: &Sender, bot_profile: Option<BotSenderProfile>) -> Self {
+ match sender {
+ Sender::Bot(bot_id) => Self {
+ sender_type: "bot",
+ id: bot_id.as_uuid().to_string(),
+ name: bot_profile.as_ref().map(|profile| profile.name.clone()),
+ avatar_url: bot_profile.and_then(|profile| profile.avatar_url),
+ },
+ Sender::User(user_id) => Self {
+ sender_type: "user",
+ id: user_id.as_ref().to_string(),
+ name: None,
+ avatar_url: None,
+ },
+ }
+ }
+}
+
#[derive(Serialize)]
struct AttachmentRealtimeData {
channel_id: Uuid,
diff --git a/rust/cloud-storage/channels/src/outbound/connection_gateway_realtime/test.rs b/rust/cloud-storage/channels/src/outbound/connection_gateway_realtime/test.rs
new file mode 100644
index 0000000000..9201151237
--- /dev/null
+++ b/rust/cloud-storage/channels/src/outbound/connection_gateway_realtime/test.rs
@@ -0,0 +1,70 @@
+use super::*;
+use crate::domain::models::MutatedMessage;
+use bot_id::BotId;
+use chrono::Utc;
+
+fn message(sender_id: Sender) -> MutatedMessage {
+ let now = Utc::now();
+ MutatedMessage {
+ id: Uuid::new_v4(),
+ channel_id: Uuid::new_v4(),
+ thread_id: None,
+ sender_id,
+ content: "hello".to_string(),
+ created_at: now,
+ updated_at: now,
+ edited_at: None,
+ deleted_at: None,
+ }
+}
+
+#[test]
+fn bot_message_payload_includes_enriched_sender() {
+ let bot_id = BotId::from_uuid(Uuid::new_v4());
+ let message = message(Sender::Bot(bot_id));
+ let sender = MessageRealtimeSender::new(
+ &message.sender_id,
+ Some(BotSenderProfile {
+ name: "Deploy Bot".to_string(),
+ avatar_url: Some("https://example.com/bot.png".to_string()),
+ }),
+ );
+
+ let payload = serde_json::to_value(WithNonce {
+ data: MessageRealtimeData { message, sender },
+ nonce: Some("nonce-1".to_string()),
+ })
+ .unwrap();
+
+ // Flattened message fields stay at the top level for existing clients.
+ assert_eq!(payload["sender_id"], bot_id.to_storage_string());
+ assert_eq!(payload["content"], "hello");
+ assert_eq!(payload["nonce"], "nonce-1");
+ assert_eq!(payload["sender"]["type"], "bot");
+ assert_eq!(payload["sender"]["id"], bot_id.as_uuid().to_string());
+ assert_eq!(payload["sender"]["name"], "Deploy Bot");
+ assert_eq!(
+ payload["sender"]["avatar_url"],
+ "https://example.com/bot.png"
+ );
+}
+
+#[test]
+fn user_message_payload_omits_bot_fields() {
+ let user = macro_user_id::user_id::MacroUserIdStr::try_from_email("[email protected]")
+ .expect("valid email");
+ let message = message(Sender::User(user.clone()));
+ let sender = MessageRealtimeSender::new(&message.sender_id, None);
+
+ let payload = serde_json::to_value(WithNonce {
+ data: MessageRealtimeData { message, sender },
+ nonce: None,
+ })
+ .unwrap();
+
+ assert_eq!(payload["sender"]["type"], "user");
+ assert_eq!(payload["sender"]["id"], user.as_ref());
+ assert!(payload["sender"].get("name").is_none());
+ assert!(payload["sender"].get("avatar_url").is_none());
+ assert!(payload.get("nonce").is_none());
+}
diff --git a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
index d81a58537c..b70549ba0b 100644
--- a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
+++ b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs
@@ -4,13 +4,13 @@ mod tests;
use crate::domain::{
models::{
Activity, ActivityType, AttachmentChannelReference, AttachmentEntityReference,
- AttachmentGenericReference, ChannelAttachment, ChannelAttachmentType,
- ChannelContextMessage, ChannelInfo, ChannelMessageFilters, ChannelMessageKind,
- ChannelMetadata, ChannelParticipant, ChannelPreviewRow, ChannelType, CountedReaction,
- CreateChannelRequest, CreateEntityMentionOptions, EntityMention, MessageAttachment,
- MessagePageDirection, MutatedAttachment, MutatedMessage, NewChannelAttachment,
- ParticipantRole, PatchChannelRequest, ResolvedChannelMessage, Sender, SimpleMention,
- ThreadData, ThreadReplyRow, TopLevelMessageRow,
+ AttachmentGenericReference, BotId, BotSenderProfile, ChannelAttachment,
+ ChannelAttachmentType, ChannelContextMessage, ChannelInfo, ChannelMessageFilters,
+ ChannelMessageKind, ChannelMetadata, ChannelParticipant, ChannelPreviewRow, ChannelType,
+ CountedReaction, CreateChannelRequest, CreateEntityMentionOptions, EntityMention,
+ MessageAttachment, MessagePageDirection, MutatedAttachment, MutatedMessage,
+ NewChannelAttachment, ParticipantRole, PatchChannelRequest, ResolvedChannelMessage, Sender,
+ SimpleMention, ThreadData, ThreadReplyRow, TopLevelMessageRow,
},
ports::{ChannelRepo, TopLevelMessagesQueryResult},
};
@@ -146,6 +146,8 @@ impl From<ContextMessageRow> for ChannelContextMessage {
channel_id: row.channel_id,
thread_id: row.thread_id,
sender_id: row.sender_id,
+ // Bot profiles are joined in the service layer.
+ bot_profile: None,
content: row.content,
created_at: row.created_at,
updated_at: row.updated_at,
@@ -2532,4 +2534,41 @@ impl ChannelRepo for PgChannelsRepo {
.collect::<Vec<_>>();
Ok(group_counted_reactions(reactions))
}
+
+ async fn get_bot_profiles(
+ &self,
+ bot_ids: &[BotId],
+ ) -> Result<HashMap<BotId, BotSenderProfile>, Self::Err> {
+ if bot_ids.is_empty() {
+ return Ok(HashMap::new());
+ }
+
+ let ids: Vec<Uuid> = bot_ids.iter().map(|id| id.as_uuid()).collect();
+ // Soft-deleted bots are included on purpose so historical messages
+ // keep their sender identity.
+ let rows = sqlx::query!(
+ r#"
+ SELECT id, name, avatar_url
+ FROM bots
+ WHERE id = ANY($1)
+ "#,
+ &ids,
+ )
+ .fetch_all(&self.pool)
+ .await
+ .context("unable to fetch bot profiles")?;
+
+ Ok(rows
+ .into_iter()
+ .map(|row| {
+ (
+ BotId::from_uuid(row.id),
+ BotSenderProfile {
+ name: row.name,
+ avatar_url: row.avatar_url,
+ },
+ )
+ })
+ .collect())
+ }
}
diff --git a/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs b/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs
index dbae112bee..a8818cde8c 100644
--- a/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs
+++ b/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs
@@ -1,6 +1,6 @@
use crate::domain::models::{
- AttachmentEntityReference, ChannelMessageFilters, CreateEntityMentionOptions,
- MessagePageDirection, NotificationFilters, ParticipantRole,
+ AttachmentEntityReference, BotId, BotSenderProfile, ChannelMessageFilters,
+ CreateEntityMentionOptions, MessagePageDirection, NotificationFilters, ParticipantRole,
};
use crate::domain::ports::ChannelRepo;
use crate::outbound::pg_channels_repo::PgChannelsRepo;
@@ -1469,3 +1469,45 @@ async fn attachment_references_merges_channel_and_generic_newest_first(
);
Ok(())
}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn bot_profiles_includes_soft_deleted_bots(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let active = Uuid::new_v4();
+ let deleted = Uuid::new_v4();
+ sqlx::query(
+ r#"
+ INSERT INTO bots (id, kind, owner_user_id, name, handle, avatar_url, deleted_at)
+ VALUES
+ ($1, 'owned', $3, 'Active Bot', 'active-bot', 'https://example.com/a.png', NULL),
+ ($2, 'owned', $3, 'Deleted Bot', 'deleted-bot', NULL, now())
+ "#,
+ )
+ .bind(active)
+ .bind(deleted)
+ .bind(USER_A)
+ .execute(&pool)
+ .await?;
+
+ let missing = BotId::from_uuid(Uuid::new_v4());
+ let profiles = repo(pool)
+ .get_bot_profiles(&[BotId::from_uuid(active), BotId::from_uuid(deleted), missing])
+ .await?;
+
+ assert_eq!(profiles.len(), 2);
+ assert_eq!(
+ profiles.get(&BotId::from_uuid(active)),
+ Some(&BotSenderProfile {
+ name: "Active Bot".to_string(),
+ avatar_url: Some("https://example.com/a.png".to_string()),
+ })
+ );
+ assert_eq!(
+ profiles.get(&BotId::from_uuid(deleted)),
+ Some(&BotSenderProfile {
+ name: "Deleted Bot".to_string(),
+ avatar_url: None,
+ })
+ );
+ assert!(!profiles.contains_key(&missing));
+ Ok(())
+}
diff --git a/rust/cloud-storage/channels/src/outbound/pg_side_effect_context.rs b/rust/cloud-storage/channels/src/outbound/pg_side_effect_context.rs
index ab12f924a6..1e3f2ab957 100644
--- a/rust/cloud-storage/channels/src/outbound/pg_side_effect_context.rs
+++ b/rust/cloud-storage/channels/src/outbound/pg_side_effect_context.rs
@@ -4,6 +4,7 @@
mod tests;
use crate::domain::{
+ models::{BotId, BotSenderProfile},
ports::ChannelSideEffectContext,
side_effects::{ChannelDocumentMention, ThreadNotificationContext},
};
@@ -136,6 +137,29 @@ impl ChannelSideEffectContext for PgChannelSideEffectContext {
) -> Option<String> {
get_sender_profile_picture_url(&self.pool, &sender_id).await
}
+
+ async fn get_bot_sender_profile(&self, bot_id: BotId) -> Option<BotSenderProfile> {
+ get_bot_sender_profile(&self.pool, bot_id).await
+ }
+}
+
+async fn get_bot_sender_profile(db: &PgPool, bot_id: BotId) -> Option<BotSenderProfile> {
+ sqlx::query!(
+ r#"
+ SELECT name, avatar_url
+ FROM bots
+ WHERE id = $1
+ "#,
+ bot_id.as_uuid(),
+ )
+ .fetch_optional(db)
+ .await
+ .ok()
+ .flatten()
+ .map(|row| BotSenderProfile {
+ name: row.name,
+ avatar_url: row.avatar_url,
+ })
}
async fn get_sender_profile_picture_url(