Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Merge branch 'main' into guest-exp
Conrad Irwinea4e67fb76cf
diff --cc crates/channel/src/channel_chat.rsindex 299c91759cd,ca344c409f5..ef11d964249--- a/crates/channel/src/channel_chat.rs+++ b/crates/channel/src/channel_chat.rs@@@ -14,8 -19,9 +19,9 @@@ use time::OffsetDateTimeuse util::{post_inc, ResultExt as _, TryFutureExt};pub struct ChannelChat {- channel: Arc<Channel>,+ pub channel_id: ChannelId,messages: SumTree<ChannelMessage>,+ acknowledged_message_ids: HashSet<u64>,channel_store: ModelHandle<ChannelStore>,loaded_all_messages: bool,last_acknowledged_id: Option<u64>,@@@ -116,19 -130,20 +130,23 @@@ impl ChannelChat}))}- pub fn channel(&self) -> &Arc<Channel> {- &self.channel+ pub fn channel(&self, cx: &AppContext) -> Option<Arc<Channel>> {+ self.channel_store+ .read(cx)+ .channel_for_id(self.channel_id)+ .cloned()}+ pub fn client(&self) -> &Arc<Client> {+ &self.rpc+ }+pub fn send_message(&mut self,- body: String,+ message: MessageParams,cx: &mut ModelContext<Self>,- ) -> Result<Task<Result<()>>> {- if body.is_empty() {+ ) -> Result<Task<Result<u64>>> {+ if message.text.is_empty() {Err(anyhow!("message body can't be empty"))?;}@@@ -194,41 -208,76 +211,76 @@@})}- pub fn load_more_messages(&mut self, cx: &mut ModelContext<Self>) -> bool {- if !self.loaded_all_messages {- let rpc = self.rpc.clone();- let user_store = self.user_store.clone();- let channel_id = self.channel_id;- if let Some(before_message_id) =- self.messages.first().and_then(|message| match message.id {- ChannelMessageId::Saved(id) => Some(id),- ChannelMessageId::Pending(_) => None,- })- {- cx.spawn(|this, mut cx| {- async move {- let response = rpc- .request(proto::GetChannelMessages {- channel_id,- before_message_id,- })- .await?;- let loaded_all_messages = response.done;- let messages =- messages_from_proto(response.messages, &user_store, &mut cx).await?;- this.update(&mut cx, |this, cx| {- this.loaded_all_messages = loaded_all_messages;- this.insert_messages(messages, cx);- });- anyhow::Ok(())+ pub fn load_more_messages(&mut self, cx: &mut ModelContext<Self>) -> Option<Task<Option<()>>> {+ if self.loaded_all_messages {+ return None;+ }++ let rpc = self.rpc.clone();+ let user_store = self.user_store.clone();- let channel_id = self.channel.id;++ let channel_id = self.channel_id;+ let before_message_id = self.first_loaded_message_id()?;+ Some(cx.spawn(|this, mut cx| {+ async move {+ let response = rpc+ .request(proto::GetChannelMessages {+ channel_id,+ before_message_id,+ })+ .await?;+ let loaded_all_messages = response.done;+ let messages = messages_from_proto(response.messages, &user_store, &mut cx).await?;+ this.update(&mut cx, |this, cx| {+ this.loaded_all_messages = loaded_all_messages;+ this.insert_messages(messages, cx);+ });+ anyhow::Ok(())+ }+ .log_err()+ }))+ }++ pub fn first_loaded_message_id(&mut self) -> Option<u64> {+ self.messages.first().and_then(|message| match message.id {+ ChannelMessageId::Saved(id) => Some(id),+ ChannelMessageId::Pending(_) => None,+ })+ }++ /// Load all of the chat messages since a certain message id.+ ///+ /// For now, we always maintain a suffix of the channel's messages.+ pub async fn load_history_since_message(+ chat: ModelHandle<Self>,+ message_id: u64,+ mut cx: AsyncAppContext,+ ) -> Option<usize> {+ loop {+ let step = chat.update(&mut cx, |chat, cx| {+ if let Some(first_id) = chat.first_loaded_message_id() {+ if first_id <= message_id {+ let mut cursor = chat.messages.cursor::<(ChannelMessageId, Count)>();+ let message_id = ChannelMessageId::Saved(message_id);+ cursor.seek(&message_id, Bias::Left, &());+ return ControlFlow::Break(+ if cursor+ .item()+ .map_or(false, |message| message.id == message_id)+ {+ Some(cursor.start().1 .0)+ } else {+ None+ },+ );}- .log_err()- })- .detach();- return true;+ }+ ControlFlow::Continue(chat.load_more_messages(cx))+ });+ match step {+ ControlFlow::Break(ix) => return ix,+ ControlFlow::Continue(task) => task?.await?,}}- false}pub fn acknowledge_last_message(&mut self, cx: &mut ModelContext<Self>) {@@@ -322,6 -372,17 +375,17 @@@cursor.item().unwrap()}+ pub fn acknowledge_message(&mut self, id: u64) {+ if self.acknowledged_message_ids.insert(id) {+ self.rpc+ .send(proto::AckChannelMessage {- channel_id: self.channel.id,++ channel_id: self.channel_id,+ message_id: id,+ })+ .ok();+ }+ }+pub fn messages_in_range(&self, range: Range<usize>) -> impl Iterator<Item = &ChannelMessage> {let mut cursor = self.messages.cursor::<Count>();cursor.seek(&Count(range.start), Bias::Right, &());diff --cc crates/channel/src/channel_store.rsindex 2e1e92431e2,221b8452970..2665c2e1ec0--- a/crates/channel/src/channel_store.rs+++ b/crates/channel/src/channel_store.rs@@@ -764,6 -800,6 +795,11 @@@ impl ChannelStore}fn handle_connect(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {++ self.channel_index.clear();++ self.channel_invitations.clear();++ self.channel_participants.clear();++ self.channel_index.clear();++ self.outgoing_invites.clear();self.disconnect_channel_buffers_task.take();for chat in self.opened_chats.values() {@@@ -873,11 -909,12 +909,6 @@@}fn handle_disconnect(&mut self, wait_for_reconnect: bool, cx: &mut ModelContext<Self>) {-- self.channel_index.clear();-- self.channel_invitations.clear();-- self.channel_participants.clear();- self.channels_with_admin_privileges.clear();-- self.channel_index.clear();-- self.outgoing_invites.clear();cx.notify();self.disconnect_channel_buffers_task.get_or_insert_with(|| {diff --cc crates/collab/src/db.rsindex 936b6552003,5f3d0fc0c7c..8c6bca21137--- a/crates/collab/src/db.rs+++ b/crates/collab/src/db.rs@@@ -428,44 -435,6 +435,62 @@@ pub struct NewUserResultpub signup_device_id: Option<String>,}+#[derive(Debug)]+pub struct MoveChannelResult {+ pub participants_to_update: HashMap<UserId, ChannelsForUser>,+ pub participants_to_remove: HashSet<UserId>,+ pub moved_channels: HashSet<ChannelId>,+}++#[derive(Debug)]+pub struct RenameChannelResult {+ pub channel: Channel,+ pub participants_to_update: HashMap<UserId, Channel>,+}++#[derive(Debug)]+pub struct CreateChannelResult {+ pub channel: Channel,+ pub participants_to_update: Vec<(UserId, ChannelsForUser)>,+}++#[derive(Debug)]+pub struct SetChannelVisibilityResult {+ pub participants_to_update: HashMap<UserId, ChannelsForUser>,+ pub participants_to_remove: HashSet<UserId>,+}++#[derive(Debug)]+pub struct MembershipUpdated {+ pub channel_id: ChannelId,+ pub new_channels: ChannelsForUser,+ pub removed_channels: Vec<ChannelId>,+}++#[derive(Debug)]+pub enum SetMemberRoleResult {+ InviteUpdated(Channel),+ MembershipUpdated(MembershipUpdated),+}+++#[derive(Debug)]++pub struct InviteMemberResult {++ pub channel: Channel,++ pub notifications: NotificationBatch,++}++++#[derive(Debug)]++pub struct RespondToChannelInvite {++ pub membership_update: Option<MembershipUpdated>,++ pub notifications: NotificationBatch,++}++++#[derive(Debug)]++pub struct RemoveChannelMemberResult {++ pub membership_update: MembershipUpdated,++ pub notification_id: Option<NotificationId>,++}++#[derive(FromQueryResult, Debug, PartialEq, Eq, Hash)]pub struct Channel {pub id: ChannelId,diff --cc crates/collab/src/db/ids.rsindex 4c6e7116eeb,433444de67e..5f0df90811c--- a/crates/collab/src/db/ids.rs+++ b/crates/collab/src/db/ids.rs@@@ -81,8 -81,10 +81,10 @@@ id_type!(SignupId)id_type!(UserId);id_type!(ChannelBufferCollaboratorId);id_type!(FlagId);+ id_type!(NotificationId);+ id_type!(NotificationKindId);-#[derive(Eq, PartialEq, Copy, Clone, Debug, EnumIter, DeriveActiveEnum, Default)]+#[derive(Eq, PartialEq, Copy, Clone, Debug, EnumIter, DeriveActiveEnum, Default, Hash)]#[sea_orm(rs_type = "String", db_type = "String(None)")]pub enum ChannelRole {#[sea_orm(string_value = "admin")]diff --cc crates/collab/src/db/queries/channels.rsindex dbc701e4ae0,4ee7625afdf..0abd36049dc--- a/crates/collab/src/db/queries/channels.rs+++ b/crates/collab/src/db/queries/channels.rs@@@ -349,13 -269,18 +349,13 @@@ impl Database&self,channel_id: ChannelId,invitee_id: UserId,- admin_id: UserId,+ inviter_id: UserId,role: ChannelRole,- ) -> Result<Channel> {- ) -> Result<NotificationBatch> {++ ) -> Result<InviteMemberResult> {self.transaction(move |tx| async move {- self.check_user_is_channel_admin(channel_id, admin_id, &*tx)+ self.check_user_is_channel_admin(channel_id, inviter_id, &*tx).await?;- let channel = channel::Entity::find_by_id(channel_id)- .one(&*tx)- .await?- .ok_or_else(|| anyhow!("no such channel"))?;-channel_member::ActiveModel {id: ActiveValue::NotSet,channel_id: ActiveValue::Set(channel_id),@@@ -366,17 -291,20 +366,37 @@@.insert(&*tx).await?;- Ok(self+ let channel = channel::Entity::find_by_id(channel_id)+ .one(&*tx)+ .await?+ .unwrap();+- Ok(Channel {++ let channel = Channel {+ id: channel.id,+ visibility: channel.visibility,+ name: channel.name,+ role,++ };++++ let notifications = self+ .create_notification(+ invitee_id,+ rpc::Notification::ChannelInvitation {+ channel_id: channel_id.to_proto(),- channel_name: channel.name,++ channel_name: channel.name.clone(),+ inviter_id: inviter_id.to_proto(),+ },+ true,+ &*tx,+ )+ .await?+ .into_iter()- .collect())++ .collect();++++ Ok(InviteMemberResult {++ channel,++ notifications,+ })}).await}@@@ -445,10 -351,10 +465,10 @@@channel_id: ChannelId,user_id: UserId,accept: bool,- ) -> Result<Option<MembershipUpdated>> {- ) -> Result<NotificationBatch> {++ ) -> Result<RespondToChannelInvite> {self.transaction(move |tx| async move {- if accept {- let rows_affected = if accept {- channel_member::Entity::update_many()++ let membership_update = if accept {+ let rows_affected = channel_member::Entity::update_many().set(channel_member::ActiveModel {accepted: ActiveValue::Set(accept),..Default::default()@@@ -461,88 -367,40 +481,107 @@@).exec(&*tx).await?- .rows_affected+ .rows_affected;++ if rows_affected == 0 {+ Err(anyhow!("no such invitation"))?;+ }+- return Ok(Some(++ Some(+ self.calculate_membership_updated(channel_id, user_id, &*tx)+ .await?,- ));- }-- let rows_affected = channel_member::ActiveModel {- channel_id: ActiveValue::Unchanged(channel_id),- user_id: ActiveValue::Unchanged(user_id),- ..Default::default()- }- .delete(&*tx)- .await?- .rows_affected;++ )+ } else {- channel_member::Entity::delete_many()++ let rows_affected = channel_member::Entity::delete_many()+ .filter(+ channel_member::Column::ChannelId+ .eq(channel_id)+ .and(channel_member::Column::UserId.eq(user_id))+ .and(channel_member::Column::Accepted.eq(false)),+ )+ .exec(&*tx)+ .await?- .rows_affected++ .rows_affected;++ if rows_affected == 0 {++ Err(anyhow!("no such invitation"))?;++ }+- if rows_affected == 0 {- Err(anyhow!("no such invitation"))?;- }++ None+ };- Ok(None)- if rows_affected == 0 {- Err(anyhow!("no such invitation"))?;++ Ok(RespondToChannelInvite {++ membership_update,++ notifications: self++ .mark_notification_as_read_with_response(++ user_id,++ &rpc::Notification::ChannelInvitation {++ channel_id: channel_id.to_proto(),++ channel_name: Default::default(),++ inviter_id: Default::default(),++ },++ accept,++ &*tx,++ )++ .await?++ .into_iter()++ .collect(),++ })+ })+ .await+ }++ async fn calculate_membership_updated(+ &self,+ channel_id: ChannelId,+ user_id: UserId,+ tx: &DatabaseTransaction,+ ) -> Result<MembershipUpdated> {+ let mut channel_to_refresh = channel_id;+ let mut removed_channels: Vec<ChannelId> = Vec::new();++ // if the user was previously a guest of a parent public channel they may have seen this+ // channel (or its descendants) in the tree already.+ // Now they have new permissions, the graph of channels needs updating from that point.+ if let Some(public_parent) = self.public_parent_channel_id(channel_id, &*tx).await? {+ if self+ .channel_role_for_user(public_parent, user_id, &*tx)+ .await?+ == Some(ChannelRole::Guest)+ {+ channel_to_refresh = public_parent;}+ }- Ok(self- .mark_notification_as_read_with_response(- user_id,- &rpc::Notification::ChannelInvitation {- channel_id: channel_id.to_proto(),- channel_name: Default::default(),- inviter_id: Default::default(),- },- accept,- &*tx,- )+ // remove all descendant channels from the user's tree+ removed_channels.append(+ &mut self+ .get_channel_descendants(vec![channel_to_refresh], &*tx).await?.into_iter()- .collect())+ .map(|edge| ChannelId::from_proto(edge.channel_id))+ .collect(),+ );++ let new_channels = self+ .get_user_channels(user_id, Some(channel_to_refresh), &*tx)+ .await?;++ // We only add the current channel to "moved" if the user has lost access,+ // otherwise it would be made a root channel on the client.+ if !new_channels+ .channels+ .channels+ .iter()+ .any(|c| c.id == channel_id)+ {+ removed_channels.push(channel_id);+ }++ Ok(MembershipUpdated {+ channel_id,+ new_channels,+ removed_channels,})- .await}pub async fn remove_channel_member(@@@ -550,7 -408,7 +589,7 @@@channel_id: ChannelId,member_id: UserId,admin_id: UserId,- ) -> Result<MembershipUpdated> {- ) -> Result<Option<NotificationId>> {++ ) -> Result<RemoveChannelMemberResult> {self.transaction(|tx| async move {self.check_user_is_channel_admin(channel_id, admin_id, &*tx).await?;@@@ -568,9 -426,17 +607,22 @@@Err(anyhow!("no such member"))?;}-- Ok(self- .calculate_membership_updated(channel_id, member_id, &*tx)- .remove_notification(- member_id,- rpc::Notification::ChannelInvitation {- channel_id: channel_id.to_proto(),- channel_name: Default::default(),- inviter_id: Default::default(),- },- &*tx,- )-- .await?)++ Ok(RemoveChannelMemberResult {++ membership_update: self++ .calculate_membership_updated(channel_id, member_id, &*tx)++ .await?,++ notification_id: self++ .remove_notification(++ member_id,++ rpc::Notification::ChannelInvitation {++ channel_id: channel_id.to_proto(),++ channel_name: Default::default(),++ inviter_id: Default::default(),++ },++ &*tx,++ )++ .await?,++ })}).await}@@@ -911,132 -707,141 +963,151 @@@.await}+ pub async fn get_channel_participant_details(+ &self,+ channel_id: ChannelId,+ user_id: UserId,+ ) -> Result<Vec<proto::ChannelMember>> {- self.transaction(|tx| async move {- let user_role = self- .check_user_is_channel_member(channel_id, user_id, &*tx)- .await?;++ let (role, members) = self++ .transaction(move |tx| async move {++ let role = self++ .check_user_is_channel_participant(channel_id, user_id, &*tx)++ .await?;++ Ok((++ role,++ self.get_channel_participant_details_internal(channel_id, &*tx)++ .await?,++ ))++ })++ .await?;+- let channel_visibility = channel::Entity::find()- .filter(channel::Column::Id.eq(channel_id))- .one(&*tx)- .await?- .map(|channel| channel.visibility)- .unwrap_or(ChannelVisibility::Members);++ if role == ChannelRole::Admin {++ Ok(members++ .into_iter()++ .map(|channel_member| channel_member.to_proto())++ .collect())++ } else {++ return Ok(members++ .into_iter()++ .filter_map(|member| {++ if member.kind == proto::channel_member::Kind::Invitee {++ return None;++ }++ Some(ChannelMember {++ role: member.role,++ user_id: member.user_id,++ kind: proto::channel_member::Kind::Member,++ })++ })++ .map(|channel_member| channel_member.to_proto())++ .collect());++ }++ }+- #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]- enum QueryMemberDetails {- UserId,- Role,- IsDirectMember,- Accepted,- Visibility,- }+ async fn get_channel_participant_details_internal(+ &self,+ channel_id: ChannelId,+ tx: &DatabaseTransaction,+ ) -> Result<Vec<ChannelMember>> {+ let channel_visibility = channel::Entity::find()+ .filter(channel::Column::Id.eq(channel_id))+ .one(&*tx)+ .await?+ .map(|channel| channel.visibility)+ .unwrap_or(ChannelVisibility::Members);- let tx = tx;- let ancestor_ids = self.get_channel_ancestors(channel_id, &*tx).await?;- let mut stream = channel_member::Entity::find()- .left_join(channel::Entity)- .filter(channel_member::Column::ChannelId.is_in(ancestor_ids.iter().copied()))- .select_only()- .column(channel_member::Column::UserId)- .column(channel_member::Column::Role)- .column_as(- channel_member::Column::ChannelId.eq(channel_id),- QueryMemberDetails::IsDirectMember,- )- .column(channel_member::Column::Accepted)- .column(channel::Column::Visibility)- .into_values::<_, QueryMemberDetails>()- .stream(&*tx)- .await?;+ #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]+ enum QueryMemberDetails {+ UserId,+ Role,+ IsDirectMember,+ Accepted,+ Visibility,+ }- struct UserDetail {- kind: Kind,- channel_role: ChannelRole,+ let tx = tx;+ let ancestor_ids = self.get_channel_ancestors(channel_id, &*tx).await?;+ let mut stream = channel_member::Entity::find()+ .left_join(channel::Entity)+ .filter(channel_member::Column::ChannelId.is_in(ancestor_ids.iter().copied()))+ .select_only()+ .column(channel_member::Column::UserId)+ .column(channel_member::Column::Role)+ .column_as(+ channel_member::Column::ChannelId.eq(channel_id),+ QueryMemberDetails::IsDirectMember,+ )+ .column(channel_member::Column::Accepted)+ .column(channel::Column::Visibility)+ .into_values::<_, QueryMemberDetails>()+ .stream(&*tx)+ .await?;++ let mut user_details: HashMap<UserId, ChannelMember> = HashMap::default();++ while let Some(user_membership) = stream.next().await {+ let (user_id, channel_role, is_direct_member, is_invite_accepted, visibility): (+ UserId,+ ChannelRole,+ bool,+ bool,+ ChannelVisibility,+ ) = user_membership?;+ let kind = match (is_direct_member, is_invite_accepted) {+ (true, true) => proto::channel_member::Kind::Member,+ (true, false) => proto::channel_member::Kind::Invitee,+ (false, true) => proto::channel_member::Kind::AncestorMember,+ (false, false) => continue,+ };++ if channel_role == ChannelRole::Guest+ && visibility != ChannelVisibility::Public+ && channel_visibility != ChannelVisibility::Public+ {+ continue;}- let mut user_details: HashMap<UserId, UserDetail> = HashMap::default();-- while let Some(user_membership) = stream.next().await {- let (user_id, channel_role, is_direct_member, is_invite_accepted, visibility): (- UserId,- ChannelRole,- bool,- bool,- ChannelVisibility,- ) = user_membership?;- let kind = match (is_direct_member, is_invite_accepted) {- (true, true) => proto::channel_member::Kind::Member,- (true, false) => proto::channel_member::Kind::Invitee,- (false, true) => proto::channel_member::Kind::AncestorMember,- (false, false) => continue,- };-- if channel_role == ChannelRole::Guest- && visibility != ChannelVisibility::Public- && channel_visibility != ChannelVisibility::Public- {- continue;- }- if let Some(details_mut) = user_details.get_mut(&user_id) {- if channel_role.should_override(details_mut.channel_role) {- details_mut.channel_role = channel_role;- }- if kind == Kind::Member {- details_mut.kind = kind;- // the UI is going to be a bit confusing if you already have permissions- // that are greater than or equal to the ones you're being invited to.- } else if kind == Kind::Invitee && details_mut.kind == Kind::AncestorMember {- details_mut.kind = kind;- }- } else {- user_details.insert(user_id, UserDetail { kind, channel_role });+ if let Some(details_mut) = user_details.get_mut(&user_id) {+ if channel_role.should_override(details_mut.role) {+ details_mut.role = channel_role;}+ if kind == Kind::Member {+ details_mut.kind = kind;+ // the UI is going to be a bit confusing if you already have permissions+ // that are greater than or equal to the ones you're being invited to.+ } else if kind == Kind::Invitee && details_mut.kind == Kind::AncestorMember {+ details_mut.kind = kind;+ }+ } else {+ user_details.insert(+ user_id,+ ChannelMember {+ user_id,+ kind,+ role: channel_role,+ },+ );}+ }- Ok(user_details- .into_iter()- .filter_map(|(user_id, mut details)| {- // If the user is not an admin, don't give them as much- // information about the other members.- if user_role != ChannelRole::Admin {- if details.kind == Kind::Invitee- || details.channel_role == ChannelRole::Banned- {- return None;- }-- if details.channel_role == ChannelRole::Admin {- details.channel_role = ChannelRole::Member;- }- }-- Some(proto::ChannelMember {- user_id: user_id.to_proto(),- kind: details.kind.into(),- role: details.channel_role.into(),- })- })- .collect())- })- .await+ Ok(user_details+ .into_iter()+ .map(|(_, details)| details)+ .collect())}- pub async fn get_channel_participant_details(- &self,- channel_id: ChannelId,- admin_id: UserId,- ) -> Result<Vec<proto::ChannelMember>> {- let members = self- .transaction(move |tx| async move {- self.check_user_is_channel_admin(channel_id, admin_id, &*tx)- .await?;-- Ok(self- .get_channel_participant_details_internal(channel_id, &*tx)- .await?)- })- .await?;-- Ok(members- .into_iter()- .map(|channel_member| channel_member.to_proto())- .collect())- }-- pub async fn get_channel_participants_internal(+ pub async fn get_channel_participants(&self,- id: ChannelId,+ channel_id: ChannelId,tx: &DatabaseTransaction,) -> Result<Vec<UserId>> {- let ancestor_ids = self.get_channel_ancestors(id, tx).await?;- let user_ids = channel_member::Entity::find()- .distinct()- .filter(- channel_member::Column::ChannelId- .is_in(ancestor_ids.iter().copied())- .and(channel_member::Column::Accepted.eq(true)),- )- .select_only()- .column(channel_member::Column::UserId)- .into_values::<_, QueryUserIds>()- .all(&*tx)+ let participants = self+ .get_channel_participant_details_internal(channel_id, &*tx).await?;- Ok(user_ids)+ Ok(participants+ .into_iter()+ .map(|member| member.user_id)+ .collect())}pub async fn check_user_is_channel_admin(diff --cc crates/collab/src/db/queries/messages.rsindex 4bcac025c58,d406cbb0913..562c4e45c45--- a/crates/collab/src/db/queries/messages.rs+++ b/crates/collab/src/db/queries/messages.rs@@@ -121,13 -198,11 +198,14 @@@ impl Databasechannel_id: ChannelId,user_id: UserId,body: &str,+ mentions: &[proto::ChatMention],timestamp: OffsetDateTime,nonce: u128,- ) -> Result<(MessageId, Vec<ConnectionId>, Vec<UserId>)> {+ ) -> Result<CreatedChannelMessage> {self.transaction(|tx| async move {+ self.check_user_is_channel_participant(channel_id, user_id, &*tx)+ .await?;+let mut rows = channel_chat_participant::Entity::find().filter(channel_chat_participant::Column::ChannelId.eq(channel_id)).stream(&*tx)@@@ -169,28 -248,76 +251,74 @@@.exec(&*tx).await?;- #[derive(Debug, Clone, Copy, EnumIter, DeriveColumn)]- enum QueryConnectionId {- ConnectionId,- }+ let message_id;+ let mut notifications = Vec::new();+ match result {+ TryInsertResult::Inserted(result) => {+ message_id = result.last_insert_id;+ let mentioned_user_ids =+ mentions.iter().map(|m| m.user_id).collect::<HashSet<_>>();+ let mentions = mentions+ .iter()+ .filter_map(|mention| {+ let range = mention.range.as_ref()?;+ if !body.is_char_boundary(range.start as usize)+ || !body.is_char_boundary(range.end as usize)+ {+ return None;+ }+ Some(channel_message_mention::ActiveModel {+ message_id: ActiveValue::Set(message_id),+ start_offset: ActiveValue::Set(range.start as i32),+ end_offset: ActiveValue::Set(range.end as i32),+ user_id: ActiveValue::Set(UserId::from_proto(mention.user_id)),+ })+ })+ .collect::<Vec<_>>();+ if !mentions.is_empty() {+ channel_message_mention::Entity::insert_many(mentions)+ .exec(&*tx)+ .await?;+ }- // Observe this message for the sender- self.observe_channel_message_internal(- channel_id,- user_id,- message.last_insert_id,- &*tx,- )- .await?;+ for mentioned_user in mentioned_user_ids {+ notifications.extend(+ self.create_notification(+ UserId::from_proto(mentioned_user),+ rpc::Notification::ChannelMessageMention {+ message_id: message_id.to_proto(),+ sender_id: user_id.to_proto(),+ channel_id: channel_id.to_proto(),+ },+ false,+ &*tx,+ )+ .await?,+ );+ }++ self.observe_channel_message_internal(channel_id, user_id, message_id, &*tx)+ .await?;+ }+ _ => {+ message_id = channel_message::Entity::find()+ .filter(channel_message::Column::Nonce.eq(Uuid::from_u128(nonce)))+ .one(&*tx)+ .await?+ .ok_or_else(|| anyhow!("failed to insert message"))?+ .id;+ }+ }- let mut channel_members = self- .get_channel_participants_internal(channel_id, &*tx)- .await?;+ let mut channel_members = self.get_channel_participants(channel_id, &*tx).await?;channel_members.retain(|member| !participant_user_ids.contains(member));- Ok((- message.last_insert_id,+ Ok(CreatedChannelMessage {+ message_id,participant_connection_ids,channel_members,- ))+ notifications,+ })}).await}diff --cc crates/collab/src/db/tests.rsindex a53509a59f0,83154b9a0df..8f2939040d5--- a/crates/collab/src/db/tests.rs+++ b/crates/collab/src/db/tests.rs@@@ -10,7 -10,10 +10,10 @@@ use parking_lot::Mutexuse rpc::proto::ChannelEdge;use sea_orm::ConnectionTrait;use sqlx::migrate::MigrateDatabase;- use std::sync::Arc;+ use std::sync::{- atomic::{AtomicI32, Ordering::SeqCst},++ atomic::{AtomicI32, AtomicU32, Ordering::SeqCst},+ Arc,+ };const TEST_RELEASE_CHANNEL: &'static str = "test";@@@ -176,3 -177,19 +181,27 @@@ fn graphgraph}++ static GITHUB_USER_ID: AtomicI32 = AtomicI32::new(5);++ async fn new_test_user(db: &Arc<Database>, email: &str) -> UserId {+ db.create_user(+ email,+ false,+ NewUserParams {+ github_login: email[0..email.find("@").unwrap()].to_string(),+ github_user_id: GITHUB_USER_ID.fetch_add(1, SeqCst),+ },+ )+ .await+ .unwrap()+ .user_id+ }++++static TEST_CONNECTION_ID: AtomicU32 = AtomicU32::new(1);++fn new_test_connection(server: ServerId) -> ConnectionId {++ ConnectionId {++ id: TEST_CONNECTION_ID.fetch_add(1, SeqCst),++ owner_id: server.0 as u32,++ }++}diff --cc crates/collab/src/db/tests/channel_tests.rsindex 405839ba187,556437e45b6..32cba2fdd90--- a/crates/collab/src/db/tests/channel_tests.rs+++ b/crates/collab/src/db/tests/channel_tests.rs@@@ -1,21 -1,17 +1,18 @@@- use collections::{HashMap, HashSet};- use rpc::{- proto::{self},- ConnectionId,- };++use std::sync::Arc;+use crate::{db::{queries::channels::ChannelGraph,- tests::{graph, TEST_RELEASE_CHANNEL},- ChannelId, ChannelRole, Database, NewUserParams, RoomId, ServerId, UserId,- tests::{graph, new_test_user, TEST_RELEASE_CHANNEL},++ tests::{graph, new_test_connection, new_test_user, TEST_RELEASE_CHANNEL},+ ChannelId, ChannelRole, Database, NewUserParams, RoomId,},test_both_dbs,};- use std::sync::{- atomic::{AtomicI32, AtomicU32, Ordering},- Arc,+ use collections::{HashMap, HashSet};+ use rpc::{+ proto::{self},+ ConnectionId,};-use std::sync::Arc;test_both_dbs!(test_channels, test_channels_postgres, test_channels_sqlite);diff --cc crates/collab/src/db/tests/message_tests.rsindex f9d97e2181b,97b3142930a..10d9778612f--- a/crates/collab/src/db/tests/message_tests.rs+++ b/crates/collab/src/db/tests/message_tests.rs@@@ -12,39 -14,34 +14,38 @@@ test_both_dbs!);async fn test_channel_message_retrieval(db: &Arc<Database>) {- let user = db- .create_user(- "[email protected]",- false,- NewUserParams {- github_login: "user".into(),- github_user_id: 1,- invite_count: 0,- },- )- .await- .unwrap()- .user_id;- let channel = db.create_root_channel("channel", user).await.unwrap();+ let user = new_test_user(db, "[email protected]").await;- let channel = db.create_channel("channel", None, user).await.unwrap();++ let result = db.create_channel("channel", None, user).await.unwrap();let owner_id = db.create_server("test").await.unwrap().0 as u32;-- db.join_channel_chat(channel, rpc::ConnectionId { owner_id, id: 0 }, user)-- .await-- .unwrap();++ db.join_channel_chat(++ result.channel.id,++ rpc::ConnectionId { owner_id, id: 0 },++ user,++ )++ .await++ .unwrap();let mut all_messages = Vec::new();for i in 0..10 {all_messages.push(- db.create_channel_message(channel, user, &i.to_string(), OffsetDateTime::now_utc(), i)- .await- .unwrap()- .0- .to_proto(),+ db.create_channel_message(- channel,++ result.channel.id,+ user,+ &i.to_string(),+ &[],+ OffsetDateTime::now_utc(),+ i,+ )+ .await+ .unwrap()+ .message_id+ .to_proto(),);}let messages = db-- .get_channel_messages(channel, user, 3, None)++ .get_channel_messages(result.channel.id, user, 3, None).await.unwrap().into_iter()@@@ -54,7 -51,7 +55,7 @@@let messages = db.get_channel_messages(-- channel,++ result.channel.id,user,4,Some(MessageId::from_proto(all_messages[6])),@@@ -74,41 -71,28 +75,28 @@@ test_both_dbs!);async fn test_channel_message_nonces(db: &Arc<Database>) {- let user = db- .create_user(- "[email protected]",- false,- NewUserParams {- github_login: "user".into(),- github_user_id: 1,- invite_count: 0,- },- )+ let user_a = new_test_user(db, "[email protected]").await;+ let user_b = new_test_user(db, "[email protected]").await;+ let user_c = new_test_user(db, "[email protected]").await;- let channel = db.create_channel("channel", None, user_a).await.unwrap();++ let channel = db.create_root_channel("channel", user_a).await.unwrap();+ db.invite_channel_member(channel, user_b, user_a, ChannelRole::Member).await- .unwrap()- .user_id;- let channel = db.create_root_channel("channel", user).await.unwrap();-- let owner_id = db.create_server("test").await.unwrap().0 as u32;-- db.join_channel_chat(channel, rpc::ConnectionId { owner_id, id: 0 }, user)+ .unwrap();+ db.invite_channel_member(channel, user_c, user_a, ChannelRole::Member).await.unwrap();-- let msg1_id = db- .create_channel_message(channel, user, "1", OffsetDateTime::now_utc(), 1)+ db.respond_to_channel_invite(channel, user_b, true).await.unwrap();- let msg2_id = db- .create_channel_message(channel, user, "2", OffsetDateTime::now_utc(), 2)+ db.respond_to_channel_invite(channel, user_c, true).await.unwrap();- let msg3_id = db- .create_channel_message(channel, user, "3", OffsetDateTime::now_utc(), 1)++ let owner_id = db.create_server("test").await.unwrap().0 as u32;+ db.join_channel_chat(channel, rpc::ConnectionId { owner_id, id: 0 }, user_a).await.unwrap();- let msg4_id = db- .create_channel_message(channel, user, "4", OffsetDateTime::now_utc(), 2)+ db.join_channel_chat(channel, rpc::ConnectionId { owner_id, id: 1 }, user_b).await.unwrap();@@@ -149,11 -145,69 +149,69 @@@).await.unwrap()- .user_id;+ .message_id;- let channel_1 = db.create_root_channel("channel", user).await.unwrap();+ // As a different user, reuse one of the same nonces. This request succeeds+ // and returns a different id.+ let id5 = db+ .create_channel_message(+ channel,+ user_b,+ "omg @user_a (same nonce as user_a's first message)",+ &mentions_to_proto(&[(4..11, user_a.to_proto())]),+ OffsetDateTime::now_utc(),+ 100,+ )+ .await+ .unwrap()+ .message_id;++ assert_ne!(id1, id2);+ assert_eq!(id1, id3);+ assert_eq!(id2, id4);+ assert_ne!(id5, id1);++ let messages = db+ .get_channel_messages(channel, user_a, 5, None)+ .await+ .unwrap()+ .into_iter()+ .map(|m| (m.id, m.body, m.mentions))+ .collect::<Vec<_>>();+ assert_eq!(+ messages,+ &[+ (+ id1.to_proto(),+ "hi @user_b".into(),+ mentions_to_proto(&[(3..10, user_b.to_proto())]),+ ),+ (+ id2.to_proto(),+ "hello, fellow users".into(),+ mentions_to_proto(&[])+ ),+ (+ id5.to_proto(),+ "omg @user_a (same nonce as user_a's first message)".into(),+ mentions_to_proto(&[(4..11, user_a.to_proto())]),+ ),+ ]+ );+ }++ test_both_dbs!(+ test_unseen_channel_messages,+ test_unseen_channel_messages_postgres,+ test_unseen_channel_messages_sqlite+ );++ async fn test_unseen_channel_messages(db: &Arc<Database>) {+ let user = new_test_user(db, "[email protected]").await;+ let observer = new_test_user(db, "[email protected]").await;- let channel_1 = db.create_channel("channel", None, user).await.unwrap();- let channel_2 = db.create_channel("channel-2", None, user).await.unwrap();++ let channel_1 = db.create_root_channel("channel", user).await.unwrap();+ let channel_2 = db.create_root_channel("channel-2", user).await.unwrap();db.invite_channel_member(channel_1, observer, user, ChannelRole::Member).await@@@ -295,3 -350,96 +354,101 @@@}]);}++ test_both_dbs!(+ test_channel_message_mentions,+ test_channel_message_mentions_postgres,+ test_channel_message_mentions_sqlite+ );++ async fn test_channel_message_mentions(db: &Arc<Database>) {+ let user_a = new_test_user(db, "[email protected]").await;+ let user_b = new_test_user(db, "[email protected]").await;+ let user_c = new_test_user(db, "[email protected]").await;+- let channel = db.create_channel("channel", None, user_a).await.unwrap();++ let channel = db++ .create_channel("channel", None, user_a)++ .await++ .unwrap()++ .channel++ .id;+ db.invite_channel_member(channel, user_b, user_a, ChannelRole::Member)+ .await+ .unwrap();+ db.respond_to_channel_invite(channel, user_b, true)+ .await+ .unwrap();++ let owner_id = db.create_server("test").await.unwrap().0 as u32;+ let connection_id = rpc::ConnectionId { owner_id, id: 0 };+ db.join_channel_chat(channel, connection_id, user_a)+ .await+ .unwrap();++ db.create_channel_message(+ channel,+ user_a,+ "hi @user_b and @user_c",+ &mentions_to_proto(&[(3..10, user_b.to_proto()), (15..22, user_c.to_proto())]),+ OffsetDateTime::now_utc(),+ 1,+ )+ .await+ .unwrap();+ db.create_channel_message(+ channel,+ user_a,+ "bye @user_c",+ &mentions_to_proto(&[(4..11, user_c.to_proto())]),+ OffsetDateTime::now_utc(),+ 2,+ )+ .await+ .unwrap();+ db.create_channel_message(+ channel,+ user_a,+ "umm",+ &mentions_to_proto(&[]),+ OffsetDateTime::now_utc(),+ 3,+ )+ .await+ .unwrap();+ db.create_channel_message(+ channel,+ user_a,+ "@user_b, stop.",+ &mentions_to_proto(&[(0..7, user_b.to_proto())]),+ OffsetDateTime::now_utc(),+ 4,+ )+ .await+ .unwrap();++ let messages = db+ .get_channel_messages(channel, user_b, 5, None)+ .await+ .unwrap()+ .into_iter()+ .map(|m| (m.body, m.mentions))+ .collect::<Vec<_>>();+ assert_eq!(+ &messages,+ &[+ (+ "hi @user_b and @user_c".into(),+ mentions_to_proto(&[(3..10, user_b.to_proto()), (15..22, user_c.to_proto())]),+ ),+ (+ "bye @user_c".into(),+ mentions_to_proto(&[(4..11, user_c.to_proto())]),+ ),+ ("umm".into(), mentions_to_proto(&[]),),+ (+ "@user_b, stop.".into(),+ mentions_to_proto(&[(0..7, user_b.to_proto())]),+ ),+ ]+ );+ }diff --cc crates/collab/src/rpc.rsindex 9974ded821d,5a29861351d..2d89ec47a2e--- a/crates/collab/src/rpc.rs+++ b/crates/collab/src/rpc.rs@@@ -3,9 -3,8 +3,11 @@@ mod connection_pooluse crate::{auth,db::{- self, BufferId, ChannelId, ChannelRole, ChannelsForUser, CreateChannelResult, Database,- MembershipUpdated, MessageId, MoveChannelResult, ProjectId, RenameChannelResult, RoomId,- ServerId, SetChannelVisibilityResult, User, UserId,- self, BufferId, ChannelId, ChannelVisibility, ChannelsForUser, CreatedChannelMessage,- Database, MessageId, NotificationId, ProjectId, RoomId, ServerId, User, UserId,++ self, BufferId, ChannelId, ChannelRole, ChannelsForUser, CreateChannelResult,++ CreatedChannelMessage, Database, InviteMemberResult, MembershipUpdated, MessageId,++ MoveChannelResult, NotificationId, ProjectId, RemoveChannelMemberResult,++ RenameChannelResult, RespondToChannelInvite, RoomId, ServerId, SetChannelVisibilityResult,++ User, UserId,},executor::Executor,AppState, Result,@@@ -2268,7 -2297,7 +2285,10 @@@ async fn invite_channel_memberlet db = session.db().await;let channel_id = ChannelId::from_proto(request.channel_id);let invitee_id = UserId::from_proto(request.user_id);- let channel = db- let notifications = db++ let InviteMemberResult {++ channel,++ notifications,++ } = db.invite_channel_member(channel_id,invitee_id,@@@ -2277,19 -2306,22 +2297,18 @@@).await?;- let channel = db.get_channel(channel_id, session.user_id).await?;-- let mut update = proto::UpdateChannels::default();- update.channel_invitations.push(proto::Channel {- id: channel.id.to_proto(),- visibility: channel.visibility.into(),- name: channel.name,- });+ let update = proto::UpdateChannels {+ channel_invitations: vec![channel.to_proto()],+ ..Default::default()+ };- for connection_id in session- .connection_pool()- .await- .user_connection_ids(invitee_id)- {- let pool = session.connection_pool().await;- for connection_id in pool.user_connection_ids(invitee_id) {++ let connection_pool = session.connection_pool().await;++ for connection_id in connection_pool.user_connection_ids(invitee_id) {session.peer.send(connection_id, update.clone())?;}- send_notifications(&*pool, &session.peer, notifications);++ send_notifications(&*connection_pool, &session.peer, notifications);+response.send(proto::Ack {})?;Ok(())}@@@ -2303,13 -2335,31 +2322,33 @@@ async fn remove_channel_memberlet channel_id = ChannelId::from_proto(request.channel_id);let member_id = UserId::from_proto(request.user_id);- let membership_updated = db- let removed_notification_id = db++ let RemoveChannelMemberResult {++ membership_update,++ notification_id,++ } = db.remove_channel_member(channel_id, member_id, session.user_id).await?;- dbg!(&membership_updated);- let mut update = proto::UpdateChannels::default();- update.delete_channels.push(channel_id.to_proto());--- notify_membership_updated(membership_updated, member_id, &session).await?;- for connection_id in session- .connection_pool()- .await- .user_connection_ids(member_id)- {- session.peer.send(connection_id, update.clone()).trace_err();- if let Some(notification_id) = removed_notification_id {++ let connection_pool = &session.connection_pool().await;++ notify_membership_updated(++ &connection_pool,++ membership_update,++ member_id,++ &session.peer,++ );++ for connection_id in connection_pool.user_connection_ids(member_id) {++ if let Some(notification_id) = notification_id {+ session+ .peer+ .send(+ connection_id,+ proto::DeleteNotification {+ notification_id: notification_id.to_proto(),+ },+ )+ .trace_err();+ }+ }response.send(proto::Ack {})?;Ok(())@@@ -2372,24 -2415,22 +2411,30 @@@ async fn set_channel_member_role).await?;- let channel = db.get_channel(channel_id, session.user_id).await?;-- let mut update = proto::UpdateChannels::default();- if channel_member.accepted {- update.channel_permissions.push(proto::ChannelPermission {- channel_id: channel.id.to_proto(),- role: request.role,- });- }+ match result {+ db::SetMemberRoleResult::MembershipUpdated(membership_update) => {- notify_membership_updated(membership_update, member_id, &session).await?;++ let connection_pool = session.connection_pool().await;++ notify_membership_updated(++ &connection_pool,++ membership_update,++ member_id,++ &session.peer,++ )+ }+ db::SetMemberRoleResult::InviteUpdated(channel) => {+ let update = proto::UpdateChannels {+ channel_invitations: vec![channel.to_proto()],+ ..Default::default()+ };- for connection_id in session- .connection_pool()- .await- .user_connection_ids(member_id)- {- session.peer.send(connection_id, update.clone())?;+ for connection_id in session+ .connection_pool()+ .await+ .user_connection_ids(member_id)+ {+ session.peer.send(connection_id, update.clone())?;+ }+ }}response.send(proto::Ack {})?;@@@ -2535,26 -2620,78 +2580,36 @@@ async fn respond_to_channel_invite) -> Result<()> {let db = session.db().await;let channel_id = ChannelId::from_proto(request.channel_id);- let result = db- let notifications = db++ let RespondToChannelInvite {++ membership_update,++ notifications,++ } = db.respond_to_channel_invite(channel_id, session.user_id, request.accept).await?;- if let Some(accept_invite_result) = result {- notify_membership_updated(accept_invite_result, session.user_id, &session).await?;- if request.accept {- channel_membership_updated(db, channel_id, &session).await?;++ let connection_pool = session.connection_pool().await;++ if let Some(membership_update) = membership_update {++ notify_membership_updated(++ &connection_pool,++ membership_update,++ session.user_id,++ &session.peer,++ );} else {- let mut update = proto::UpdateChannels::default();- update- .remove_channel_invitations- .push(channel_id.to_proto());- session.peer.send(session.connection_id, update)?;- }+ let update = proto::UpdateChannels {+ remove_channel_invitations: vec![channel_id.to_proto()],+ ..Default::default()+ };- let connection_pool = session.connection_pool().await;- send_notifications(- &*session.connection_pool().await,- &session.peer,- notifications,- );- response.send(proto::Ack {})?;+ for connection_id in connection_pool.user_connection_ids(session.user_id) {+ session.peer.send(connection_id, update.clone())?;+ }+ };- Ok(())-}++ send_notifications(&*connection_pool, &session.peer, notifications);+++ response.send(proto::Ack {})?;-async fn channel_membership_updated(- db: tokio::sync::MutexGuard<'_, DbHandle>,- channel_id: ChannelId,- session: &Session,-) -> Result<(), crate::Error> {- let mut update = proto::UpdateChannels::default();- update- .remove_channel_invitations- .push(channel_id.to_proto());-- let result = db.get_channel_for_user(channel_id, session.user_id).await?;- update.channels.extend(- result- .channels- .channels- .into_iter()- .map(|channel| proto::Channel {- id: channel.id.to_proto(),- visibility: channel.visibility.into(),- name: channel.name,- }),- );- update.unseen_channel_messages = result.channel_messages;- update.unseen_channel_buffer_changes = result.unseen_buffer_changes;- update.insert_edge = result.channels.edges;- update- .channel_participants- .extend(- result- .channel_participants- .into_iter()- .map(|(channel_id, user_ids)| proto::ChannelParticipants {- channel_id: channel_id.to_proto(),- participant_user_ids: user_ids.into_iter().map(UserId::to_proto).collect(),- }),- );- update- .channel_permissions- .extend(- result- .channels_with_admin_privileges- .into_iter()- .map(|channel_id| proto::ChannelPermission {- channel_id: channel_id.to_proto(),- role: proto::ChannelRole::Admin.into(),- }),- );- session.peer.send(session.connection_id, update)?;Ok(())}@@@ -2635,8 -2756,8 +2690,14 @@@ async fn join_channel_internallive_kit_connection_info,})?;- if let Some(joined_channel) = joined_channel {- channel_membership_updated(db, joined_channel, &session).await?++ let connection_pool = session.connection_pool().await;+ if let Some(accept_invite_result) = accept_invite_result {- notify_membership_updated(accept_invite_result, session.user_id, &session).await?;++ notify_membership_updated(++ &connection_pool,++ accept_invite_result,++ session.user_id,++ &session.peer,++ );}room_updated(&joined_room.room, &session.peer);@@@ -3052,27 -3281,7 +3221,26 @@@ fn to_tungstenite_message(message: Axum}}- async fn notify_membership_updated(-fn build_initial_channels_update(++fn notify_membership_updated(++ connection_pool: &ConnectionPool,+ result: MembershipUpdated,+ user_id: UserId,- session: &Session,- ) -> Result<()> {++ peer: &Peer,++) {+ let mut update = build_channels_update(result.new_channels, vec![]);+ update.delete_channels = result+ .removed_channels+ .into_iter()+ .map(|id| id.to_proto())+ .collect();+ update.remove_channel_invitations = vec![result.channel_id.to_proto()];+- let connection_pool = session.connection_pool().await;+ for connection_id in connection_pool.user_connection_ids(user_id) {- session.peer.send(connection_id, update.clone())?;++ peer.send(connection_id, update.clone()).trace_err();+ }- Ok(())+}++fn build_channels_update(channels: ChannelsForUser,channel_invites: Vec<db::Channel>,) -> proto::UpdateChannels {diff --cc crates/collab/src/tests/channel_tests.rsindex 3df9597777d,54a958e71c6..63cc78b6518--- a/crates/collab/src/tests/channel_tests.rs+++ b/crates/collab/src/tests/channel_tests.rs@@@ -289,11 -287,11 +288,17 @@@ async fn test_core_channels// Client B no longer has access to the channelassert_channels(client_b.channel_store(), cx_b, &[]);-- // When disconnected, client A sees no channels.server.forbid_connections();server.disconnect_client(client_a.peer_id().unwrap());deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);-- assert_channels(client_a.channel_store(), cx_a, &[]);++++ client_b++ .channel_store()++ .update(cx_b, |channel_store, cx| {++ channel_store.rename(channel_a_id, "channel-a-renamed", cx)++ })++ .await++ .unwrap();server.allow_connections();deterministic.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);@@@ -302,9 -300,9 +307,9 @@@cx_a,&[ExpectedChannel {id: channel_a_id,-- name: "channel-a".to_string(),++ name: "channel-a-renamed".to_string(),depth: 0,- user_is_admin: true,+ role: ChannelRole::Admin,}],);}@@@ -914,320 -912,6 +919,320 @@@ async fn test_lost_channel_creation],);}++#[gpui::test]+async fn test_channel_link_notifications(+ deterministic: Arc<Deterministic>,+ cx_a: &mut TestAppContext,+ cx_b: &mut TestAppContext,+ cx_c: &mut TestAppContext,+) {+ deterministic.forbid_parking();++ let mut server = TestServer::start(&deterministic).await;+ let client_a = server.create_client(cx_a, "user_a").await;+ let client_b = server.create_client(cx_b, "user_b").await;+ let client_c = server.create_client(cx_c, "user_c").await;++ let user_b = client_b.user_id().unwrap();+ let user_c = client_c.user_id().unwrap();++ let channels = server+ .make_channel_tree(&[("zed", None)], (&client_a, cx_a))+ .await;+ let zed_channel = channels[0];++ try_join_all(client_a.channel_store().update(cx_a, |channel_store, cx| {+ [+ channel_store.set_channel_visibility(zed_channel, proto::ChannelVisibility::Public, cx),+ channel_store.invite_member(zed_channel, user_b, proto::ChannelRole::Member, cx),+ channel_store.invite_member(zed_channel, user_c, proto::ChannelRole::Guest, cx),+ ]+ }))+ .await+ .unwrap();++ deterministic.run_until_parked();++ client_b+ .channel_store()- .update(cx_b, |channel_store, _| {- channel_store.respond_to_channel_invite(zed_channel, true)++ .update(cx_b, |channel_store, cx| {++ channel_store.respond_to_channel_invite(zed_channel, true, cx)+ })+ .await+ .unwrap();++ client_c+ .channel_store()- .update(cx_c, |channel_store, _| {- channel_store.respond_to_channel_invite(zed_channel, true)++ .update(cx_c, |channel_store, cx| {++ channel_store.respond_to_channel_invite(zed_channel, true, cx)+ })+ .await+ .unwrap();++ deterministic.run_until_parked();++ // we have an admin (a), member (b) and guest (c) all part of the zed channel.++ // create a new private channel, make it public, and move it under the previous one, and verify it shows for b and not c+ let active_channel = client_a+ .channel_store()+ .update(cx_a, |channel_store, cx| {+ channel_store.create_channel("active", Some(zed_channel), cx)+ })+ .await+ .unwrap();++ // the new channel shows for b and not c+ assert_channels_list_shape(+ client_a.channel_store(),+ cx_a,+ &[(zed_channel, 0), (active_channel, 1)],+ );+ assert_channels_list_shape(+ client_b.channel_store(),+ cx_b,+ &[(zed_channel, 0), (active_channel, 1)],+ );+ assert_channels_list_shape(client_c.channel_store(), cx_c, &[(zed_channel, 0)]);++ let vim_channel = client_a+ .channel_store()+ .update(cx_a, |channel_store, cx| {+ channel_store.create_channel("vim", None, cx)+ })+ .await+ .unwrap();++ client_a+ .channel_store()+ .update(cx_a, |channel_store, cx| {+ channel_store.set_channel_visibility(vim_channel, proto::ChannelVisibility::Public, cx)+ })+ .await+ .unwrap();++ client_a+ .channel_store()+ .update(cx_a, |channel_store, cx| {+ channel_store.link_channel(vim_channel, active_channel, cx)+ })+ .await+ .unwrap();++ deterministic.run_until_parked();++ // the new channel shows for b and c+ assert_channels_list_shape(+ client_a.channel_store(),+ cx_a,+ &[(zed_channel, 0), (active_channel, 1), (vim_channel, 2)],+ );+ assert_channels_list_shape(+ client_b.channel_store(),+ cx_b,+ &[(zed_channel, 0), (active_channel, 1), (vim_channel, 2)],+ );+ assert_channels_list_shape(+ client_c.channel_store(),+ cx_c,+ &[(zed_channel, 0), (vim_channel, 1)],+ );++ let helix_channel = client_a+ .channel_store()+ .update(cx_a, |channel_store, cx| {+ channel_store.create_channel("helix", None, cx)+ })+ .await+ .unwrap();++ client_a+ .channel_store()+ .update(cx_a, |channel_store, cx| {+ channel_store.link_channel(helix_channel, vim_channel, cx)+ })+ .await+ .unwrap();++ client_a+ .channel_store()+ .update(cx_a, |channel_store, cx| {+ channel_store.set_channel_visibility(+ helix_channel,+ proto::ChannelVisibility::Public,+ cx,+ )+ })+ .await+ .unwrap();++ // the new channel shows for b and c+ assert_channels_list_shape(+ client_b.channel_store(),+ cx_b,+ &[+ (zed_channel, 0),+ (active_channel, 1),+ (vim_channel, 2),+ (helix_channel, 3),+ ],+ );+ assert_channels_list_shape(+ client_c.channel_store(),+ cx_c,+ &[(zed_channel, 0), (vim_channel, 1), (helix_channel, 2)],+ );++ client_a+ .channel_store()+ .update(cx_a, |channel_store, cx| {+ channel_store.set_channel_visibility(vim_channel, proto::ChannelVisibility::Members, cx)+ })+ .await+ .unwrap();++ // the members-only channel is still shown for c, but hidden for b+ assert_channels_list_shape(+ client_b.channel_store(),+ cx_b,+ &[+ (zed_channel, 0),+ (active_channel, 1),+ (vim_channel, 2),+ (helix_channel, 3),+ ],+ );+ client_b+ .channel_store()+ .read_with(cx_b, |channel_store, _| {+ assert_eq!(+ channel_store+ .channel_for_id(vim_channel)+ .unwrap()+ .visibility,+ proto::ChannelVisibility::Members+ )+ });++ assert_channels_list_shape(+ client_c.channel_store(),+ cx_c,+ &[(zed_channel, 0), (helix_channel, 1)],+ );+}++#[gpui::test]+async fn test_channel_membership_notifications(+ deterministic: Arc<Deterministic>,+ cx_a: &mut TestAppContext,+ cx_b: &mut TestAppContext,+) {+ deterministic.forbid_parking();++ deterministic.forbid_parking();++ let mut server = TestServer::start(&deterministic).await;+ let client_a = server.create_client(cx_a, "user_a").await;+ let client_b = server.create_client(cx_b, "user_c").await;++ let user_b = client_b.user_id().unwrap();++ let channels = server+ .make_channel_tree(+ &[+ ("zed", None),+ ("active", Some("zed")),+ ("vim", Some("active")),+ ],+ (&client_a, cx_a),+ )+ .await;+ let zed_channel = channels[0];+ let _active_channel = channels[1];+ let vim_channel = channels[2];++ try_join_all(client_a.channel_store().update(cx_a, |channel_store, cx| {+ [+ channel_store.set_channel_visibility(zed_channel, proto::ChannelVisibility::Public, cx),+ channel_store.set_channel_visibility(vim_channel, proto::ChannelVisibility::Public, cx),+ channel_store.invite_member(vim_channel, user_b, proto::ChannelRole::Member, cx),+ channel_store.invite_member(zed_channel, user_b, proto::ChannelRole::Guest, cx),+ ]+ }))+ .await+ .unwrap();++ deterministic.run_until_parked();++ client_b+ .channel_store()- .update(cx_b, |channel_store, _| {- channel_store.respond_to_channel_invite(zed_channel, true)++ .update(cx_b, |channel_store, cx| {++ channel_store.respond_to_channel_invite(zed_channel, true, cx)+ })+ .await+ .unwrap();++ client_b+ .channel_store()- .update(cx_b, |channel_store, _| {- channel_store.respond_to_channel_invite(vim_channel, true)++ .update(cx_b, |channel_store, cx| {++ channel_store.respond_to_channel_invite(vim_channel, true, cx)+ })+ .await+ .unwrap();++ deterministic.run_until_parked();++ // we have an admin (a), and a guest (b) with access to all of zed, and membership in vim.+ assert_channels(+ client_b.channel_store(),+ cx_b,+ &[+ ExpectedChannel {+ depth: 0,+ id: zed_channel,+ name: "zed".to_string(),+ role: ChannelRole::Guest,+ },+ ExpectedChannel {+ depth: 1,+ id: vim_channel,+ name: "vim".to_string(),+ role: ChannelRole::Member,+ },+ ],+ );++ client_a+ .channel_store()+ .update(cx_a, |channel_store, cx| {+ channel_store.remove_member(vim_channel, user_b, cx)+ })+ .await+ .unwrap();++ deterministic.run_until_parked();++ assert_channels(+ client_b.channel_store(),+ cx_b,+ &[+ ExpectedChannel {+ depth: 0,+ id: zed_channel,+ name: "zed".to_string(),+ role: ChannelRole::Guest,+ },+ ExpectedChannel {+ depth: 1,+ id: vim_channel,+ name: "vim".to_string(),+ role: ChannelRole::Guest,+ },+ ],+ )+}+#[gpui::test]async fn test_guest_access(deterministic: Arc<Deterministic>,diff --cc crates/collab_ui/src/chat_panel.rsindex 8f492e2e368,5b922037c51..5a4dafb6d41--- a/crates/collab_ui/src/chat_panel.rs+++ b/crates/collab_ui/src/chat_panel.rs@@@ -267,24 -263,21 +263,22 @@@ impl ChatPanelfn set_active_chat(&mut self, chat: ModelHandle<ChannelChat>, cx: &mut ViewContext<Self>) {if self.active_chat.as_ref().map(|e| &e.0) != Some(&chat) {- let id = chat.read(cx).channel_id;- self.markdown_data.clear();- let id = {++ let channel_id = chat.read(cx).channel_id;+ {++ self.markdown_data.clear();let chat = chat.read(cx);- let channel = chat.channel().clone();self.message_list.reset(chat.message_count());- let placeholder = if let Some(channel) = chat.channel(cx) {- format!("Message #{}", channel.name)- } else {- "Message Channel".to_string()- };- self.input_editor.update(cx, move |editor, cx| {- editor.set_placeholder_text(placeholder, cx);++++ let channel_name = chat.channel(cx).map(|channel| channel.name.clone());+ self.input_editor.update(cx, |editor, cx| {- editor.set_channel(channel.clone(), cx);++ editor.set_channel(channel_id, channel_name, cx);});- }- channel.id+ };let subscription = cx.subscribe(&chat, Self::channel_did_change);self.active_chat = Some((chat, subscription));self.acknowledge_last_message(cx);self.channel_select.update(cx, |select, cx| {-- if let Some(ix) = self.channel_store.read(cx).index_of_channel(id) {++ if let Some(ix) = self.channel_store.read(cx).index_of_channel(channel_id) {select.set_selected_index(ix, cx);}});@@@ -359,33 -352,47 +353,48 @@@}fn render_message(&mut self, ix: usize, cx: &mut ViewContext<Self>) -> AnyElement<Self> {- let (message, is_continuation, is_last, is_admin) = {- let active_chat = self.active_chat.as_ref().unwrap().0.read(cx);- let is_admin = self- .channel_store- .read(cx)- .is_channel_admin(active_chat.channel_id);- let last_message = active_chat.message(ix.saturating_sub(1));- let this_message = active_chat.message(ix);- let is_continuation = last_message.id != this_message.id- && this_message.sender.id == last_message.sender.id;-- (- active_chat.message(ix).clone(),- is_continuation,- active_chat.message_count() == ix + 1,- is_admin,- )- };+ let (message, is_continuation, is_last, is_admin) = self+ .active_chat+ .as_ref()+ .unwrap()+ .0+ .update(cx, |active_chat, cx| {+ let is_admin = self+ .channel_store+ .read(cx)- .is_user_admin(active_chat.channel().id);++ .is_channel_admin(active_chat.channel_id);+++ let last_message = active_chat.message(ix.saturating_sub(1));+ let this_message = active_chat.message(ix).clone();+ let is_continuation = last_message.id != this_message.id+ && this_message.sender.id == last_message.sender.id;++ if let ChannelMessageId::Saved(id) = this_message.id {+ if this_message+ .mentions+ .iter()+ .any(|(_, user_id)| Some(*user_id) == self.client.user_id())+ {+ active_chat.acknowledge_message(id);+ }+ }++ (+ this_message,+ is_continuation,+ active_chat.message_count() == ix + 1,+ is_admin,+ )+ });let is_pending = message.is_pending();- let text = self- .markdown_data- .entry(message.id)- .or_insert_with(|| rich_text::render_markdown(message.body, &self.languages, None));+ let theme = theme::current(cx);+ let text = self.markdown_data.entry(message.id).or_insert_with(|| {+ Self::render_markdown_with_mentions(&self.languages, self.client.id(), &message)+ });let now = OffsetDateTime::now_utc();- let theme = theme::current(cx);+let style = if is_pending {&theme.chat_panel.pending_message} else if is_continuation {@@@ -646,17 -669,22 +671,22 @@@pub fn select_channel(&mut self,selected_channel_id: u64,+ scroll_to_message_id: Option<u64>,cx: &mut ViewContext<ChatPanel>,) -> Task<Result<()>> {- if let Some((chat, _)) = &self.active_chat {- if chat.read(cx).channel_id == selected_channel_id {- return Task::ready(Ok(()));- }- }+ let open_chat = self+ .active_chat+ .as_ref()+ .and_then(|(chat, _)| {- (chat.read(cx).channel().id == selected_channel_id)++ (chat.read(cx).channel_id == selected_channel_id)+ .then(|| Task::ready(anyhow::Ok(chat.clone())))+ })+ .unwrap_or_else(|| {+ self.channel_store.update(cx, |store, cx| {+ store.open_channel_chat(selected_channel_id, cx)+ })+ });- let open_chat = self.channel_store.update(cx, |store, cx| {- store.open_channel_chat(selected_channel_id, cx)- });cx.spawn(|this, mut cx| async move {let chat = open_chat.await?;this.update(&mut cx, |this, cx| {diff --cc crates/collab_ui/src/chat_panel/message_editor.rsindex 00000000000,b72af36e632..6dbe3aa204emode 000000,100644..100644--- a/crates/collab_ui/src/chat_panel/message_editor.rs+++ b/crates/collab_ui/src/chat_panel/message_editor.rs@@@ -1,0 -1,304 +1,313 @@@-use channel::{Channel, ChannelMembership, ChannelStore, MessageParams};++use channel::{ChannelId, ChannelMembership, ChannelStore, MessageParams};+ use client::UserId;+ use collections::HashMap;+ use editor::{AnchorRangeExt, Editor};+ use gpui::{+ elements::ChildView, AnyElement, AsyncAppContext, Element, Entity, ModelHandle, Task, View,+ ViewContext, ViewHandle, WeakViewHandle,+ };+ use language::{language_settings::SoftWrap, Buffer, BufferSnapshot, LanguageRegistry};+ use lazy_static::lazy_static;+ use project::search::SearchQuery;+ use std::{sync::Arc, time::Duration};++ const MENTIONS_DEBOUNCE_INTERVAL: Duration = Duration::from_millis(50);++ lazy_static! {+ static ref MENTIONS_SEARCH: SearchQuery = SearchQuery::regex(+ "@[-_\\w]+",+ false,+ false,+ Default::default(),+ Default::default()+ )+ .unwrap();+ }++ pub struct MessageEditor {+ pub editor: ViewHandle<Editor>,+ channel_store: ModelHandle<ChannelStore>,+ users: HashMap<String, UserId>,+ mentions: Vec<UserId>,+ mentions_task: Option<Task<()>>,- channel: Option<Arc<Channel>>,++ channel_id: Option<ChannelId>,+ }++ impl MessageEditor {+ pub fn new(+ language_registry: Arc<LanguageRegistry>,+ channel_store: ModelHandle<ChannelStore>,+ editor: ViewHandle<Editor>,+ cx: &mut ViewContext<Self>,+ ) -> Self {+ editor.update(cx, |editor, cx| {+ editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);+ });++ let buffer = editor+ .read(cx)+ .buffer()+ .read(cx)+ .as_singleton()+ .expect("message editor must be singleton");++ cx.subscribe(&buffer, Self::on_buffer_event).detach();++ let markdown = language_registry.language_for_name("Markdown");+ cx.app_context()+ .spawn(|mut cx| async move {+ let markdown = markdown.await?;+ buffer.update(&mut cx, |buffer, cx| {+ buffer.set_language(Some(markdown), cx)+ });+ anyhow::Ok(())+ })+ .detach_and_log_err(cx);++ Self {+ editor,+ channel_store,+ users: HashMap::default(),- channel: None,++ channel_id: None,+ mentions: Vec::new(),+ mentions_task: None,+ }+ }+- pub fn set_channel(&mut self, channel: Arc<Channel>, cx: &mut ViewContext<Self>) {++ pub fn set_channel(++ &mut self,++ channel_id: u64,++ channel_name: Option<String>,++ cx: &mut ViewContext<Self>,++ ) {+ self.editor.update(cx, |editor, cx| {- editor.set_placeholder_text(format!("Message #{}", channel.name), cx);++ if let Some(channel_name) = channel_name {++ editor.set_placeholder_text(format!("Message #{}", channel_name), cx);++ } else {++ editor.set_placeholder_text(format!("Message Channel"), cx);++ }+ });- self.channel = Some(channel);++ self.channel_id = Some(channel_id);+ self.refresh_users(cx);+ }++ pub fn refresh_users(&mut self, cx: &mut ViewContext<Self>) {- if let Some(channel) = &self.channel {++ if let Some(channel_id) = self.channel_id {+ let members = self.channel_store.update(cx, |store, cx| {- store.get_channel_member_details(channel.id, cx)++ store.get_channel_member_details(channel_id, cx)+ });+ cx.spawn(|this, mut cx| async move {+ let members = members.await?;+ this.update(&mut cx, |this, cx| this.set_members(members, cx))?;+ anyhow::Ok(())+ })+ .detach_and_log_err(cx);+ }+ }++ pub fn set_members(&mut self, members: Vec<ChannelMembership>, _: &mut ViewContext<Self>) {+ self.users.clear();+ self.users.extend(+ members+ .into_iter()+ .map(|member| (member.user.github_login.clone(), member.user.id)),+ );+ }++ pub fn take_message(&mut self, cx: &mut ViewContext<Self>) -> MessageParams {+ self.editor.update(cx, |editor, cx| {+ let highlights = editor.text_highlights::<Self>(cx);+ let text = editor.text(cx);+ let snapshot = editor.buffer().read(cx).snapshot(cx);+ let mentions = if let Some((_, ranges)) = highlights {+ ranges+ .iter()+ .map(|range| range.to_offset(&snapshot))+ .zip(self.mentions.iter().copied())+ .collect()+ } else {+ Vec::new()+ };++ editor.clear(cx);+ self.mentions.clear();++ MessageParams { text, mentions }+ })+ }++ fn on_buffer_event(+ &mut self,+ buffer: ModelHandle<Buffer>,+ event: &language::Event,+ cx: &mut ViewContext<Self>,+ ) {+ if let language::Event::Reparsed | language::Event::Edited = event {+ let buffer = buffer.read(cx).snapshot();+ self.mentions_task = Some(cx.spawn(|this, cx| async move {+ cx.background().timer(MENTIONS_DEBOUNCE_INTERVAL).await;+ Self::find_mentions(this, buffer, cx).await;+ }));+ }+ }++ async fn find_mentions(+ this: WeakViewHandle<MessageEditor>,+ buffer: BufferSnapshot,+ mut cx: AsyncAppContext,+ ) {+ let (buffer, ranges) = cx+ .background()+ .spawn(async move {+ let ranges = MENTIONS_SEARCH.search(&buffer, None).await;+ (buffer, ranges)+ })+ .await;++ this.update(&mut cx, |this, cx| {+ let mut anchor_ranges = Vec::new();+ let mut mentioned_user_ids = Vec::new();+ let mut text = String::new();++ this.editor.update(cx, |editor, cx| {+ let multi_buffer = editor.buffer().read(cx).snapshot(cx);+ for range in ranges {+ text.clear();+ text.extend(buffer.text_for_range(range.clone()));+ if let Some(username) = text.strip_prefix("@") {+ if let Some(user_id) = this.users.get(username) {+ let start = multi_buffer.anchor_after(range.start);+ let end = multi_buffer.anchor_after(range.end);++ mentioned_user_ids.push(*user_id);+ anchor_ranges.push(start..end);+ }+ }+ }++ editor.clear_highlights::<Self>(cx);+ editor.highlight_text::<Self>(+ anchor_ranges,+ theme::current(cx).chat_panel.rich_text.mention_highlight,+ cx,+ )+ });++ this.mentions = mentioned_user_ids;+ this.mentions_task.take();+ })+ .ok();+ }+ }++ impl Entity for MessageEditor {+ type Event = ();+ }++ impl View for MessageEditor {+ fn render(&mut self, cx: &mut ViewContext<'_, '_, Self>) -> AnyElement<Self> {+ ChildView::new(&self.editor, cx).into_any()+ }++ fn focus_in(&mut self, _: gpui::AnyViewHandle, cx: &mut ViewContext<Self>) {+ if cx.is_self_focused() {+ cx.focus(&self.editor);+ }+ }+ }++ #[cfg(test)]+ mod tests {+ use super::*;+ use client::{Client, User, UserStore};+ use gpui::{TestAppContext, WindowHandle};+ use language::{Language, LanguageConfig};+ use rpc::proto;+ use settings::SettingsStore;+ use util::{http::FakeHttpClient, test::marked_text_ranges};++ #[gpui::test]+ async fn test_message_editor(cx: &mut TestAppContext) {+ let editor = init_test(cx);+ let editor = editor.root(cx);++ editor.update(cx, |editor, cx| {+ editor.set_members(+ vec![+ ChannelMembership {+ user: Arc::new(User {+ github_login: "a-b".into(),+ id: 101,+ avatar: None,+ }),+ kind: proto::channel_member::Kind::Member,+ role: proto::ChannelRole::Member,+ },+ ChannelMembership {+ user: Arc::new(User {+ github_login: "C_D".into(),+ id: 102,+ avatar: None,+ }),+ kind: proto::channel_member::Kind::Member,+ role: proto::ChannelRole::Member,+ },+ ],+ cx,+ );++ editor.editor.update(cx, |editor, cx| {+ editor.set_text("Hello, @a-b! Have you met @C_D?", cx)+ });+ });++ cx.foreground().advance_clock(MENTIONS_DEBOUNCE_INTERVAL);++ editor.update(cx, |editor, cx| {+ let (text, ranges) = marked_text_ranges("Hello, «@a-b»! Have you met «@C_D»?", false);+ assert_eq!(+ editor.take_message(cx),+ MessageParams {+ text,+ mentions: vec![(ranges[0].clone(), 101), (ranges[1].clone(), 102)],+ }+ );+ });+ }++ fn init_test(cx: &mut TestAppContext) -> WindowHandle<MessageEditor> {+ cx.foreground().forbid_parking();++ cx.update(|cx| {+ let http = FakeHttpClient::with_404_response();+ let client = Client::new(http.clone(), cx);+ let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http, cx));+ cx.set_global(SettingsStore::test(cx));+ theme::init((), cx);+ language::init(cx);+ editor::init(cx);+ client::init(&client, cx);+ channel::init(&client, user_store, cx);+ });++ let language_registry = Arc::new(LanguageRegistry::test());+ language_registry.add(Arc::new(Language::new(+ LanguageConfig {+ name: "Markdown".into(),+ ..Default::default()+ },+ Some(tree_sitter_markdown::language()),+ )));++ let editor = cx.add_window(|cx| {+ MessageEditor::new(+ language_registry,+ ChannelStore::global(cx),+ cx.add_view(|cx| Editor::auto_height(4, None, cx)),+ cx,+ )+ });+ cx.foreground().run_until_parked();+ editor+ }+ }diff --cc crates/collab_ui/src/notification_panel.rsindex 00000000000,e245a919f3a..1720c8dcdc8mode 000000,100644..100644--- a/crates/collab_ui/src/notification_panel.rs+++ b/crates/collab_ui/src/notification_panel.rs@@@ -1,0 -1,884 +1,884 @@@+ use crate::{chat_panel::ChatPanel, render_avatar, NotificationPanelSettings};+ use anyhow::Result;+ use channel::ChannelStore;+ use client::{Client, Notification, User, UserStore};+ use collections::HashMap;+ use db::kvp::KEY_VALUE_STORE;+ use futures::StreamExt;+ use gpui::{+ actions,+ elements::*,+ platform::{CursorStyle, MouseButton},+ serde_json, AnyViewHandle, AppContext, AsyncAppContext, Entity, ModelHandle, Task, View,+ ViewContext, ViewHandle, WeakViewHandle, WindowContext,+ };+ use notifications::{NotificationEntry, NotificationEvent, NotificationStore};+ use project::Fs;+ use rpc::proto;+ use serde::{Deserialize, Serialize};+ use settings::SettingsStore;+ use std::{sync::Arc, time::Duration};+ use theme::{ui, Theme};+ use time::{OffsetDateTime, UtcOffset};+ use util::{ResultExt, TryFutureExt};+ use workspace::{+ dock::{DockPosition, Panel},+ Workspace,+ };++ const LOADING_THRESHOLD: usize = 30;+ const MARK_AS_READ_DELAY: Duration = Duration::from_secs(1);+ const TOAST_DURATION: Duration = Duration::from_secs(5);+ const NOTIFICATION_PANEL_KEY: &'static str = "NotificationPanel";++ pub struct NotificationPanel {+ client: Arc<Client>,+ user_store: ModelHandle<UserStore>,+ channel_store: ModelHandle<ChannelStore>,+ notification_store: ModelHandle<NotificationStore>,+ fs: Arc<dyn Fs>,+ width: Option<f32>,+ active: bool,+ notification_list: ListState<Self>,+ pending_serialization: Task<Option<()>>,+ subscriptions: Vec<gpui::Subscription>,+ workspace: WeakViewHandle<Workspace>,+ current_notification_toast: Option<(u64, Task<()>)>,+ local_timezone: UtcOffset,+ has_focus: bool,+ mark_as_read_tasks: HashMap<u64, Task<Result<()>>>,+ }++ #[derive(Serialize, Deserialize)]+ struct SerializedNotificationPanel {+ width: Option<f32>,+ }++ #[derive(Debug)]+ pub enum Event {+ DockPositionChanged,+ Focus,+ Dismissed,+ }++ pub struct NotificationPresenter {+ pub actor: Option<Arc<client::User>>,+ pub text: String,+ pub icon: &'static str,+ pub needs_response: bool,+ pub can_navigate: bool,+ }++ actions!(notification_panel, [ToggleFocus]);++ pub fn init(_cx: &mut AppContext) {}++ impl NotificationPanel {+ pub fn new(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) -> ViewHandle<Self> {+ let fs = workspace.app_state().fs.clone();+ let client = workspace.app_state().client.clone();+ let user_store = workspace.app_state().user_store.clone();+ let workspace_handle = workspace.weak_handle();++ cx.add_view(|cx| {+ let mut status = client.status();+ cx.spawn(|this, mut cx| async move {+ while let Some(_) = status.next().await {+ if this+ .update(&mut cx, |_, cx| {+ cx.notify();+ })+ .is_err()+ {+ break;+ }+ }+ })+ .detach();++ let mut notification_list =+ ListState::<Self>::new(0, Orientation::Top, 1000., move |this, ix, cx| {+ this.render_notification(ix, cx)+ .unwrap_or_else(|| Empty::new().into_any())+ });+ notification_list.set_scroll_handler(|visible_range, count, this, cx| {+ if count.saturating_sub(visible_range.end) < LOADING_THRESHOLD {+ if let Some(task) = this+ .notification_store+ .update(cx, |store, cx| store.load_more_notifications(false, cx))+ {+ task.detach();+ }+ }+ });++ let mut this = Self {+ fs,+ client,+ user_store,+ local_timezone: cx.platform().local_timezone(),+ channel_store: ChannelStore::global(cx),+ notification_store: NotificationStore::global(cx),+ notification_list,+ pending_serialization: Task::ready(None),+ workspace: workspace_handle,+ has_focus: false,+ current_notification_toast: None,+ subscriptions: Vec::new(),+ active: false,+ mark_as_read_tasks: HashMap::default(),+ width: None,+ };++ let mut old_dock_position = this.position(cx);+ this.subscriptions.extend([+ cx.observe(&this.notification_store, |_, _, cx| cx.notify()),+ cx.subscribe(&this.notification_store, Self::on_notification_event),+ cx.observe_global::<SettingsStore, _>(move |this: &mut Self, cx| {+ let new_dock_position = this.position(cx);+ if new_dock_position != old_dock_position {+ old_dock_position = new_dock_position;+ cx.emit(Event::DockPositionChanged);+ }+ cx.notify();+ }),+ ]);+ this+ })+ }++ pub fn load(+ workspace: WeakViewHandle<Workspace>,+ cx: AsyncAppContext,+ ) -> Task<Result<ViewHandle<Self>>> {+ cx.spawn(|mut cx| async move {+ let serialized_panel = if let Some(panel) = cx+ .background()+ .spawn(async move { KEY_VALUE_STORE.read_kvp(NOTIFICATION_PANEL_KEY) })+ .await+ .log_err()+ .flatten()+ {+ Some(serde_json::from_str::<SerializedNotificationPanel>(&panel)?)+ } else {+ None+ };++ workspace.update(&mut cx, |workspace, cx| {+ let panel = Self::new(workspace, cx);+ if let Some(serialized_panel) = serialized_panel {+ panel.update(cx, |panel, cx| {+ panel.width = serialized_panel.width;+ cx.notify();+ });+ }+ panel+ })+ })+ }++ fn serialize(&mut self, cx: &mut ViewContext<Self>) {+ let width = self.width;+ self.pending_serialization = cx.background().spawn(+ async move {+ KEY_VALUE_STORE+ .write_kvp(+ NOTIFICATION_PANEL_KEY.into(),+ serde_json::to_string(&SerializedNotificationPanel { width })?,+ )+ .await?;+ anyhow::Ok(())+ }+ .log_err(),+ );+ }++ fn render_notification(+ &mut self,+ ix: usize,+ cx: &mut ViewContext<Self>,+ ) -> Option<AnyElement<Self>> {+ let entry = self.notification_store.read(cx).notification_at(ix)?;+ let notification_id = entry.id;+ let now = OffsetDateTime::now_utc();+ let timestamp = entry.timestamp;+ let NotificationPresenter {+ actor,+ text,+ needs_response,+ can_navigate,+ ..+ } = self.present_notification(entry, cx)?;++ let theme = theme::current(cx);+ let style = &theme.notification_panel;+ let response = entry.response;+ let notification = entry.notification.clone();++ let message_style = if entry.is_read {+ style.read_text.clone()+ } else {+ style.unread_text.clone()+ };++ if self.active && !entry.is_read {+ self.did_render_notification(notification_id, ¬ification, cx);+ }++ enum Decline {}+ enum Accept {}++ Some(+ MouseEventHandler::new::<NotificationEntry, _>(ix, cx, |_, cx| {+ let container = message_style.container;++ Flex::row()+ .with_children(actor.map(|actor| {+ render_avatar(actor.avatar.clone(), &style.avatar, style.avatar_container)+ }))+ .with_child(+ Flex::column()+ .with_child(Text::new(text, message_style.text.clone()))+ .with_child(+ Flex::row()+ .with_child(+ Label::new(+ format_timestamp(timestamp, now, self.local_timezone),+ style.timestamp.text.clone(),+ )+ .contained()+ .with_style(style.timestamp.container),+ )+ .with_children(if let Some(is_accepted) = response {+ Some(+ Label::new(+ if is_accepted {+ "You accepted"+ } else {+ "You declined"+ },+ style.read_text.text.clone(),+ )+ .flex_float()+ .into_any(),+ )+ } else if needs_response {+ Some(+ Flex::row()+ .with_children([+ MouseEventHandler::new::<Decline, _>(+ ix,+ cx,+ |state, _| {+ let button =+ style.button.style_for(state);+ Label::new(+ "Decline",+ button.text.clone(),+ )+ .contained()+ .with_style(button.container)+ },+ )+ .with_cursor_style(CursorStyle::PointingHand)+ .on_click(MouseButton::Left, {+ let notification = notification.clone();+ move |_, view, cx| {+ view.respond_to_notification(+ notification.clone(),+ false,+ cx,+ );+ }+ }),+ MouseEventHandler::new::<Accept, _>(+ ix,+ cx,+ |state, _| {+ let button =+ style.button.style_for(state);+ Label::new(+ "Accept",+ button.text.clone(),+ )+ .contained()+ .with_style(button.container)+ },+ )+ .with_cursor_style(CursorStyle::PointingHand)+ .on_click(MouseButton::Left, {+ let notification = notification.clone();+ move |_, view, cx| {+ view.respond_to_notification(+ notification.clone(),+ true,+ cx,+ );+ }+ }),+ ])+ .flex_float()+ .into_any(),+ )+ } else {+ None+ }),+ )+ .flex(1.0, true),+ )+ .contained()+ .with_style(container)+ .into_any()+ })+ .with_cursor_style(if can_navigate {+ CursorStyle::PointingHand+ } else {+ CursorStyle::default()+ })+ .on_click(MouseButton::Left, {+ let notification = notification.clone();+ move |_, this, cx| this.did_click_notification(¬ification, cx)+ })+ .into_any(),+ )+ }++ fn present_notification(+ &self,+ entry: &NotificationEntry,+ cx: &AppContext,+ ) -> Option<NotificationPresenter> {+ let user_store = self.user_store.read(cx);+ let channel_store = self.channel_store.read(cx);+ match entry.notification {+ Notification::ContactRequest { sender_id } => {+ let requester = user_store.get_cached_user(sender_id)?;+ Some(NotificationPresenter {+ icon: "icons/plus.svg",+ text: format!("{} wants to add you as a contact", requester.github_login),+ needs_response: user_store.has_incoming_contact_request(requester.id),+ actor: Some(requester),+ can_navigate: false,+ })+ }+ Notification::ContactRequestAccepted { responder_id } => {+ let responder = user_store.get_cached_user(responder_id)?;+ Some(NotificationPresenter {+ icon: "icons/plus.svg",+ text: format!("{} accepted your contact invite", responder.github_login),+ needs_response: false,+ actor: Some(responder),+ can_navigate: false,+ })+ }+ Notification::ChannelInvitation {+ ref channel_name,+ channel_id,+ inviter_id,+ } => {+ let inviter = user_store.get_cached_user(inviter_id)?;+ Some(NotificationPresenter {+ icon: "icons/hash.svg",+ text: format!(+ "{} invited you to join the #{channel_name} channel",+ inviter.github_login+ ),+ needs_response: channel_store.has_channel_invitation(channel_id),+ actor: Some(inviter),+ can_navigate: false,+ })+ }+ Notification::ChannelMessageMention {+ sender_id,+ channel_id,+ message_id,+ } => {+ let sender = user_store.get_cached_user(sender_id)?;+ let channel = channel_store.channel_for_id(channel_id)?;+ let message = self+ .notification_store+ .read(cx)+ .channel_message_for_id(message_id)?;+ Some(NotificationPresenter {+ icon: "icons/conversations.svg",+ text: format!(+ "{} mentioned you in #{}:\n{}",+ sender.github_login, channel.name, message.body,+ ),+ needs_response: false,+ actor: Some(sender),+ can_navigate: true,+ })+ }+ }+ }++ fn did_render_notification(+ &mut self,+ notification_id: u64,+ notification: &Notification,+ cx: &mut ViewContext<Self>,+ ) {+ let should_mark_as_read = match notification {+ Notification::ContactRequestAccepted { .. } => true,+ Notification::ContactRequest { .. }+ | Notification::ChannelInvitation { .. }+ | Notification::ChannelMessageMention { .. } => false,+ };++ if should_mark_as_read {+ self.mark_as_read_tasks+ .entry(notification_id)+ .or_insert_with(|| {+ let client = self.client.clone();+ cx.spawn(|this, mut cx| async move {+ cx.background().timer(MARK_AS_READ_DELAY).await;+ client+ .request(proto::MarkNotificationRead { notification_id })+ .await?;+ this.update(&mut cx, |this, _| {+ this.mark_as_read_tasks.remove(¬ification_id);+ })?;+ Ok(())+ })+ });+ }+ }++ fn did_click_notification(&mut self, notification: &Notification, cx: &mut ViewContext<Self>) {+ if let Notification::ChannelMessageMention {+ message_id,+ channel_id,+ ..+ } = notification.clone()+ {+ if let Some(workspace) = self.workspace.upgrade(cx) {+ cx.app_context().defer(move |cx| {+ workspace.update(cx, |workspace, cx| {+ if let Some(panel) = workspace.focus_panel::<ChatPanel>(cx) {+ panel.update(cx, |panel, cx| {+ panel+ .select_channel(channel_id, Some(message_id), cx)+ .detach_and_log_err(cx);+ });+ }+ });+ });+ }+ }+ }++ fn is_showing_notification(&self, notification: &Notification, cx: &AppContext) -> bool {+ if let Notification::ChannelMessageMention { channel_id, .. } = ¬ification {+ if let Some(workspace) = self.workspace.upgrade(cx) {+ return workspace+ .read_with(cx, |workspace, cx| {+ if let Some(panel) = workspace.panel::<ChatPanel>(cx) {+ return panel.read_with(cx, |panel, cx| {+ panel.is_scrolled_to_bottom()+ && panel.active_chat().map_or(false, |chat| {- chat.read(cx).channel().id == *channel_id++ chat.read(cx).channel_id == *channel_id+ })+ });+ }+ false+ })+ .unwrap_or_default();+ }+ }++ false+ }++ fn render_sign_in_prompt(+ &self,+ theme: &Arc<Theme>,+ cx: &mut ViewContext<Self>,+ ) -> AnyElement<Self> {+ enum SignInPromptLabel {}++ MouseEventHandler::new::<SignInPromptLabel, _>(0, cx, |mouse_state, _| {+ Label::new(+ "Sign in to view your notifications".to_string(),+ theme+ .chat_panel+ .sign_in_prompt+ .style_for(mouse_state)+ .clone(),+ )+ })+ .with_cursor_style(CursorStyle::PointingHand)+ .on_click(MouseButton::Left, move |_, this, cx| {+ let client = this.client.clone();+ cx.spawn(|_, cx| async move {+ client.authenticate_and_connect(true, &cx).log_err().await;+ })+ .detach();+ })+ .aligned()+ .into_any()+ }++ fn render_empty_state(+ &self,+ theme: &Arc<Theme>,+ _cx: &mut ViewContext<Self>,+ ) -> AnyElement<Self> {+ Label::new(+ "You have no notifications".to_string(),+ theme.chat_panel.sign_in_prompt.default.clone(),+ )+ .aligned()+ .into_any()+ }++ fn on_notification_event(+ &mut self,+ _: ModelHandle<NotificationStore>,+ event: &NotificationEvent,+ cx: &mut ViewContext<Self>,+ ) {+ match event {+ NotificationEvent::NewNotification { entry } => self.add_toast(entry, cx),+ NotificationEvent::NotificationRemoved { entry }+ | NotificationEvent::NotificationRead { entry } => self.remove_toast(entry.id, cx),+ NotificationEvent::NotificationsUpdated {+ old_range,+ new_count,+ } => {+ self.notification_list.splice(old_range.clone(), *new_count);+ cx.notify();+ }+ }+ }++ fn add_toast(&mut self, entry: &NotificationEntry, cx: &mut ViewContext<Self>) {+ if self.is_showing_notification(&entry.notification, cx) {+ return;+ }++ let Some(NotificationPresenter { actor, text, .. }) = self.present_notification(entry, cx)+ else {+ return;+ };++ let notification_id = entry.id;+ self.current_notification_toast = Some((+ notification_id,+ cx.spawn(|this, mut cx| async move {+ cx.background().timer(TOAST_DURATION).await;+ this.update(&mut cx, |this, cx| this.remove_toast(notification_id, cx))+ .ok();+ }),+ ));++ self.workspace+ .update(cx, |workspace, cx| {+ workspace.dismiss_notification::<NotificationToast>(0, cx);+ workspace.show_notification(0, cx, |cx| {+ let workspace = cx.weak_handle();+ cx.add_view(|_| NotificationToast {+ notification_id,+ actor,+ text,+ workspace,+ })+ })+ })+ .ok();+ }++ fn remove_toast(&mut self, notification_id: u64, cx: &mut ViewContext<Self>) {+ if let Some((current_id, _)) = &self.current_notification_toast {+ if *current_id == notification_id {+ self.current_notification_toast.take();+ self.workspace+ .update(cx, |workspace, cx| {+ workspace.dismiss_notification::<NotificationToast>(0, cx)+ })+ .ok();+ }+ }+ }++ fn respond_to_notification(+ &mut self,+ notification: Notification,+ response: bool,+ cx: &mut ViewContext<Self>,+ ) {+ self.notification_store.update(cx, |store, cx| {+ store.respond_to_notification(notification, response, cx);+ });+ }+ }++ impl Entity for NotificationPanel {+ type Event = Event;+ }++ impl View for NotificationPanel {+ fn ui_name() -> &'static str {+ "NotificationPanel"+ }++ fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {+ let theme = theme::current(cx);+ let style = &theme.notification_panel;+ let element = if self.client.user_id().is_none() {+ self.render_sign_in_prompt(&theme, cx)+ } else if self.notification_list.item_count() == 0 {+ self.render_empty_state(&theme, cx)+ } else {+ Flex::column()+ .with_child(+ Flex::row()+ .with_child(Label::new("Notifications", style.title.text.clone()))+ .with_child(ui::svg(&style.title_icon).flex_float())+ .align_children_center()+ .contained()+ .with_style(style.title.container)+ .constrained()+ .with_height(style.title_height),+ )+ .with_child(+ List::new(self.notification_list.clone())+ .contained()+ .with_style(style.list)+ .flex(1., true),+ )+ .into_any()+ };+ element+ .contained()+ .with_style(style.container)+ .constrained()+ .with_min_width(150.)+ .into_any()+ }++ fn focus_in(&mut self, _: AnyViewHandle, _: &mut ViewContext<Self>) {+ self.has_focus = true;+ }++ fn focus_out(&mut self, _: AnyViewHandle, _: &mut ViewContext<Self>) {+ self.has_focus = false;+ }+ }++ impl Panel for NotificationPanel {+ fn position(&self, cx: &gpui::WindowContext) -> DockPosition {+ settings::get::<NotificationPanelSettings>(cx).dock+ }++ fn position_is_valid(&self, position: DockPosition) -> bool {+ matches!(position, DockPosition::Left | DockPosition::Right)+ }++ fn set_position(&mut self, position: DockPosition, cx: &mut ViewContext<Self>) {+ settings::update_settings_file::<NotificationPanelSettings>(+ self.fs.clone(),+ cx,+ move |settings| settings.dock = Some(position),+ );+ }++ fn size(&self, cx: &gpui::WindowContext) -> f32 {+ self.width+ .unwrap_or_else(|| settings::get::<NotificationPanelSettings>(cx).default_width)+ }++ fn set_size(&mut self, size: Option<f32>, cx: &mut ViewContext<Self>) {+ self.width = size;+ self.serialize(cx);+ cx.notify();+ }++ fn set_active(&mut self, active: bool, cx: &mut ViewContext<Self>) {+ self.active = active;+ if self.notification_store.read(cx).notification_count() == 0 {+ cx.emit(Event::Dismissed);+ }+ }++ fn icon_path(&self, cx: &gpui::WindowContext) -> Option<&'static str> {+ (settings::get::<NotificationPanelSettings>(cx).button+ && self.notification_store.read(cx).notification_count() > 0)+ .then(|| "icons/bell.svg")+ }++ fn icon_tooltip(&self) -> (String, Option<Box<dyn gpui::Action>>) {+ (+ "Notification Panel".to_string(),+ Some(Box::new(ToggleFocus)),+ )+ }++ fn icon_label(&self, cx: &WindowContext) -> Option<String> {+ let count = self.notification_store.read(cx).unread_notification_count();+ if count == 0 {+ None+ } else {+ Some(count.to_string())+ }+ }++ fn should_change_position_on_event(event: &Self::Event) -> bool {+ matches!(event, Event::DockPositionChanged)+ }++ fn should_close_on_event(event: &Self::Event) -> bool {+ matches!(event, Event::Dismissed)+ }++ fn has_focus(&self, _cx: &gpui::WindowContext) -> bool {+ self.has_focus+ }++ fn is_focus_event(event: &Self::Event) -> bool {+ matches!(event, Event::Focus)+ }+ }++ pub struct NotificationToast {+ notification_id: u64,+ actor: Option<Arc<User>>,+ text: String,+ workspace: WeakViewHandle<Workspace>,+ }++ pub enum ToastEvent {+ Dismiss,+ }++ impl NotificationToast {+ fn focus_notification_panel(&self, cx: &mut AppContext) {+ let workspace = self.workspace.clone();+ let notification_id = self.notification_id;+ cx.defer(move |cx| {+ workspace+ .update(cx, |workspace, cx| {+ if let Some(panel) = workspace.focus_panel::<NotificationPanel>(cx) {+ panel.update(cx, |panel, cx| {+ let store = panel.notification_store.read(cx);+ if let Some(entry) = store.notification_for_id(notification_id) {+ panel.did_click_notification(&entry.clone().notification, cx);+ }+ });+ }+ })+ .ok();+ })+ }+ }++ impl Entity for NotificationToast {+ type Event = ToastEvent;+ }++ impl View for NotificationToast {+ fn ui_name() -> &'static str {+ "ContactNotification"+ }++ fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {+ let user = self.actor.clone();+ let theme = theme::current(cx).clone();+ let theme = &theme.contact_notification;++ MouseEventHandler::new::<Self, _>(0, cx, |_, cx| {+ Flex::row()+ .with_children(user.and_then(|user| {+ Some(+ Image::from_data(user.avatar.clone()?)+ .with_style(theme.header_avatar)+ .aligned()+ .constrained()+ .with_height(+ cx.font_cache()+ .line_height(theme.header_message.text.font_size),+ )+ .aligned()+ .top(),+ )+ }))+ .with_child(+ Text::new(self.text.clone(), theme.header_message.text.clone())+ .contained()+ .with_style(theme.header_message.container)+ .aligned()+ .top()+ .left()+ .flex(1., true),+ )+ .with_child(+ MouseEventHandler::new::<ToastEvent, _>(0, cx, |state, _| {+ let style = theme.dismiss_button.style_for(state);+ Svg::new("icons/x.svg")+ .with_color(style.color)+ .constrained()+ .with_width(style.icon_width)+ .aligned()+ .contained()+ .with_style(style.container)+ .constrained()+ .with_width(style.button_width)+ .with_height(style.button_width)+ })+ .with_cursor_style(CursorStyle::PointingHand)+ .with_padding(Padding::uniform(5.))+ .on_click(MouseButton::Left, move |_, _, cx| {+ cx.emit(ToastEvent::Dismiss)+ })+ .aligned()+ .constrained()+ .with_height(+ cx.font_cache()+ .line_height(theme.header_message.text.font_size),+ )+ .aligned()+ .top()+ .flex_float(),+ )+ .contained()+ })+ .with_cursor_style(CursorStyle::PointingHand)+ .on_click(MouseButton::Left, move |_, this, cx| {+ this.focus_notification_panel(cx);+ cx.emit(ToastEvent::Dismiss);+ })+ .into_any()+ }+ }++ impl workspace::notifications::Notification for NotificationToast {+ fn should_dismiss_notification_on_event(&self, event: &<Self as Entity>::Event) -> bool {+ matches!(event, ToastEvent::Dismiss)+ }+ }++ fn format_timestamp(+ mut timestamp: OffsetDateTime,+ mut now: OffsetDateTime,+ local_timezone: UtcOffset,+ ) -> String {+ timestamp = timestamp.to_offset(local_timezone);+ now = now.to_offset(local_timezone);++ let today = now.date();+ let date = timestamp.date();+ if date == today {+ let difference = now - timestamp;+ if difference >= Duration::from_secs(3600) {+ format!("{}h", difference.whole_seconds() / 3600)+ } else if difference >= Duration::from_secs(60) {+ format!("{}m", difference.whole_seconds() / 60)+ } else {+ "just now".to_string()+ }+ } else if date.next_day() == Some(today) {+ format!("yesterday")+ } else {+ format!("{:02}/{}/{}", date.month() as u32, date.day(), date.year())+ }+ }