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.

fix(channels): create team channel with auto join adds team members (#5096)

Will Hutchinsonedf6646694ea
diff --git a/.sqlx/query-554ab371c567d428e70e2e70d02c45fad492cf675abeb6d12a400483f9654a75.json b/.sqlx/query-554ab371c567d428e70e2e70d02c45fad492cf675abeb6d12a400483f9654a75.json
new file mode 100644
index 0000000000..4f4f3b4ca4
--- /dev/null
+++ b/.sqlx/query-554ab371c567d428e70e2e70d02c45fad492cf675abeb6d12a400483f9654a75.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT user_id\n FROM comms_channel_participants\n WHERE channel_id = $1 AND left_at IS NULL\n ORDER BY user_id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "554ab371c567d428e70e2e70d02c45fad492cf675abeb6d12a400483f9654a75"
+}
diff --git a/.sqlx/query-7c61621a46ce9ff8e10c87417b6cab040a742c03141312fbd8448924136218e4.json b/.sqlx/query-7c61621a46ce9ff8e10c87417b6cab040a742c03141312fbd8448924136218e4.json
new file mode 100644
index 0000000000..41bfde6b32
--- /dev/null
+++ b/.sqlx/query-7c61621a46ce9ff8e10c87417b6cab040a742c03141312fbd8448924136218e4.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO comms_channel_participants (channel_id, role, user_id)\n SELECT $1, 'member'::comms_participant_role, user_id\n FROM team_user\n WHERE team_id = $2\n ON CONFLICT (channel_id, user_id) DO NOTHING\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "7c61621a46ce9ff8e10c87417b6cab040a742c03141312fbd8448924136218e4"
+}
diff --git a/crates/channels/src/domain/models.rs b/crates/channels/src/domain/models.rs
index 2f824b9ae5..0c2e39f4f9 100644
--- a/crates/channels/src/domain/models.rs
+++ b/crates/channels/src/domain/models.rs
@@ -709,6 +709,15 @@ pub struct CreateChannelRequest {
pub participants: HashSet<MacroUserIdStr<'static>>,
}
+/// Persisted channel data returned by channel creation.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct CreatedChannel {
+ /// Created channel id.
+ pub id: Uuid,
+ /// All active user participants added during creation.
+ pub participant_user_ids: Vec<MacroUserIdStr<'static>>,
+}
+
/// Response containing a channel's reusable join code.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
diff --git a/crates/channels/src/domain/ports.rs b/crates/channels/src/domain/ports.rs
index 58cbed8f83..5ce4ff70ff 100644
--- a/crates/channels/src/domain/ports.rs
+++ b/crates/channels/src/domain/ports.rs
@@ -6,13 +6,13 @@ use crate::domain::models::{
BotSenderProfile, ChannelAttachment, ChannelAttachmentType, ChannelContextMessage, ChannelInfo,
ChannelJoinCodeResponse, 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,
+ CreateChannelResponse, CreateEntityMentionOptions, CreatedChannel, 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,
};
#[cfg(feature = "list")]
use crate::domain::models::{
@@ -266,13 +266,13 @@ pub trait ChannelRepo: Send + Sync + 'static {
team_id: Uuid,
) -> impl Future<Output = Result<bool, Self::Err>> + Send;
- /// Create a channel.
+ /// Create a channel and return its complete active participant set.
fn create_channel<'a>(
&self,
owner_id: MacroUserIdStr<'a>,
org_id: Option<i64>,
req: CreateChannelRequest,
- ) -> impl Future<Output = Result<Uuid, Self::Err>> + Send;
+ ) -> impl Future<Output = Result<CreatedChannel, Self::Err>> + Send;
/// Add or reactivate a user in every auto-join channel for a team.
fn auto_join_by_team_id<'a>(
diff --git a/crates/channels/src/domain/service.rs b/crates/channels/src/domain/service.rs
index 648ec86e3c..a7d9c2859b 100644
--- a/crates/channels/src/domain/service.rs
+++ b/crates/channels/src/domain/service.rs
@@ -316,17 +316,6 @@ fn is_admin_or_owner(role: ParticipantRole) -> bool {
matches!(role, ParticipantRole::Owner | ParticipantRole::Admin)
}
-/// returns all user participants in a channel given an iterator of participants and the channel owner
-fn created_channel_participant_ids<'a>(
- owner_id: MacroUserIdStr<'a>,
- participants: impl IntoIterator<Item = MacroUserIdStr<'a>>,
-) -> HashSet<MacroUserIdStr<'a>> {
- participants
- .into_iter()
- .chain(std::iter::once(owner_id))
- .collect()
-}
-
impl<R, E, P, M> ChannelServiceImpl<R, E, P, M>
where
R: ChannelRepo,
@@ -376,26 +365,23 @@ where
));
}
- let participants_clone = req.participants.clone();
let channel_type = req.channel_type;
let channel_name = req.name.clone();
- let channel_id = self
+ let created_channel = self
.create_channel_record(actor.copied(), org_id, req)
.await?;
self.events.dispatch(ChannelEvent::ChannelCreated {
- channel_id,
- actor: Sender::new_from_user(actor.clone()),
+ channel_id: created_channel.id,
+ actor: Sender::new_from_user(actor),
channel_type,
channel_name,
- participant_user_ids: created_channel_participant_ids(actor, participants_clone)
- .into_iter()
- .collect(),
+ participant_user_ids: created_channel.participant_user_ids,
});
Ok(crate::domain::models::CreateChannelResponse {
- id: channel_id.to_string(),
+ id: created_channel.id.to_string(),
})
}
@@ -1192,7 +1178,7 @@ where
owner_id: MacroUserIdStr<'a>,
org_id: Option<i64>,
req: crate::domain::models::CreateChannelRequest,
- ) -> Result<Uuid, ChannelMutationErr> {
+ ) -> Result<crate::domain::models::CreatedChannel, ChannelMutationErr> {
self.repo
.create_channel(owner_id, org_id, req)
.await
@@ -1216,22 +1202,18 @@ where
let channel_type = create_req.channel_type;
let channel_name = create_req.name.clone();
let owner_sender = ChannelSender::new_from_user(owner_id.clone());
- let participant_user_ids =
- created_channel_participant_ids(owner_id.clone(), create_req.participants.clone())
- .into_iter()
- .collect();
- let channel_id = self
+ let created_channel = self
.create_channel_record(owner_id, org_id, create_req)
.await?;
self.events.dispatch(ChannelEvent::ChannelCreated {
- channel_id,
+ channel_id: created_channel.id,
actor: owner_sender,
channel_type,
channel_name,
- participant_user_ids,
+ participant_user_ids: created_channel.participant_user_ids,
});
Ok(GetOrCreateChannelResponse {
- channel_id: channel_id.to_string(),
+ channel_id: created_channel.id.to_string(),
action: GetOrCreateAction::Create,
})
}
diff --git a/crates/channels/src/domain/service/test.rs b/crates/channels/src/domain/service/test.rs
index 02334331fd..621933622b 100644
--- a/crates/channels/src/domain/service/test.rs
+++ b/crates/channels/src/domain/service/test.rs
@@ -5,12 +5,12 @@ use crate::domain::{
Activity, ActivityType, BotId, BotSenderProfile, ChannelAttachment, ChannelAttachmentType,
ChannelContextMessage, ChannelInfo, ChannelMessageFilters, ChannelMetadata,
ChannelParticipant, ChannelType, CountedReaction, CreateChannelRequest,
- CreateEntityMentionOptions, DeleteMessageQuery, EntityMention, MessageAttachment,
- MessagePageDirection, MutatedAttachment, MutatedMessage, NewChannelAttachment,
- ParticipantRole, PatchChannelRequest, PatchMessageRequest, PostMessageRequest,
- PostReactionRequest, ReactionAction, ReferencedShareItem, ReferencedShareItemType,
- ResolvedChannelMessage, Sender, SimpleMention, ThreadData, ThreadReplyRow,
- TopLevelMessageRow,
+ CreateEntityMentionOptions, CreatedChannel, DeleteMessageQuery, EntityMention,
+ MessageAttachment, MessagePageDirection, MutatedAttachment, MutatedMessage,
+ NewChannelAttachment, ParticipantRole, PatchChannelRequest, PatchMessageRequest,
+ PostMessageRequest, PostReactionRequest, ReactionAction, ReferencedShareItem,
+ ReferencedShareItemType, ResolvedChannelMessage, Sender, SimpleMention, ThreadData,
+ ThreadReplyRow, TopLevelMessageRow,
},
ports::{
ChannelEventDispatcher, ChannelMentionExtractor, ChannelReferenceSharePermissions,
@@ -523,11 +523,27 @@ impl ChannelRepo for FakeMutationRepo {
async fn create_channel(
&self,
- _owner_id: MacroUserIdStr<'_>,
+ owner_id: MacroUserIdStr<'_>,
_org_id: Option<i64>,
- _req: crate::domain::models::CreateChannelRequest,
- ) -> Result<Uuid, Self::Err> {
- Ok(self.state.lock().unwrap().channel_id)
+ req: crate::domain::models::CreateChannelRequest,
+ ) -> Result<CreatedChannel, Self::Err> {
+ let state = self.state.lock().unwrap();
+ let mut participant_user_ids = req.participants;
+ participant_user_ids.insert(owner_id.into_owned());
+ if req.auto_join_team {
+ participant_user_ids.extend(
+ state
+ .participants
+ .iter()
+ .map(|participant| macro_id(&participant.user_id)),
+ );
+ }
+ let mut participant_user_ids: Vec<_> = participant_user_ids.into_iter().collect();
+ participant_user_ids.sort_by(|a, b| a.as_ref().cmp(b.as_ref()));
+ Ok(CreatedChannel {
+ id: state.channel_id,
+ participant_user_ids,
+ })
}
async fn auto_join_by_team_id(
@@ -1935,6 +1951,37 @@ async fn create_private_channel_allows_no_invited_participants() {
));
}
+#[tokio::test]
+async fn create_auto_join_team_channel_event_includes_current_team_members() {
+ let channel_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ let events = FakeEvents::default();
+ let svc = mutation_service(repo, events.clone(), FakeReferenceSharing::default());
+
+ svc.create_channel(
+ sender("macro|[email protected]"),
+ None,
+ CreateChannelRequest {
+ name: Some("general".to_string()),
+ channel_type: ChannelType::Team,
+ team_id: Some(Uuid::new_v4()),
+ auto_join_team: true,
+ participants: HashSet::from([macro_id("macro|[email protected]")]),
+ },
+ )
+ .await
+ .unwrap();
+
+ let events = events.events.lock().unwrap();
+ assert!(matches!(
+ events.as_slice(),
+ [ChannelEvent::ChannelCreated { participant_user_ids, .. }]
+ if participant_user_ids.len() == 2
+ && participant_user_ids.contains(&macro_id("macro|[email protected]"))
+ && participant_user_ids.contains(&macro_id("macro|[email protected]"))
+ ));
+}
+
#[test]
fn create_channel_request_defaults_auto_join_team_to_false() {
let request: CreateChannelRequest = serde_json::from_value(serde_json::json!({
diff --git a/crates/channels/src/outbound/pg_channels_repo.rs b/crates/channels/src/outbound/pg_channels_repo.rs
index 6abe8f9b48..c054488ad0 100644
--- a/crates/channels/src/outbound/pg_channels_repo.rs
+++ b/crates/channels/src/outbound/pg_channels_repo.rs
@@ -12,12 +12,12 @@ use crate::domain::{
ChannelAttachmentType, ChannelContextMessage, ChannelInfo, ChannelListItem, ChannelMessage,
ChannelMessageFilters, ChannelMessageKind, ChannelMetadata, ChannelParticipant,
ChannelPreviewRow, ChannelType, ChannelWithParticipants, CountedReaction,
- CreateChannelRequest, CreateEntityMentionOptions, EntityMention, GetChannelsParams,
- GetThreadReplyRowsParams, LatestMessage, MessageAttachment, MessagePageDirection,
- MutatedAttachment, MutatedMessage, NameLookup, NewChannelAttachment, ParticipantRole,
- PatchChannelRequest, RecentChannelMessage, ResolvedChannelMessage, SimpleMention,
- ThreadData, ThreadInfo, ThreadReply, ThreadReplyRow, TopLevelMessageRow, UserName,
- fallback_user_name,
+ CreateChannelRequest, CreateEntityMentionOptions, CreatedChannel, EntityMention,
+ GetChannelsParams, GetThreadReplyRowsParams, LatestMessage, MessageAttachment,
+ MessagePageDirection, MutatedAttachment, MutatedMessage, NameLookup, NewChannelAttachment,
+ ParticipantRole, PatchChannelRequest, RecentChannelMessage, ResolvedChannelMessage,
+ SimpleMention, ThreadData, ThreadInfo, ThreadReply, ThreadReplyRow, TopLevelMessageRow,
+ UserName, fallback_user_name,
},
ports::{ChannelRepo, TopLevelMessagesQueryResult},
};
@@ -2737,7 +2737,14 @@ impl ChannelRepo for PgChannelsRepo {
owner_id: MacroUserIdStr<'_>,
_org_id: Option<i64>,
req: CreateChannelRequest,
- ) -> Result<Uuid, Self::Err> {
+ ) -> Result<CreatedChannel, Self::Err> {
+ let CreateChannelRequest {
+ name,
+ channel_type,
+ team_id,
+ auto_join_team,
+ participants,
+ } = req;
let channel_id = macro_uuid::generate_uuid_v7();
let mut transaction = self.pool.begin().await?;
sqlx::query!(
@@ -2748,12 +2755,12 @@ impl ChannelRepo for PgChannelsRepo {
VALUES ($1, $2, $3, $4, $5, $6, $7)
"#,
channel_id,
- req.name.as_deref(),
+ name.as_deref(),
owner_id.as_ref(),
None::<i64>,
- req.team_id,
- req.channel_type as ChannelType,
- req.auto_join_team,
+ team_id,
+ channel_type as ChannelType,
+ auto_join_team,
)
.execute(&mut *transaction)
.await
@@ -2772,8 +2779,7 @@ impl ChannelRepo for PgChannelsRepo {
.await
.context("unable to create channel participant for owner")?;
- for participant in req
- .participants
+ for participant in participants
.into_iter()
.filter(|participant| participant.as_ref() != owner_id.as_ref())
{
@@ -2791,14 +2797,52 @@ impl ChannelRepo for PgChannelsRepo {
.context("unable to create channel participant")?;
}
+ if auto_join_team {
+ sqlx::query!(
+ r#"
+ INSERT INTO comms_channel_participants (channel_id, role, user_id)
+ SELECT $1, 'member'::comms_participant_role, user_id
+ FROM team_user
+ WHERE team_id = $2
+ ON CONFLICT (channel_id, user_id) DO NOTHING
+ "#,
+ channel_id,
+ team_id,
+ )
+ .execute(&mut *transaction)
+ .await
+ .context("unable to add current team members to channel")?;
+ }
+
create_activity(&mut *transaction, channel_id, owner_id.as_ref())
.await
.context("unable to create activity for channel")?;
+
+ let participant_user_ids = sqlx::query_scalar!(
+ r#"
+ SELECT user_id
+ FROM comms_channel_participants
+ WHERE channel_id = $1 AND left_at IS NULL
+ ORDER BY user_id
+ "#,
+ channel_id,
+ )
+ .fetch_all(&mut *transaction)
+ .await
+ .context("unable to fetch created channel participants")?
+ .into_iter()
+ .map(MacroUserIdStr::try_from)
+ .collect::<Result<Vec<_>, _>>()
+ .context("created channel contains an invalid user id")?;
+
transaction
.commit()
.await
.context("unable to commit transaction")?;
- Ok(channel_id)
+ Ok(CreatedChannel {
+ id: channel_id,
+ participant_user_ids,
+ })
}
async fn auto_join_by_team_id(
diff --git a/crates/channels/src/outbound/pg_channels_repo/tests.rs b/crates/channels/src/outbound/pg_channels_repo/tests.rs
index 8c6f0ee44e..b26c81e9c3 100644
--- a/crates/channels/src/outbound/pg_channels_repo/tests.rs
+++ b/crates/channels/src/outbound/pg_channels_repo/tests.rs
@@ -233,7 +233,7 @@ async fn is_participant_filter_inside_not_widens_candidates(pool: Pool<Postgres>
fixtures(path = "../../../fixtures", scripts("channels_repo")),
migrator = "MACRO_DB_MIGRATIONS"
)]
-async fn create_channel_persists_auto_join_team(pool: Pool<Postgres>) {
+async fn create_channel_persists_auto_join_team_and_adds_current_members(pool: Pool<Postgres>) {
let repo = repo(pool.clone());
let enabled_channel_id = repo
@@ -267,21 +267,60 @@ async fn create_channel_persists_auto_join_team(pool: Pool<Postgres>) {
let enabled = sqlx::query_scalar!(
"SELECT auto_join_team FROM comms_channels WHERE id = $1",
- enabled_channel_id,
+ enabled_channel_id.id,
)
.fetch_one(&pool)
.await
.unwrap();
let disabled = sqlx::query_scalar!(
"SELECT auto_join_team FROM comms_channels WHERE id = $1",
- disabled_channel_id,
+ disabled_channel_id.id,
)
.fetch_one(&pool)
.await
.unwrap();
+ let enabled_participants = sqlx::query!(
+ r#"
+ SELECT user_id, role AS "role: ParticipantRole"
+ FROM comms_channel_participants
+ WHERE channel_id = $1
+ ORDER BY user_id
+ "#,
+ enabled_channel_id.id,
+ )
+ .fetch_all(&pool)
+ .await
+ .unwrap();
+ let disabled_participants = sqlx::query_scalar!(
+ r#"
+ SELECT user_id
+ FROM comms_channel_participants
+ WHERE channel_id = $1
+ ORDER BY user_id
+ "#,
+ disabled_channel_id.id,
+ )
+ .fetch_all(&pool)
+ .await
+ .unwrap();
assert!(enabled);
assert!(!disabled);
+ assert_eq!(
+ enabled_participants
+ .iter()
+ .map(|participant| (participant.user_id.as_str(), participant.role))
+ .collect::<Vec<_>>(),
+ vec![
+ (LEFT_USER, ParticipantRole::Member),
+ (USER_A, ParticipantRole::Owner),
+ ]
+ );
+ assert_eq!(disabled_participants, vec![USER_A]);
+ assert_eq!(
+ enabled_channel_id.participant_user_ids,
+ vec![macro_user_id(LEFT_USER), macro_user_id(USER_A)]
+ );
}
#[sqlx::test(
diff --git a/crates/teams/src/outbound/team_repo/test.rs b/crates/teams/src/outbound/team_repo/test.rs
index 3abdbdb3fe..b9de21b0d0 100644
--- a/crates/teams/src/outbound/team_repo/test.rs
+++ b/crates/teams/src/outbound/team_repo/test.rs
@@ -1670,33 +1670,6 @@ async fn test_get_team_id_by_domain(pool: Pool<Postgres>) -> anyhow::Result<()>
Ok(())
}
-#[sqlx::test(
- migrator = "MACRO_DB_MIGRATIONS",
- fixtures(path = "../../../fixtures", scripts("teams"))
-)]
-async fn test_get_team_id_by_domain_prefers_oldest_team(
- pool: Pool<Postgres>,
-) -> anyhow::Result<()> {
- sqlx::query("UPDATE team SET auto_join_domain = 'user.com'")
- .execute(&pool)
- .await?;
-
- let team_repo = TeamRepositoryImpl::new(pool);
-
- // Both fixture teams claim user.com; the one with the lowest id wins.
- let found = team_repo
- .get_team_id_by_domain(&MacroUserIdStr::parse_from_str("macro|[email protected]")?)
- .await?;
- assert_eq!(
- found,
- Some(macro_uuid::string_to_uuid(
- "11111111-1111-1111-1111-111111111111"
- )?)
- );
-
- Ok(())
-}
-
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("teams"))