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
feat(bots): let bots list their channels (#5374)
teo6ec403d840f7
diff --git a/crates/bots/src/domain/models.rs b/crates/bots/src/domain/models.rsindex ea5d090967..9135be2ac2 100644--- a/crates/bots/src/domain/models.rs+++ b/crates/bots/src/domain/models.rs@@ -1,6 +1,7 @@//! Bot domain models.use chrono::{DateTime, Utc};+use macro_user_id::user_id::MacroUserIdStr;use serde::{Deserialize, Serialize};use uuid::Uuid;@@ -140,6 +141,17 @@ pub struct BotChannel {pub joined_at: DateTime<Utc>,}+/// Authenticated principal asking to list a bot's channels.+#[derive(Debug, Clone)]+pub enum BotChannelListCaller {+ /// A directly authenticated Macro user.+ User(MacroUserIdStr<'static>),+ /// An authenticated bot.+ Bot(BotId),+ /// An authenticated internal service, with or without an acting user.+ Internal,+}+/// Bot token metadata.#[derive(Debug, Clone, Serialize, Deserialize)]#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]diff --git a/crates/bots/src/domain/ports.rs b/crates/bots/src/domain/ports.rsindex a58acccded..ff93815e1c 100644--- a/crates/bots/src/domain/ports.rs+++ b/crates/bots/src/domain/ports.rs@@ -1,9 +1,9 @@//! Bot ports.use super::models::{- AuthenticatedBot, Bot, BotChannel, BotId, BotOwner, BotToken, BotTokenCandidate,- CreateBotRequest, CreateBotTokenRequest, CreateBotTokenResponse, CreateChannelScopedBotRequest,- CreateChannelScopedBotResponse, PatchBotRequest,+ AuthenticatedBot, Bot, BotChannel, BotChannelListCaller, BotId, BotOwner, BotToken,+ BotTokenCandidate, CreateBotRequest, CreateBotTokenRequest, CreateBotTokenResponse,+ CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, PatchBotRequest,};use macro_user_id::user_id::MacroUserIdStr;use std::future::Future;@@ -202,10 +202,11 @@ pub trait BotService: Clone + Send + Sync + 'static {bot_id: BotId,) -> impl Future<Output = Result<(), BotError>> + Send;- /// List active channels containing a manageable bot.+ /// List active channels containing a manageable bot, the calling bot itself,+ /// or a bot requested by an authenticated internal service.fn list_bot_channels(&self,- caller: MacroUserIdStr<'static>,+ caller: BotChannelListCaller,bot_id: BotId,) -> impl Future<Output = Result<Vec<BotChannel>, BotError>> + Send;diff --git a/crates/bots/src/domain/service.rs b/crates/bots/src/domain/service.rsindex 350e0e1524..602c1e5ce0 100644--- a/crates/bots/src/domain/service.rs+++ b/crates/bots/src/domain/service.rs@@ -3,9 +3,9 @@use super::{events::{BotCreatedMetadata, BotDeletedMetadata, BotMacroEvent, BotUpdatedMetadata},models::{- AuthenticatedBot, Bot, BotChannel, BotId, BotKind, BotOwner, BotToken, BotTokenCandidate,- CreateBotRequest, CreateBotTokenRequest, CreateChannelScopedBotRequest,- CreateChannelScopedBotResponse, PatchBotRequest,+ AuthenticatedBot, Bot, BotChannel, BotChannelListCaller, BotId, BotKind, BotOwner,+ BotToken, BotTokenCandidate, CreateBotRequest, CreateBotTokenRequest,+ CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, PatchBotRequest,},ports::{BotError, BotRepo, BotService},tokens,@@ -340,10 +340,19 @@ whereasync fn list_bot_channels(&self,- caller: MacroUserIdStr<'static>,+ caller: BotChannelListCaller,bot_id: BotId,) -> Result<Vec<BotChannel>, BotError> {- self.ensure_manageable(caller, bot_id).await?;+ match caller {+ BotChannelListCaller::User(user_id) => {+ self.ensure_manageable(user_id, bot_id).await?;+ }+ BotChannelListCaller::Bot(caller_id) if caller_id == bot_id => {}+ BotChannelListCaller::Internal => {}+ BotChannelListCaller::Bot(_) => {+ return Err(BotError::Unauthorized);+ }+ }self.repo.list_bot_channels(bot_id).awaitdiff --git a/crates/bots/src/inbound/axum_router.rs b/crates/bots/src/inbound/axum_router.rsindex 9ea384d3f7..d9ca0dad6d 100644--- a/crates/bots/src/inbound/axum_router.rs+++ b/crates/bots/src/inbound/axum_router.rs@@ -5,8 +5,8 @@ mod tests;use crate::domain::{models::{- AddChannelBotRequest, Bot, BotChannel, BotId, BotToken, CreateBotRequest,- CreateBotTokenRequest, CreateBotTokenResponse, PatchBotRequest,+ AddChannelBotRequest, Bot, BotChannel, BotChannelListCaller, BotId, BotToken,+ CreateBotRequest, CreateBotTokenRequest, CreateBotTokenResponse, PatchBotRequest,},ports::{BotError, BotService},};@@ -25,8 +25,8 @@ use entity_access::{inbound::axum_extractors::ChannelAccessLevelExtractor,};use macro_authorization::{- BotOnly, MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,- UserOrInternal,+ AnyPrincipal, BotOnly, MacroAuthorization, MacroAuthorizationExtractor,+ MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,};use macro_user_id::user_id::MacroUserIdStr;use model_error_response::ErrorResponse;@@ -374,14 +374,16 @@ pub async fn list_bot_channels_handler<Auth: MacroAuthorizationService,>(State(state): State<BotsRouterState<S, Svc, Auth>>,- authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ authorization: MacroAuthorizationExtractor<Auth, AnyPrincipal>,Path(path): Path<BotPath>,) -> Result<Json<Vec<BotChannel>>, BotsHandlerErr> {+ let caller = match authorization.authorization {+ MacroAuthorization::User(user) => BotChannelListCaller::User(user.macro_user_id),+ MacroAuthorization::Bot(bot) => BotChannelListCaller::Bot(bot.bot_id),+ MacroAuthorization::Internal(_) => BotChannelListCaller::Internal,+ };Ok(Json(- state- .service- .list_bot_channels(authorization.authorization.user.macro_user_id, path.bot_id)- .await?,+ state.service.list_bot_channels(caller, path.bot_id).await?,))}diff --git a/crates/bots/src/inbound/axum_router/tests.rs b/crates/bots/src/inbound/axum_router/tests.rsindex 740bed0ba5..6729550e80 100644--- a/crates/bots/src/inbound/axum_router/tests.rs+++ b/crates/bots/src/inbound/axum_router/tests.rs@@ -1,7 +1,7 @@use super::*;use crate::domain::models::{- AuthenticatedBot, BotChannel, BotChannelType, BotKind, BotOwner, CreateChannelScopedBotRequest,- CreateChannelScopedBotResponse,+ AuthenticatedBot, BotChannel, BotChannelListCaller, BotChannelType, BotKind, BotOwner,+ CreateChannelScopedBotRequest, CreateChannelScopedBotResponse,};use crate::{domain::service::BotServiceImpl, outbound::pg_bots_repo::PgBotsRepo};use axum::{@@ -170,7 +170,7 @@ impl BotService for TestBotService {async fn list_bot_channels(&self,- _caller: MacroUserIdStr<'static>,+ _caller: BotChannelListCaller,_bot_id: BotId,) -> Result<Vec<BotChannel>, BotError> {self.list_bot_channels_calls.fetch_add(1, Ordering::SeqCst);diff --git a/crates/bots/src/inbound/channel_webhook_router/tests.rs b/crates/bots/src/inbound/channel_webhook_router/tests.rsindex f687ba1e7c..13c6cb5075 100644--- a/crates/bots/src/inbound/channel_webhook_router/tests.rs+++ b/crates/bots/src/inbound/channel_webhook_router/tests.rs@@ -1,7 +1,7 @@use super::*;use crate::domain::models::{- AuthenticatedBot, Bot, BotChannel, BotKind, BotOwner, BotToken, CreateBotRequest,- CreateBotTokenRequest, CreateBotTokenResponse, PatchBotRequest,+ AuthenticatedBot, Bot, BotChannel, BotChannelListCaller, BotKind, BotOwner, BotToken,+ CreateBotRequest, CreateBotTokenRequest, CreateBotTokenResponse, PatchBotRequest,};use axum::{Router,@@ -228,7 +228,7 @@ impl BotService for TestBotService {async fn list_bot_channels(&self,- _caller: MacroUserIdStr<'static>,+ _caller: BotChannelListCaller,_bot_id: BotId,) -> Result<Vec<BotChannel>, BotError> {unimplemented!()diff --git a/crates/bots/src/outbound/pg_bots_repo/tests.rs b/crates/bots/src/outbound/pg_bots_repo/tests.rsindex f9f016ad7a..f14a195d7d 100644--- a/crates/bots/src/outbound/pg_bots_repo/tests.rs+++ b/crates/bots/src/outbound/pg_bots_repo/tests.rs@@ -1,8 +1,8 @@use super::*;use crate::domain::{models::{- BotChannelType, CreateBotRequest, CreateBotTokenRequest, CreateChannelScopedBotRequest,- PatchBotRequest,+ BotChannelListCaller, BotChannelType, CreateBotRequest, CreateBotTokenRequest,+ CreateChannelScopedBotRequest, PatchBotRequest,},ports::{BotError, BotService},service::BotServiceImpl,@@ -475,13 +475,16 @@ async fn list_bot_channels_requires_manageable_bot_and_returns_only_active_chann.await?;let err = service- .list_bot_channels(user_id(USER_OTHER), bot.id)+ .list_bot_channels(BotChannelListCaller::User(user_id(USER_OTHER)), bot.id).await.expect_err("non-owner must not list someone else's bot channels");assert!(matches!(err, BotError::Unauthorized));let empty_channels = service- .list_bot_channels(user_id(USER_OWNER), empty_bot.id)+ .list_bot_channels(+ BotChannelListCaller::User(user_id(USER_OWNER)),+ empty_bot.id,+ ).await?;assert!(empty_channels.is_empty());@@ -496,7 +499,7 @@ async fn list_bot_channels_requires_manageable_bot_and_returns_only_active_chann.await?;let channels = service- .list_bot_channels(user_id(USER_OWNER), bot.id)+ .list_bot_channels(BotChannelListCaller::User(user_id(USER_OWNER)), bot.id).await?;assert_eq!(channels.len(), 1);@@ -908,7 +911,7 @@ async fn non_lifecycle_and_failed_operations_do_not_publish(pool: PgPool) -> any.add_bot_to_channel(user_id(USER_OWNER), channel_id, bot.id).await?;service- .list_bot_channels(user_id(USER_OWNER), bot.id)+ .list_bot_channels(BotChannelListCaller::User(user_id(USER_OWNER)), bot.id).await?;service.remove_bot_from_channel(user_id(USER_OWNER), channel_id, bot.id)diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex f0ea694ebe..be52b223d8 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -262,7 +262,6 @@ export const storageExcluded = ['joinChannelByCode','jobProcessingResultHandler','leaveOrEndCall',- 'listBotChannels','patchViewHandler','postChannelBotWebhook','postChannelMessages',diff --git a/packages/sdk/src/entities/bots/namespace.ts b/packages/sdk/src/entities/bots/namespace.tsindex 1b103fb272..4eaf6b5bd9 100644--- a/packages/sdk/src/entities/bots/namespace.ts+++ b/packages/sdk/src/entities/bots/namespace.ts@@ -1,4 +1,4 @@-import type { Bot } from '../../../generated/storage/types.gen';+import type { Bot, BotChannel } from '../../../generated/storage/types.gen';import { MacroError, unwrap } from '../../utils';import type { MacroClient } from '../../utils/client';@@ -19,9 +19,22 @@ export class BotsNamespace {'bots.me() requires bot auth — a user API key has no bot identity',);}+ return unwrap(await this.client.storage.getSelfBot());+ }++ /**+ * Channels containing the authenticated bot. Requires bot auth.+ */+ async channels(): Promise<BotChannel[]> {+ if (this.client.authConfig.type !== 'bot') {+ throw new MacroError(+ 'bots.channels() requires bot auth — a user API key has no bot identity',+ );+ }+ const bot = await this.me();return unwrap(- await this.client.storage.getSelfBot({- headers: { 'x-macro-bot-scope': 'user' },+ await this.client.storage.listBotChannels({+ path: { bot_id: bot.id },}),);}diff --git a/packages/sdk/tests/bots-namespace.test.ts b/packages/sdk/tests/bots-namespace.test.tsindex fabc15b848..7907147891 100644--- a/packages/sdk/tests/bots-namespace.test.ts+++ b/packages/sdk/tests/bots-namespace.test.ts@@ -9,11 +9,11 @@ afterEach(() => {});describe('BotsNamespace', () => {- test('uses user scope for self lookup with default bot auth', async () => {+ test('uses the configured bot scope for self lookup', async () => {const bot: Bot = {id: '0198a4cc-e138-7670-a308-a6b766602700',kind: 'owned',- owner: { type: 'user', user_id: 'macro|[email protected]' },+ owner: { type: 'team', team_id: '0198a4cc-e138-7670-a308-a6b766602701' },name: 'Mention Bot',handle: 'mention-bot',description: null,@@ -32,14 +32,14 @@ describe('BotsNamespace', () => {});}) as typeof fetch;const macro = new Macro({- auth: { type: 'bot', token: 'mbot_user_owned' },+ auth: { type: 'bot', token: 'mbot_team_owned', scope: 'team' },hosts: { storage: 'https://storage.example.test' },});await expect(macro.bots.me()).resolves.toEqual(bot);expect(request?.url).toBe('https://storage.example.test/bots/me');- expect(request?.headers.get('x-macro-bot-token')).toBe('mbot_user_owned');- expect(request?.headers.get('x-macro-bot-scope')).toBe('user');+ expect(request?.headers.get('x-macro-bot-token')).toBe('mbot_team_owned');+ expect(request?.headers.get('x-macro-bot-scope')).toBe('team');expect(request?.headers.has('x-macro-bot-for-macro-user-id')).toBe(false);});});