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): channels get and delete (#4119)
Will Hutchinson4dce5f2ecf2e
diff --git a/js/app/packages/service-clients/service-storage/client.ts b/js/app/packages/service-clients/service-storage/client.tsindex 9fa7b934ff..146c7d886f 100644--- a/js/app/packages/service-clients/service-storage/client.ts+++ b/js/app/packages/service-clients/service-storage/client.ts@@ -54,6 +54,7 @@ import type { ApiChannelMessagesPage } from './generated/schemas/apiChannelMessaimport type { ApiChannelParticipant } from './generated/schemas/apiChannelParticipant';import type { ApiResolvedChannelMessage } from './generated/schemas/apiResolvedChannelMessage';import type { ApiThreadReply } from './generated/schemas/apiThreadReply';+import type { BotChannel } from './generated/schemas/botChannel';import type { ChannelMessageFilters } from './generated/schemas/channelMessageFilters';import { ChannelType } from './generated/schemas/channelType';import {@@ -247,6 +248,7 @@ export type TaskSimilaritySearchResponse = {results: TaskSimilarityResult[];};+type WithBotId = { bot_id: string };type WithChannelId = { channel_id: string };type WithMessageId = { message_id: string };type WithMentionId = { mention_id: string };@@ -467,6 +469,22 @@ export const storageServiceClient = {).map((result) => result);},+ async getBotChannels(args: WithBotId) {+ const { bot_id } = args;+ return (+ await dssFetch<BotChannel[]>(`/bots/${bot_id}/channels`, {+ method: 'GET',+ })+ ).map((result) => result);+ },++ async removeBotFromChannel(args: WithBotId & WithChannelId) {+ const { bot_id, channel_id } = args;+ return await dssFetch(`/bots/${bot_id}/channels/${channel_id}`, {+ method: 'DELETE',+ });+ },+async getOrCreateDirectMessage(args: GetOrCreateDmRequest) {const { recipient_id } = args;return (diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/botChannel.ts b/js/app/packages/service-clients/service-storage/generated/schemas/botChannel.tsnew file mode 100644index 0000000000..07b8ddade0--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/botChannel.ts@@ -0,0 +1,23 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++import type { BotChannelName } from './botChannelName';+import type { BotChannelType } from './botChannelType';++/**+ * Channel containing a bot.+ */+export interface BotChannel {+ /** Channel id. */+ channel_id: string;+ /** Channel type. */+ channel_type: BotChannelType;+ /** Timestamp when the bot joined the channel. */+ joined_at: string;+ /** Channel display name. */+ name?: BotChannelName;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/botChannelName.ts b/js/app/packages/service-clients/service-storage/generated/schemas/botChannelName.tsnew file mode 100644index 0000000000..35aeec7147--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/botChannelName.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Channel display name.+ */+export type BotChannelName = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/botChannelType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/botChannelType.tsnew file mode 100644index 0000000000..36daeb7910--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/botChannelType.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Channel type for a channel containing a bot.+ */+export type BotChannelType =+ (typeof BotChannelType)[keyof typeof BotChannelType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const BotChannelType = {+ public: 'public',+ private: 'private',+ direct_message: 'direct_message',+ team: 'team',+} as const;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.tsindex e99c63b772..e528d8cc1f 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@@ -117,6 +117,9 @@ export * from './basicDocumentUpdatedAt';export * from './bomPart';export * from './bot';export * from './botAvatarUrl';+export * from './botChannel';+export * from './botChannelName';+export * from './botChannelType';export * from './botCreatedBy';export * from './botDeletedAt';export * from './botDescription';diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex 652215e7d0..1a5a7355b9 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -822,6 +822,35 @@ export const createCommentResponse = zod}));+/**+ * @summary Handler for `GET /bots/{bot_id}/channels`.+ */+export const listBotChannelsParams = zod.object({+ bot_id: zod.string().describe('Bot ID'),+});++export const listBotChannelsResponseItem = zod+ .object({+ channel_id: zod.uuid().describe('Channel id.'),+ channel_type: zod+ .enum(['public', 'private', 'direct_message', 'team'])+ .describe('Channel type for a channel containing a bot.'),+ joined_at: zod.iso+ .datetime({})+ .describe('Timestamp when the bot joined the channel.'),+ name: zod.string().nullish().describe('Channel display name.'),+ })+ .describe('Channel containing a bot.');+export const listBotChannelsResponse = zod.array(listBotChannelsResponseItem);++/**+ * @summary Handler for `DELETE /bots/{bot_id}/channels/{channel_id}`.+ */+export const removeBotFromChannelByBotParams = zod.object({+ bot_id: zod.string().describe('Bot ID'),+ channel_id: zod.uuid().describe('Channel ID'),+});+/*** Batch-fetches lightweight previews for a list of call ids. Mirrors the`POST /documents/preview` endpoint: no per-id access checks, duplicatediff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 77a627c8cb..62a78cf400 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -594,6 +594,132 @@}}},+ "/bots/{bot_id}/channels": {+ "get": {+ "tags": ["bots"],+ "summary": "Handler for `GET /bots/{bot_id}/channels`.",+ "operationId": "list_bot_channels",+ "parameters": [+ {+ "name": "bot_id",+ "in": "path",+ "description": "Bot ID",+ "required": true,+ "schema": {+ "$ref": "#/components/schemas/BotId"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/BotChannel"+ }+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },+ "/bots/{bot_id}/channels/{channel_id}": {+ "delete": {+ "tags": ["bots"],+ "summary": "Handler for `DELETE /bots/{bot_id}/channels/{channel_id}`.",+ "operationId": "remove_bot_from_channel_by_bot",+ "parameters": [+ {+ "name": "bot_id",+ "in": "path",+ "description": "Bot ID",+ "required": true,+ "schema": {+ "$ref": "#/components/schemas/BotId"+ }+ },+ {+ "name": "channel_id",+ "in": "path",+ "description": "Channel ID",+ "required": true,+ "schema": {+ "type": "string",+ "format": "uuid"+ }+ }+ ],+ "responses": {+ "204": {+ "description": ""+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/call/record/preview": {"post": {"tags": ["call::inbound::axum_router"],@@ -10149,6 +10275,36 @@}}},+ "BotChannel": {+ "type": "object",+ "description": "Channel containing a bot.",+ "required": ["channel_id", "channel_type", "joined_at"],+ "properties": {+ "channel_id": {+ "type": "string",+ "format": "uuid",+ "description": "Channel id."+ },+ "channel_type": {+ "$ref": "#/components/schemas/BotChannelType",+ "description": "Channel type."+ },+ "joined_at": {+ "type": "string",+ "format": "date-time",+ "description": "Timestamp when the bot joined the channel."+ },+ "name": {+ "type": ["string", "null"],+ "description": "Channel display name."+ }+ }+ },+ "BotChannelType": {+ "type": "string",+ "description": "Channel type for a channel containing a bot.",+ "enum": ["public", "private", "direct_message", "team"]+ },"BotId": {"type": "string"},diff --git a/rust/cloud-storage/.sqlx/query-b6129015abc39d2465fdbf93cc66a9063031b1a1d7ba57918bab8ef4e7955bd1.json b/rust/cloud-storage/.sqlx/query-b6129015abc39d2465fdbf93cc66a9063031b1a1d7ba57918bab8ef4e7955bd1.jsonnew file mode 100644index 0000000000..6090bfe9e2--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-b6129015abc39d2465fdbf93cc66a9063031b1a1d7ba57918bab8ef4e7955bd1.json@@ -0,0 +1,40 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n c.id AS channel_id,\n c.name,\n c.channel_type::text AS \"channel_type!\",\n cp.joined_at\n FROM comms_channel_participants cp\n JOIN comms_channels c ON c.id = cp.channel_id\n WHERE cp.user_id = $1\n AND cp.left_at IS NULL\n ORDER BY cp.joined_at ASC, c.id ASC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "channel_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "name",+ "type_info": "Varchar"+ },+ {+ "ordinal": 2,+ "name": "channel_type!",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "joined_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ true,+ null,+ false+ ]+ },+ "hash": "b6129015abc39d2465fdbf93cc66a9063031b1a1d7ba57918bab8ef4e7955bd1"+}diff --git a/rust/cloud-storage/bots/src/domain/models.rs b/rust/cloud-storage/bots/src/domain/models.rsindex 07fb381ea0..a075fb8745 100644--- a/rust/cloud-storage/bots/src/domain/models.rs+++ b/rust/cloud-storage/bots/src/domain/models.rs@@ -40,6 +40,47 @@ impl std::str::FromStr for BotKind {}}+/// Channel type for a channel containing a bot.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+#[serde(rename_all = "snake_case")]+pub enum BotChannelType {+ /// Public channel.+ Public,+ /// Private channel.+ Private,+ /// Direct message channel.+ DirectMessage,+ /// Team channel.+ Team,+}++impl BotChannelType {+ /// Storage representation.+ pub const fn as_str(self) -> &'static str {+ match self {+ Self::Public => "public",+ Self::Private => "private",+ Self::DirectMessage => "direct_message",+ Self::Team => "team",+ }+ }+}++impl std::str::FromStr for BotChannelType {+ type Err = String;++ fn from_str(value: &str) -> Result<Self, Self::Err> {+ match value {+ "public" => Ok(Self::Public),+ "private" => Ok(Self::Private),+ "direct_message" => Ok(Self::DirectMessage),+ "team" => Ok(Self::Team),+ other => Err(format!("unknown bot channel type: {other}")),+ }+ }+}+/// Bot owner.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]@@ -85,6 +126,20 @@ pub struct Bot {pub deleted_at: Option<DateTime<Utc>>,}+/// Channel containing a bot.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]+pub struct BotChannel {+ /// Channel id.+ pub channel_id: Uuid,+ /// Channel display name.+ pub name: Option<String>,+ /// Channel type.+ pub channel_type: BotChannelType,+ /// Timestamp when the bot joined the channel.+ pub joined_at: DateTime<Utc>,+}+/// Bot token metadata.#[derive(Debug, Clone, Serialize, Deserialize)]#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]diff --git a/rust/cloud-storage/bots/src/domain/ports.rs b/rust/cloud-storage/bots/src/domain/ports.rsindex cd116a0608..b5f74b8ae3 100644--- a/rust/cloud-storage/bots/src/domain/ports.rs+++ b/rust/cloud-storage/bots/src/domain/ports.rs@@ -1,8 +1,8 @@//! Bot ports.use super::models::{- AuthenticatedBot, Bot, BotId, BotOwner, BotToken, BotTokenCandidate, CreateBotRequest,- CreateBotTokenRequest, CreateBotTokenResponse, CreateChannelScopedBotRequest,+ AuthenticatedBot, Bot, BotChannel, BotId, BotOwner, BotToken, BotTokenCandidate,+ CreateBotRequest, CreateBotTokenRequest, CreateBotTokenResponse, CreateChannelScopedBotRequest,CreateChannelScopedBotResponse, PatchBotRequest,};use macro_user_id::user_id::MacroUserIdStr;@@ -73,6 +73,12 @@ pub trait BotRepo: Clone + Send + Sync + 'static {bot_id: BotId,) -> impl Future<Output = Result<bool, Self::Err>> + Send;+ /// List active channels containing a bot.+ fn list_bot_channels(+ &self,+ bot_id: BotId,+ ) -> impl Future<Output = Result<Vec<BotChannel>, Self::Err>> + Send;+/// List active bots in a channel.fn list_channel_bots(&self,@@ -179,6 +185,13 @@ pub trait BotService: Clone + Send + Sync + 'static {bot_id: BotId,) -> impl Future<Output = Result<(), BotError>> + Send;+ /// List active channels containing a manageable bot.+ fn list_bot_channels(+ &self,+ caller: MacroUserIdStr<'static>,+ bot_id: BotId,+ ) -> impl Future<Output = Result<Vec<BotChannel>, BotError>> + Send;+/// List channel bots.fn list_channel_bots(&self,diff --git a/rust/cloud-storage/bots/src/domain/service.rs b/rust/cloud-storage/bots/src/domain/service.rsindex 14968379c0..730a458ec9 100644--- a/rust/cloud-storage/bots/src/domain/service.rs+++ b/rust/cloud-storage/bots/src/domain/service.rs@@ -2,7 +2,7 @@use super::{models::{- AuthenticatedBot, Bot, BotId, BotKind, BotOwner, BotToken, BotTokenCandidate,+ AuthenticatedBot, Bot, BotChannel, BotId, BotKind, BotOwner, BotToken, BotTokenCandidate,CreateBotRequest, CreateBotTokenRequest, CreateChannelScopedBotRequest,CreateChannelScopedBotResponse, PatchBotRequest,},@@ -256,6 +256,18 @@ where}}+ async fn list_bot_channels(+ &self,+ caller: MacroUserIdStr<'static>,+ bot_id: BotId,+ ) -> Result<Vec<BotChannel>, BotError> {+ self.ensure_manageable(caller, bot_id).await?;+ self.repo+ .list_bot_channels(bot_id)+ .await+ .map_err(|err| BotError::Repo(err.into()))+ }+async fn list_channel_bots(&self, channel_id: Uuid) -> Result<Vec<Bot>, BotError> {self.repo.list_channel_bots(channel_id)diff --git a/rust/cloud-storage/bots/src/inbound/axum_router.rs b/rust/cloud-storage/bots/src/inbound/axum_router.rsindex 622a1a8144..0893cad5d8 100644--- a/rust/cloud-storage/bots/src/inbound/axum_router.rs+++ b/rust/cloud-storage/bots/src/inbound/axum_router.rs@@ -5,8 +5,8 @@ mod tests;use crate::domain::{models::{- AddChannelBotRequest, Bot, BotId, BotToken, CreateBotRequest, CreateBotTokenRequest,- CreateBotTokenResponse, PatchBotRequest,+ AddChannelBotRequest, Bot, BotChannel, BotId, BotToken, CreateBotRequest,+ CreateBotTokenRequest, CreateBotTokenResponse, PatchBotRequest,},ports::{BotError, BotService},};@@ -93,6 +93,15 @@ pub struct ChannelBotPath {pub bot_id: BotId,}+/// Bot channel path.+#[derive(Debug, serde::Deserialize)]+pub struct BotChannelPath {+ /// Bot id.+ pub bot_id: BotId,+ /// Channel id.+ pub channel_id: Uuid,+}+/// Create a bots router.pub fn bots_router<S, Svc, T>(state: BotsRouterState<S, Svc>) -> Router<T>where@@ -106,6 +115,14 @@ where.route("/bots/{bot_id}", get(get_bot_handler::<S, Svc>)).route("/bots/{bot_id}", patch(patch_bot_handler::<S, Svc>)).route("/bots/{bot_id}", delete(delete_bot_handler::<S, Svc>))+ .route(+ "/bots/{bot_id}/channels",+ get(list_bot_channels_handler::<S, Svc>),+ )+ .route(+ "/bots/{bot_id}/channels/{channel_id}",+ delete(remove_bot_channel_handler::<S, Svc>),+ ).route("/bots/{bot_id}/tokens", get(list_tokens_handler::<S, Svc>)).route("/bots/{bot_id}/tokens",@@ -239,6 +256,64 @@ async fn revoke_token_handler<S: BotService, Svc: EntityAccessService>(Ok(StatusCode::NO_CONTENT)}+/// Handler for `GET /bots/{bot_id}/channels`.+#[utoipa::path(+ get,+ tag = "bots",+ operation_id = "list_bot_channels",+ path = "/bots/{bot_id}/channels",+ params(+ ("bot_id" = BotId, Path, description = "Bot ID")+ ),+ responses(+ (status = 200, body = Vec<BotChannel>),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+pub async fn list_bot_channels_handler<S: BotService, Svc: EntityAccessService>(+ State(state): State<BotsRouterState<S, Svc>>,+ user: MacroUserExtractor,+ Path(path): Path<BotPath>,+) -> Result<Json<Vec<BotChannel>>, BotsHandlerErr> {+ Ok(Json(+ state+ .service+ .list_bot_channels(caller_from_user(user), path.bot_id)+ .await?,+ ))+}++/// Handler for `DELETE /bots/{bot_id}/channels/{channel_id}`.+#[utoipa::path(+ delete,+ tag = "bots",+ operation_id = "remove_bot_from_channel_by_bot",+ path = "/bots/{bot_id}/channels/{channel_id}",+ params(+ ("bot_id" = BotId, Path, description = "Bot ID"),+ ("channel_id" = Uuid, Path, description = "Channel ID")+ ),+ responses(+ (status = 204),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+pub async fn remove_bot_channel_handler<S: BotService, Svc: EntityAccessService>(+ State(state): State<BotsRouterState<S, Svc>>,+ user: MacroUserExtractor,+ Path(path): Path<BotChannelPath>,+) -> Result<StatusCode, BotsHandlerErr> {+ state+ .service+ .remove_bot_from_channel(caller_from_user(user), path.channel_id, path.bot_id)+ .await?;+ Ok(StatusCode::NO_CONTENT)+}+async fn list_channel_bots_handler<S: BotService, Svc: EntityAccessService>(State(state): State<BotsRouterState<S, Svc>>,_access: ChannelAccessLevelExtractor<AdminParticipantRole, Svc>,diff --git a/rust/cloud-storage/bots/src/inbound/axum_router/tests.rs b/rust/cloud-storage/bots/src/inbound/axum_router/tests.rsindex bc7854a017..7da8c9b343 100644--- a/rust/cloud-storage/bots/src/inbound/axum_router/tests.rs+++ b/rust/cloud-storage/bots/src/inbound/axum_router/tests.rs@@ -1,6 +1,7 @@use super::*;use crate::domain::models::{- AuthenticatedBot, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse,+ AuthenticatedBot, BotChannel, BotChannelType, CreateChannelScopedBotRequest,+ CreateChannelScopedBotResponse,};use crate::{domain::service::BotServiceImpl, outbound::pg_bots_repo::PgBotsRepo};use axum::{@@ -35,16 +36,24 @@ enum TestBotMode {#[derive(Clone)]struct TestBotService {mode: TestBotMode,+ bot_channels: Vec<BotChannel>,add_calls: Arc<AtomicUsize>,remove_calls: Arc<AtomicUsize>,+ list_bot_channels_calls: Arc<AtomicUsize>,}impl TestBotService {fn new(mode: TestBotMode) -> Self {+ Self::with_bot_channels(mode, Vec::new())+ }++ fn with_bot_channels(mode: TestBotMode, bot_channels: Vec<BotChannel>) -> Self {Self {mode,+ bot_channels,add_calls: Arc::new(AtomicUsize::new(0)),remove_calls: Arc::new(AtomicUsize::new(0)),+ list_bot_channels_calls: Arc::new(AtomicUsize::new(0)),}}@@ -123,6 +132,16 @@ impl BotService for TestBotService {self.result()}+ async fn list_bot_channels(+ &self,+ _caller: MacroUserIdStr<'static>,+ _bot_id: BotId,+ ) -> Result<Vec<BotChannel>, BotError> {+ self.list_bot_channels_calls.fetch_add(1, Ordering::SeqCst);+ self.result()?;+ Ok(self.bot_channels.clone())+ }+async fn list_channel_bots(&self, _channel_id: Uuid) -> Result<Vec<Bot>, BotError> {unimplemented!()}@@ -363,6 +382,106 @@ fn macro_user_id(value: &str) -> MacroUserIdStr<'static> {MacroUserIdStr::try_from(value.to_string()).expect("valid macro user id")}+fn bot_channel(channel_id: Uuid) -> BotChannel {+ BotChannel {+ channel_id,+ name: Some("alarms".to_string()),+ channel_type: BotChannelType::Private,+ joined_at: chrono::Utc::now(),+ }+}++async fn read_bot_channels(response: axum::response::Response) -> Vec<BotChannel> {+ let body = axum::body::to_bytes(response.into_body(), usize::MAX)+ .await+ .unwrap();+ serde_json::from_slice(&body).unwrap()+}++#[tokio::test]+async fn bot_owner_can_list_bot_channels_via_http() {+ let channel_id = Uuid::new_v4();+ let service = TestBotService::with_bot_channels(TestBotMode::Ok, vec![bot_channel(channel_id)]);+ let bot_id = BotId::from_uuid(Uuid::new_v4());+ let request = Request::builder()+ .method("GET")+ .uri(format!("/bots/{bot_id}/channels"))+ .body(Body::empty())+ .unwrap();++ let response = router(service.clone(), EntityParticipantRole::Member)+ .oneshot(request)+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::OK);+ let channels = read_bot_channels(response).await;+ assert_eq!(channels.len(), 1);+ assert_eq!(channels[0].channel_id, channel_id);+ assert_eq!(channels[0].name.as_deref(), Some("alarms"));+ assert_eq!(channels[0].channel_type, BotChannelType::Private);+ assert_eq!(service.list_bot_channels_calls.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn bot_listing_requires_bot_usability() {+ let service = TestBotService::new(TestBotMode::Unauthorized);+ let bot_id = BotId::from_uuid(Uuid::new_v4());+ let request = Request::builder()+ .method("GET")+ .uri(format!("/bots/{bot_id}/channels"))+ .body(Body::empty())+ .unwrap();++ let response = router(service.clone(), EntityParticipantRole::Member)+ .oneshot(request)+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);+ assert_eq!(service.list_bot_channels_calls.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn bot_owner_can_remove_bot_from_channel_via_bot_route_without_channel_admin() {+ let service = TestBotService::new(TestBotMode::Ok);+ let channel_id = Uuid::new_v4();+ let bot_id = BotId::from_uuid(Uuid::new_v4());+ let request = Request::builder()+ .method("DELETE")+ .uri(format!("/bots/{bot_id}/channels/{channel_id}"))+ .body(Body::empty())+ .unwrap();++ let response = router(service.clone(), EntityParticipantRole::Member)+ .oneshot(request)+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::NO_CONTENT);+ assert_eq!(service.remove_calls.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn bot_remove_channel_requires_bot_usability() {+ let service = TestBotService::new(TestBotMode::Unauthorized);+ let channel_id = Uuid::new_v4();+ let bot_id = BotId::from_uuid(Uuid::new_v4());+ let request = Request::builder()+ .method("DELETE")+ .uri(format!("/bots/{bot_id}/channels/{channel_id}"))+ .body(Body::empty())+ .unwrap();++ let response = router(service.clone(), EntityParticipantRole::Member)+ .oneshot(request)+ .await+ .unwrap();++ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);+ assert_eq!(service.remove_calls.load(Ordering::SeqCst), 1);+}+#[tokio::test]async fn channel_member_cannot_add_bot_to_channel() {let service = TestBotService::new(TestBotMode::Ok);@@ -449,6 +568,96 @@ async fn channel_admin_still_needs_bot_usability_to_remove_bot() {assert_eq!(service.remove_calls.load(Ordering::SeqCst), 1);}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn bot_owner_can_list_and_remove_bot_channels_via_bot_routes(+ pool: PgPool,+) -> anyhow::Result<()> {+ const BOT_OWNER_ID: &str = "macro|[email protected]";+ const CHANNEL_ADMIN_ID: &str = "macro|[email protected]";+ let channel_id = Uuid::new_v4();++ insert_user(&pool, BOT_OWNER_ID).await?;+ insert_user(&pool, CHANNEL_ADMIN_ID).await?;+ insert_private_channel_with_admin(&pool, channel_id, CHANNEL_ADMIN_ID).await?;++ let bot_service = BotServiceImpl::new(PgBotsRepo::new(pool.clone()));+ let bot = bot_service+ .create_bot(+ macro_user_id(BOT_OWNER_ID),+ CreateBotRequest {+ team_id: None,+ name: "Datadog Alerts".to_string(),+ handle: "bot-route-alerts".to_string(),+ description: Some("Posts alarm notifications".to_string()),+ avatar_url: None,+ },+ )+ .await?;++ bot_service+ .add_bot_to_channel(macro_user_id(BOT_OWNER_ID), channel_id, bot.id)+ .await?;++ let bot_principal_id = bot.id.to_storage_string();+ let router = real_router(pool.clone(), BOT_OWNER_ID);+ let list_request = Request::builder()+ .method("GET")+ .uri(format!("/bots/{}/channels", bot.id))+ .body(Body::empty())+ .unwrap();++ let list_response = router.clone().oneshot(list_request).await.unwrap();+ assert_eq!(list_response.status(), StatusCode::OK);+ let channels = read_bot_channels(list_response).await;+ assert_eq!(channels.len(), 1);+ assert_eq!(channels[0].channel_id, channel_id);+ assert_eq!(channels[0].name.as_deref(), Some("alarms"));+ assert_eq!(channels[0].channel_type, BotChannelType::Private);++ let remove_request = Request::builder()+ .method("DELETE")+ .uri(format!("/bots/{}/channels/{channel_id}", bot.id))+ .body(Body::empty())+ .unwrap();++ let remove_response = router.clone().oneshot(remove_request).await.unwrap();+ assert_eq!(remove_response.status(), StatusCode::NO_CONTENT);++ let left_at: Option<chrono::DateTime<chrono::Utc>> = sqlx::query_scalar(+ r#"+ SELECT left_at+ FROM comms_channel_participants+ WHERE channel_id = $1 AND user_id = $2+ "#,+ )+ .bind(channel_id)+ .bind(&bot_principal_id)+ .fetch_one(&pool)+ .await?;+ assert!(left_at.is_some());++ let list_request = Request::builder()+ .method("GET")+ .uri(format!("/bots/{}/channels", bot.id))+ .body(Body::empty())+ .unwrap();++ let list_response = router.clone().oneshot(list_request).await.unwrap();+ assert_eq!(list_response.status(), StatusCode::OK);+ assert!(read_bot_channels(list_response).await.is_empty());++ let missing_remove_request = Request::builder()+ .method("DELETE")+ .uri(format!("/bots/{}/channels/{channel_id}", bot.id))+ .body(Body::empty())+ .unwrap();++ let missing_remove_response = router.oneshot(missing_remove_request).await.unwrap();+ assert_eq!(missing_remove_response.status(), StatusCode::NOT_FOUND);++ Ok(())+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn channel_admin_can_add_and_remove_owned_bot_via_http(pool: PgPool) -> anyhow::Result<()> {const ADMIN_USER_ID: &str = "macro|[email protected]";diff --git a/rust/cloud-storage/bots/src/inbound/channel_webhook_router/tests.rs b/rust/cloud-storage/bots/src/inbound/channel_webhook_router/tests.rsindex e23ecb1d78..a0abfd0fbd 100644--- a/rust/cloud-storage/bots/src/inbound/channel_webhook_router/tests.rs+++ b/rust/cloud-storage/bots/src/inbound/channel_webhook_router/tests.rs@@ -1,6 +1,6 @@use super::*;use crate::domain::models::{- AuthenticatedBot, Bot, BotId, BotKind, BotOwner, BotToken, CreateBotRequest,+ AuthenticatedBot, Bot, BotChannel, BotId, BotKind, BotOwner, BotToken, CreateBotRequest,CreateBotTokenRequest, CreateBotTokenResponse, PatchBotRequest,};use axum::{@@ -173,6 +173,14 @@ impl BotService for TestBotService {unimplemented!()}+ async fn list_bot_channels(+ &self,+ _caller: MacroUserIdStr<'static>,+ _bot_id: BotId,+ ) -> Result<Vec<BotChannel>, BotError> {+ unimplemented!()+ }+async fn list_channel_bots(&self, _channel_id: Uuid) -> Result<Vec<Bot>, BotError> {unimplemented!()}diff --git a/rust/cloud-storage/bots/src/outbound/pg_bots_repo.rs b/rust/cloud-storage/bots/src/outbound/pg_bots_repo.rsindex 1cb7e60cb2..a620b468c7 100644--- a/rust/cloud-storage/bots/src/outbound/pg_bots_repo.rs+++ b/rust/cloud-storage/bots/src/outbound/pg_bots_repo.rs@@ -5,8 +5,9 @@ mod tests;use crate::domain::{models::{- AuthenticatedBot, Bot, BotId, BotKind, BotOwner, BotToken, BotTokenCandidate,- CreateBotRequest, CreateBotTokenRequest, CreateChannelScopedBotRequest, PatchBotRequest,+ AuthenticatedBot, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken,+ BotTokenCandidate, CreateBotRequest, CreateBotTokenRequest, CreateChannelScopedBotRequest,+ PatchBotRequest,},ports::BotRepo,};@@ -86,6 +87,32 @@ impl TryFrom<BotRow> for Bot {}}+#[derive(Debug)]+struct BotChannelRow {+ channel_id: Uuid,+ name: Option<String>,+ channel_type: String,+ joined_at: DateTime<Utc>,+}++impl TryFrom<BotChannelRow> for BotChannel {+ type Error = anyhow::Error;++ fn try_from(row: BotChannelRow) -> Result<Self, Self::Error> {+ let channel_type = row+ .channel_type+ .parse::<BotChannelType>()+ .map_err(|err| anyhow::anyhow!(err))?;++ Ok(Self {+ channel_id: row.channel_id,+ name: row.name,+ channel_type,+ joined_at: row.joined_at,+ })+ }+}+#[derive(Debug)]struct BotTokenRow {id: Uuid,@@ -155,6 +182,10 @@ fn map_bot_row(row: BotRow) -> anyhow::Result<Bot> {row.try_into()}+fn map_bot_channel_row(row: BotChannelRow) -> anyhow::Result<BotChannel> {+ row.try_into()+}+fn map_token_row(row: BotTokenRow) -> BotToken {row.into()}@@ -505,6 +536,29 @@ impl BotRepo for PgBotsRepo {Ok(result.rows_affected() > 0)}+ async fn list_bot_channels(&self, bot_id: BotId) -> Result<Vec<BotChannel>, Self::Err> {+ let rows = sqlx::query_as!(+ BotChannelRow,+ r#"+ SELECT+ c.id AS channel_id,+ c.name,+ c.channel_type::text AS "channel_type!",+ cp.joined_at+ FROM comms_channel_participants cp+ JOIN comms_channels c ON c.id = cp.channel_id+ WHERE cp.user_id = $1+ AND cp.left_at IS NULL+ ORDER BY cp.joined_at ASC, c.id ASC+ "#,+ principal_id(bot_id),+ )+ .fetch_all(&self.pool)+ .await+ .context("failed to list bot channels")?;+ rows.into_iter().map(map_bot_channel_row).collect()+ }+async fn list_channel_bots(&self, channel_id: Uuid) -> Result<Vec<Bot>, Self::Err> {let rows = sqlx::query_as!(BotRow,diff --git a/rust/cloud-storage/bots/src/outbound/pg_bots_repo/tests.rs b/rust/cloud-storage/bots/src/outbound/pg_bots_repo/tests.rsindex 7db7ff8fad..b773ef1e63 100644--- a/rust/cloud-storage/bots/src/outbound/pg_bots_repo/tests.rs+++ b/rust/cloud-storage/bots/src/outbound/pg_bots_repo/tests.rs@@ -1,6 +1,8 @@use super::*;use crate::domain::{- models::{CreateBotRequest, CreateBotTokenRequest, CreateChannelScopedBotRequest},+ models::{+ BotChannelType, CreateBotRequest, CreateBotTokenRequest, CreateChannelScopedBotRequest,+ },ports::{BotError, BotService},service::BotServiceImpl,};@@ -274,6 +276,57 @@ async fn add_remove_channel_bot_requires_bot_usability_and_soft_removes(Ok(())}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_bot_channels_requires_manageable_bot_and_returns_only_active_channels(+ pool: PgPool,+) -> anyhow::Result<()> {+ let service = service(&pool);+ let active_channel_id = Uuid::new_v4();+ let removed_channel_id = Uuid::new_v4();+ insert_channel(&pool, active_channel_id).await?;+ insert_channel(&pool, removed_channel_id).await?;++ let bot = service+ .create_bot(user_id(USER_OWNER), create_req("channel-list"))+ .await?;+ let empty_bot = service+ .create_bot(user_id(USER_OWNER), create_req("empty-channel-list"))+ .await?;++ let err = service+ .list_bot_channels(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)+ .await?;+ assert!(empty_channels.is_empty());++ service+ .add_bot_to_channel(user_id(USER_OWNER), removed_channel_id, bot.id)+ .await?;+ service+ .remove_bot_from_channel(user_id(USER_OWNER), removed_channel_id, bot.id)+ .await?;+ service+ .add_bot_to_channel(user_id(USER_OWNER), active_channel_id, bot.id)+ .await?;++ let channels = service+ .list_bot_channels(user_id(USER_OWNER), bot.id)+ .await?;++ assert_eq!(channels.len(), 1);+ assert_eq!(channels[0].channel_id, active_channel_id);+ assert_eq!(channels[0].name.as_deref(), Some("alarms"));+ assert_eq!(channels[0].channel_type, BotChannelType::Private);+ assert!(channels[0].joined_at <= chrono::Utc::now());++ Ok(())+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn create_channel_scoped_bot_creates_bot_participant_and_token(pool: PgPool,diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rsindex ff84d194cc..832a60b421 100644--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs@@ -238,6 +238,8 @@ use utoipa::OpenApi;channels::inbound::axum_router::post_activity_handler,// bots+ bots::inbound::axum_router::list_bot_channels_handler,+ bots::inbound::axum_router::remove_bot_channel_handler,bots::inbound::channel_webhook_router::create_channel_scoped_bot_handler,bots::inbound::channel_webhook_router::post_channel_webhook_handler,@@ -473,6 +475,8 @@ use utoipa::OpenApi;bots::domain::models::BotKind,bots::domain::models::BotOwner,bots::domain::models::BotToken,+ bots::domain::models::BotChannel,+ bots::domain::models::BotChannelType,bots::domain::models::ChannelWebhookRequest,bots::domain::models::ChannelWebhookResponse,bots::domain::models::CreateChannelScopedBotRequest,