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 notifications
Max Brunsfeldb07f9fe3b565
diff --cc crates/collab/migrations.sqlite/20221109000000_test_schema.sqlindex c835fff60df,8eb6b52fd8b..fb2f276b8b1--- a/crates/collab/migrations.sqlite/20221109000000_test_schema.sql+++ b/crates/collab/migrations.sqlite/20221109000000_test_schema.sql@@@ -192,7 -192,8 +192,8 @@@ CREATE INDEX "index_followers_on_room_iCREATE TABLE "channels" ("id" INTEGER PRIMARY KEY AUTOINCREMENT,"name" VARCHAR NOT NULL,- "created_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP- "created_at" TIMESTAMP NOT NULL DEFAULT now,++ "created_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "visibility" VARCHAR NOT NULL);CREATE TABLE IF NOT EXISTS "channel_chat_participants" (diff --cc crates/collab/src/db/ids.rsindex bd07af8a35c,f0de4c255ed..433444de67e--- a/crates/collab/src/db/ids.rs+++ b/crates/collab/src/db/ids.rs@@@ -80,5 -81,101 +81,103 @@@ 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)]+ #[sea_orm(rs_type = "String", db_type = "String(None)")]+ pub enum ChannelRole {+ #[sea_orm(string_value = "admin")]+ Admin,+ #[sea_orm(string_value = "member")]+ #[default]+ Member,+ #[sea_orm(string_value = "guest")]+ Guest,+ #[sea_orm(string_value = "banned")]+ Banned,+ }++ impl ChannelRole {+ pub fn should_override(&self, other: Self) -> bool {+ use ChannelRole::*;+ match self {+ Admin => matches!(other, Member | Banned | Guest),+ Member => matches!(other, Banned | Guest),+ Banned => matches!(other, Guest),+ Guest => false,+ }+ }++ pub fn max(&self, other: Self) -> Self {+ if self.should_override(other) {+ *self+ } else {+ other+ }+ }+ }++ impl From<proto::ChannelRole> for ChannelRole {+ fn from(value: proto::ChannelRole) -> Self {+ match value {+ proto::ChannelRole::Admin => ChannelRole::Admin,+ proto::ChannelRole::Member => ChannelRole::Member,+ proto::ChannelRole::Guest => ChannelRole::Guest,+ proto::ChannelRole::Banned => ChannelRole::Banned,+ }+ }+ }++ impl Into<proto::ChannelRole> for ChannelRole {+ fn into(self) -> proto::ChannelRole {+ match self {+ ChannelRole::Admin => proto::ChannelRole::Admin,+ ChannelRole::Member => proto::ChannelRole::Member,+ ChannelRole::Guest => proto::ChannelRole::Guest,+ ChannelRole::Banned => proto::ChannelRole::Banned,+ }+ }+ }++ impl Into<i32> for ChannelRole {+ fn into(self) -> i32 {+ let proto: proto::ChannelRole = self.into();+ proto.into()+ }+ }++ #[derive(Eq, PartialEq, Copy, Clone, Debug, EnumIter, DeriveActiveEnum, Default, Hash)]+ #[sea_orm(rs_type = "String", db_type = "String(None)")]+ pub enum ChannelVisibility {+ #[sea_orm(string_value = "public")]+ Public,+ #[sea_orm(string_value = "members")]+ #[default]+ Members,+ }++ impl From<proto::ChannelVisibility> for ChannelVisibility {+ fn from(value: proto::ChannelVisibility) -> Self {+ match value {+ proto::ChannelVisibility::Public => ChannelVisibility::Public,+ proto::ChannelVisibility::Members => ChannelVisibility::Members,+ }+ }+ }++ impl Into<proto::ChannelVisibility> for ChannelVisibility {+ fn into(self) -> proto::ChannelVisibility {+ match self {+ ChannelVisibility::Public => proto::ChannelVisibility::Public,+ ChannelVisibility::Members => proto::ChannelVisibility::Members,+ }+ }+ }++ impl Into<i32> for ChannelVisibility {+ fn into(self) -> i32 {+ let proto: proto::ChannelVisibility = self.into();+ proto.into()+ }+ }diff --cc crates/collab/src/db/queries/channels.rsindex 1ca38b2e3c9,ee989b2ea06..56b1d3b7ff0--- a/crates/collab/src/db/queries/channels.rs+++ b/crates/collab/src/db/queries/channels.rs@@@ -159,19 -269,15 +269,20 @@@ impl Database&self,channel_id: ChannelId,invitee_id: UserId,- admin_id: UserId,+ inviter_id: UserId,- is_admin: bool,+ role: ChannelRole,- ) -> Result<()> {+ ) -> Result<NotificationBatch> {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),user_id: ActiveValue::Set(invitee_id),accepted: ActiveValue::Set(false),@@@ -293,10 -374,10 +407,10 @@@&self,channel_id: ChannelId,member_id: UserId,- remover_id: UserId,+ admin_id: UserId,- ) -> Result<()> {+ ) -> Result<Option<NotificationId>> {self.transaction(|tx| async move {- self.check_user_is_channel_admin(channel_id, remover_id, &*tx)+ self.check_user_is_channel_admin(channel_id, admin_id, &*tx).await?;let result = channel_member::Entity::delete_many()@@@ -546,16 -664,22 +707,23 @@@.await}- pub async fn get_channel_member_details(+ pub async fn get_channel_participant_details(&self,channel_id: ChannelId,- admin_id: UserId,+ user_id: UserId,) -> Result<Vec<proto::ChannelMember>> {self.transaction(|tx| async move {- let user_membership = self- self.check_user_is_channel_admin(channel_id, admin_id, &*tx)++ let role = self+ .check_user_is_channel_member(channel_id, user_id, &*tx).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);+#[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]enum QueryMemberDetails {UserId,@@@ -596,33 -727,38 +771,48 @@@(false, true) => proto::channel_member::Kind::AncestorMember,(false, false) => continue,};- let user_id = user_id.to_proto();- let kind = kind.into();- if let Some(last_row) = rows.last_mut() {- if last_row.user_id == user_id {- if is_direct_member {- last_row.kind = kind;- last_row.admin = is_admin;- }- 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 });}- rows.push(proto::ChannelMember {- user_id,- kind,- admin: is_admin,- });}- // If the user is not an admin, don't give them all of the details- if !user_membership.admin {- rows.retain_mut(|row| {- row.admin = false;- row.kind != proto::channel_member::Kind::Invitee as i32- });- }+ Ok(user_details+ .into_iter()- .map(|(user_id, details)| proto::ChannelMember {- user_id: user_id.to_proto(),- kind: details.kind.into(),- role: details.channel_role.into(),++ .filter_map(|(user_id, details)| {++ // If the user is not an admin, don't give them all of the details++ if role != ChannelRole::Admin {++ if details.kind == Kind::AncestorMember {++ return None;++ }++ return None;++ }+- Ok(rows)++ Some(proto::ChannelMember {++ user_id: user_id.to_proto(),++ kind: details.kind.into(),++ role: details.channel_role.into(),++ })+ })+ .collect())}).await}@@@ -653,20 -806,94 +860,95 @@@channel_id: ChannelId,user_id: UserId,tx: &DatabaseTransaction,- ) -> Result<channel_member::Model> {- ) -> Result<()> {- match self.channel_role_for_user(channel_id, user_id, tx).await? {- Some(ChannelRole::Admin) | Some(ChannelRole::Member) => Ok(()),++ ) -> Result<ChannelRole> {++ let channel_role = self.channel_role_for_user(channel_id, user_id, tx).await?;++ match channel_role {++ Some(ChannelRole::Admin) | Some(ChannelRole::Member) => Ok(channel_role.unwrap()),+ Some(ChannelRole::Banned) | Some(ChannelRole::Guest) | None => Err(anyhow!(+ "user is not a channel member or channel does not exist"+ ))?,+ }+ }++ pub async fn check_user_is_channel_participant(+ &self,+ channel_id: ChannelId,+ user_id: UserId,+ tx: &DatabaseTransaction,+ ) -> Result<()> {+ match self.channel_role_for_user(channel_id, user_id, tx).await? {+ Some(ChannelRole::Admin) | Some(ChannelRole::Member) | Some(ChannelRole::Guest) => {+ Ok(())+ }+ Some(ChannelRole::Banned) | None => Err(anyhow!(+ "user is not a channel participant or channel does not exist"+ ))?,+ }+ }++ pub async fn pending_invite_for_channel(+ &self,+ channel_id: ChannelId,+ user_id: UserId,+ tx: &DatabaseTransaction,+ ) -> Result<Option<channel_member::Model>> {let channel_ids = self.get_channel_ancestors(channel_id, tx).await?;- Ok(channel_member::Entity::find()- .filter(- channel_member::Column::ChannelId- .is_in(channel_ids)- .and(channel_member::Column::UserId.eq(user_id)),- )++ let row = channel_member::Entity::find()+ .filter(channel_member::Column::ChannelId.is_in(channel_ids))+ .filter(channel_member::Column::UserId.eq(user_id))+ .filter(channel_member::Column::Accepted.eq(false)).one(&*tx)- .await?- .ok_or_else(|| anyhow!("user is not a channel member or channel does not exist"))?)+ .await?;++ Ok(row)}- pub async fn check_user_is_channel_admin(+ pub async fn most_public_ancestor_for_channel(+ &self,+ channel_id: ChannelId,+ tx: &DatabaseTransaction,+ ) -> Result<Option<ChannelId>> {+ // Note: if there are many paths to a channel, this will return just one+ let arbitary_path = channel_path::Entity::find()+ .filter(channel_path::Column::ChannelId.eq(channel_id))+ .order_by(channel_path::Column::IdPath, sea_orm::Order::Desc)+ .one(tx)+ .await?;++ let Some(path) = arbitary_path else {+ return Ok(None);+ };++ let ancestor_ids: Vec<ChannelId> = path+ .id_path+ .trim_matches('/')+ .split('/')+ .map(|id| ChannelId::from_proto(id.parse().unwrap()))+ .collect();++ let rows = channel::Entity::find()+ .filter(channel::Column::Id.is_in(ancestor_ids.iter().copied()))+ .filter(channel::Column::Visibility.eq(ChannelVisibility::Public))+ .all(&*tx)+ .await?;++ let mut visible_channels: HashSet<ChannelId> = HashSet::default();++ for row in rows {+ visible_channels.insert(row.id);+ }++ for ancestor in ancestor_ids {+ if visible_channels.contains(&ancestor) {+ return Ok(Some(ancestor));+ }+ }++ Ok(None)+ }++ pub async fn channel_role_for_user(&self,channel_id: ChannelId,user_id: UserId,diff --cc crates/collab/src/db/queries/messages.rsindex 7e93928da2f,06e954103d1..ecf7a399854--- a/crates/collab/src/db/queries/messages.rs+++ b/crates/collab/src/db/queries/messages.rs@@@ -230,13 -172,24 +230,15 @@@ impl Database}// Observe this message for the sender- self.observe_channel_message_internal(- channel_id,- user_id,- message.last_insert_id,- &*tx,- )- .await?;+ self.observe_channel_message_internal(channel_id, user_id, message_id, &*tx)+ .await?;- let mut channel_members = self.get_channel_members_internal(channel_id, &*tx).await?;+ let mut channel_members = self+ .get_channel_participants_internal(channel_id, &*tx)+ .await?;channel_members.retain(|member| !participant_user_ids.contains(member));- Ok((- message.last_insert_id,- participant_connection_ids,- channel_members,- ))+ Ok((message_id, participant_connection_ids, channel_members))}).await}diff --cc crates/collab/src/db/tests/channel_tests.rsindex 904b5faf97d,40842aff5c3..0dbfd0a7891--- a/crates/collab/src/db/tests/channel_tests.rs+++ b/crates/collab/src/db/tests/channel_tests.rs@@@ -859,3 -1113,20 +1105,19 @@@ fn assert_dag(actual: ChannelGraph, exppretty_assertions::assert_eq!(actual_map, expected_map)}++ 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, Ordering::SeqCst),- invite_count: 0,+ },+ )+ .await+ .unwrap()+ .user_id+ }diff --cc crates/collab/src/db/tests/message_tests.rsindex d88ab9d2803,272d8e01009..5d1fce1ca0e--- a/crates/collab/src/db/tests/message_tests.rs+++ b/crates/collab/src/db/tests/message_tests.rs@@@ -1,8 -1,7 +1,8 @@@use crate::{- db::{Database, MessageId, NewUserParams},+ db::{ChannelRole, Database, MessageId, NewUserParams},test_both_dbs,};+use channel::mentions_to_proto;use std::sync::Arc;use time::OffsetDateTime;@@@ -156,17 -152,21 +156,18 @@@ async fn test_unseen_channel_messages(d.user_id;let channel_1 = db.create_channel("channel", None, user).await.unwrap();-let channel_2 = db.create_channel("channel-2", None, user).await.unwrap();- db.invite_channel_member(channel_1, observer, user, false)+ db.invite_channel_member(channel_1, observer, user, ChannelRole::Member).await.unwrap();- db.invite_channel_member(channel_2, observer, user, false)-- db.respond_to_channel_invite(channel_1, observer, true)++ db.invite_channel_member(channel_2, observer, user, ChannelRole::Member).await.unwrap();+- db.invite_channel_member(channel_2, observer, user, ChannelRole::Member)+ db.respond_to_channel_invite(channel_1, observer, true).await.unwrap();-db.respond_to_channel_invite(channel_2, observer, true).await.unwrap();@@@ -295,129 -295,3 +296,129 @@@}]);}++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 = db+ .create_user(+ "[email protected]",+ false,+ NewUserParams {+ github_login: "user_a".into(),+ github_user_id: 1,+ },+ )+ .await+ .unwrap()+ .user_id;+ let user_b = db+ .create_user(+ "[email protected]",+ false,+ NewUserParams {+ github_login: "user_b".into(),+ github_user_id: 2,+ },+ )+ .await+ .unwrap()+ .user_id;+ let user_c = db+ .create_user(+ "[email protected]",+ false,+ NewUserParams {+ github_login: "user_c".into(),+ github_user_id: 3,+ },+ )+ .await+ .unwrap()+ .user_id;++ let channel = db.create_channel("channel", None, user_a).await.unwrap();- db.invite_channel_member(channel, user_b, user_a, false)++ 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 4e4448c000b,15ea3b24e13..191ab762740--- a/crates/collab/src/rpc.rs+++ b/crates/collab/src/rpc.rs@@@ -2296,23 -2282,27 +2295,26 @@@ 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);- db.invite_channel_member(- channel_id,- invitee_id,- session.user_id,- request.role().into(),- )- .await?;+ let notifications = db- .invite_channel_member(channel_id, invitee_id, session.user_id, request.admin)++ .invite_channel_member(++ channel_id,++ invitee_id,++ session.user_id,++ request.role().into(),++ )+ .await?;- let (channel, _) = db- .get_channel(channel_id, session.user_id)- .await?- .ok_or_else(|| anyhow!("channel not found"))?;+ 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,});- 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) {session.peer.send(connection_id, update.clone())?;}@@@ -2577,60 -2592,18 +2618,25 @@@ async fn respond_to_channel_invite) -> Result<()> {let db = session.db().await;let channel_id = ChannelId::from_proto(request.channel_id);- db.respond_to_channel_invite(channel_id, session.user_id, request.accept)+ let notifications = db+ .respond_to_channel_invite(channel_id, session.user_id, request.accept).await?;- let mut update = proto::UpdateChannels::default();- update- .remove_channel_invitations- .push(channel_id.to_proto());if request.accept {- 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(),- 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(),- }),- );+ channel_membership_updated(db, channel_id, &session).await?;+ } else {+ let mut update = proto::UpdateChannels::default();update- .channel_permissions- .extend(- result- .channels_with_admin_privileges- .into_iter()- .map(|channel_id| proto::ChannelPermission {- channel_id: channel_id.to_proto(),- is_admin: true,- }),- );+ .remove_channel_invitations+ .push(channel_id.to_proto());+ session.peer.send(session.connection_id, update)?;}- session.peer.send(session.connection_id, update)?;+++ send_notifications(+ &*session.connection_pool().await,+ &session.peer,+ notifications,+ );response.send(proto::Ack {})?;Ok(())diff --cc crates/collab/src/tests/notification_tests.rsindex 518208c0c7a,00000000000..11144704493mode 100644,000000..100644--- a/crates/collab/src/tests/notification_tests.rs+++ b/crates/collab/src/tests/notification_tests.rs@@@ -1,159 -1,0 +1,159 @@@+use crate::tests::TestServer;+use gpui::{executor::Deterministic, TestAppContext};+use notifications::NotificationEvent;+use parking_lot::Mutex;- use rpc::Notification;++use rpc::{proto, Notification};+use std::sync::Arc;++#[gpui::test]+async fn test_notifications(+ deterministic: Arc<Deterministic>,+ cx_a: &mut TestAppContext,+ cx_b: &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 notification_events_a = Arc::new(Mutex::new(Vec::new()));+ let notification_events_b = Arc::new(Mutex::new(Vec::new()));+ client_a.notification_store().update(cx_a, |_, cx| {+ let events = notification_events_a.clone();+ cx.subscribe(&cx.handle(), move |_, _, event, _| {+ events.lock().push(event.clone());+ })+ .detach()+ });+ client_b.notification_store().update(cx_b, |_, cx| {+ let events = notification_events_b.clone();+ cx.subscribe(&cx.handle(), move |_, _, event, _| {+ events.lock().push(event.clone());+ })+ .detach()+ });++ // Client A sends a contact request to client B.+ client_a+ .user_store()+ .update(cx_a, |store, cx| store.request_contact(client_b.id(), cx))+ .await+ .unwrap();++ // Client B receives a contact request notification and responds to the+ // request, accepting it.+ deterministic.run_until_parked();+ client_b.notification_store().update(cx_b, |store, cx| {+ assert_eq!(store.notification_count(), 1);+ assert_eq!(store.unread_notification_count(), 1);++ let entry = store.notification_at(0).unwrap();+ assert_eq!(+ entry.notification,+ Notification::ContactRequest {+ sender_id: client_a.id()+ }+ );+ assert!(!entry.is_read);+ assert_eq!(+ ¬ification_events_b.lock()[0..],+ &[+ NotificationEvent::NewNotification {+ entry: entry.clone(),+ },+ NotificationEvent::NotificationsUpdated {+ old_range: 0..0,+ new_count: 1+ }+ ]+ );++ store.respond_to_notification(entry.notification.clone(), true, cx);+ });++ // Client B sees the notification is now read, and that they responded.+ deterministic.run_until_parked();+ client_b.notification_store().read_with(cx_b, |store, _| {+ assert_eq!(store.notification_count(), 1);+ assert_eq!(store.unread_notification_count(), 0);++ let entry = store.notification_at(0).unwrap();+ assert!(entry.is_read);+ assert_eq!(entry.response, Some(true));+ assert_eq!(+ ¬ification_events_b.lock()[2..],+ &[+ NotificationEvent::NotificationRead {+ entry: entry.clone(),+ },+ NotificationEvent::NotificationsUpdated {+ old_range: 0..1,+ new_count: 1+ }+ ]+ );+ });++ // Client A receives a notification that client B accepted their request.+ client_a.notification_store().read_with(cx_a, |store, _| {+ assert_eq!(store.notification_count(), 1);+ assert_eq!(store.unread_notification_count(), 1);++ let entry = store.notification_at(0).unwrap();+ assert_eq!(+ entry.notification,+ Notification::ContactRequestAccepted {+ responder_id: client_b.id()+ }+ );+ assert!(!entry.is_read);+ });++ // Client A creates a channel and invites client B to be a member.+ let channel_id = client_a+ .channel_store()+ .update(cx_a, |store, cx| {+ store.create_channel("the-channel", None, cx)+ })+ .await+ .unwrap();+ client_a+ .channel_store()+ .update(cx_a, |store, cx| {- store.invite_member(channel_id, client_b.id(), false, cx)++ store.invite_member(channel_id, client_b.id(), proto::ChannelRole::Member, cx)+ })+ .await+ .unwrap();++ // Client B receives a channel invitation notification and responds to the+ // invitation, accepting it.+ deterministic.run_until_parked();+ client_b.notification_store().update(cx_b, |store, cx| {+ assert_eq!(store.notification_count(), 2);+ assert_eq!(store.unread_notification_count(), 1);++ let entry = store.notification_at(0).unwrap();+ assert_eq!(+ entry.notification,+ Notification::ChannelInvitation {+ channel_id,+ channel_name: "the-channel".to_string(),+ inviter_id: client_a.id()+ }+ );+ assert!(!entry.is_read);++ store.respond_to_notification(entry.notification.clone(), true, cx);+ });++ // Client B sees the notification is now read, and that they responded.+ deterministic.run_until_parked();+ client_b.notification_store().read_with(cx_b, |store, _| {+ assert_eq!(store.notification_count(), 2);+ assert_eq!(store.unread_notification_count(), 0);++ let entry = store.notification_at(0).unwrap();+ assert!(entry.is_read);+ assert_eq!(entry.response, Some(true));+ });+}diff --cc crates/collab/src/tests/test_server.rsindex 444954dae03,c37ea19d528..f7c4fa4146c--- a/crates/collab/src/tests/test_server.rs+++ b/crates/collab/src/tests/test_server.rs@@@ -16,10 -16,9 +16,10 @@@ use futures::{channel::oneshot, StreamEuse gpui::{executor::Deterministic, ModelHandle, Task, TestAppContext, WindowHandle};use language::LanguageRegistry;use node_runtime::FakeNodeRuntime;+use notifications::NotificationStore;use parking_lot::Mutex;use project::{Project, WorktreeId};- use rpc::RECEIVE_TIMEOUT;+ use rpc::{proto::ChannelRole, RECEIVE_TIMEOUT};use settings::SettingsStore;use std::{cell::{Ref, RefCell, RefMut},diff --cc crates/collab_ui/src/chat_panel/message_editor.rsindex 1909c4ec65d,00000000000..b86b934f259mode 100644,000000..100644--- a/crates/collab_ui/src/chat_panel/message_editor.rs+++ b/crates/collab_ui/src/chat_panel/message_editor.rs@@@ -1,304 -1,0 +1,304 @@@+use channel::{Channel, 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>>,+}++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,+ mentions: Vec::new(),+ mentions_task: None,+ }+ }++ pub fn set_channel(&mut self, channel: Arc<Channel>, cx: &mut ViewContext<Self>) {+ self.editor.update(cx, |editor, cx| {+ editor.set_placeholder_text(format!("Message #{}", channel.name), cx);+ });+ self.channel = Some(channel);+ self.refresh_users(cx);+ }++ pub fn refresh_users(&mut self, cx: &mut ViewContext<Self>) {+ if let Some(channel) = &self.channel {+ let members = self.channel_store.update(cx, |store, 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.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,- admin: false,++ role: proto::ChannelRole::Member,+ },+ ChannelMembership {+ user: Arc::new(User {+ github_login: "C_D".into(),+ id: 102,+ avatar: None,+ }),+ kind: proto::channel_member::Kind::Member,- admin: false,++ 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/rpc/proto/zed.protoindex 03bd9d41e0b,0ca10b381ae..6eeb006f3a6--- a/crates/rpc/proto/zed.proto+++ b/crates/rpc/proto/zed.proto@@@ -157,29 -157,23 +157,30 @@@ message EnvelopeUpdateChannelBufferCollaborators update_channel_buffer_collaborators = 130;RejoinChannelBuffers rejoin_channel_buffers = 131;RejoinChannelBuffersResponse rejoin_channel_buffers_response = 132;- AckBufferOperation ack_buffer_operation = 145;-- JoinChannelChat join_channel_chat = 133;- JoinChannelChatResponse join_channel_chat_response = 134;- LeaveChannelChat leave_channel_chat = 135;- SendChannelMessage send_channel_message = 136;- SendChannelMessageResponse send_channel_message_response = 137;- ChannelMessageSent channel_message_sent = 138;- GetChannelMessages get_channel_messages = 139;- GetChannelMessagesResponse get_channel_messages_response = 140;- RemoveChannelMessage remove_channel_message = 141;- AckChannelMessage ack_channel_message = 146;-- LinkChannel link_channel = 142;- UnlinkChannel unlink_channel = 143;- MoveChannel move_channel = 144;- SetChannelVisibility set_channel_visibility = 147; // current max: 147+ AckBufferOperation ack_buffer_operation = 133;++ JoinChannelChat join_channel_chat = 134;+ JoinChannelChatResponse join_channel_chat_response = 135;+ LeaveChannelChat leave_channel_chat = 136;+ SendChannelMessage send_channel_message = 137;+ SendChannelMessageResponse send_channel_message_response = 138;+ ChannelMessageSent channel_message_sent = 139;+ GetChannelMessages get_channel_messages = 140;+ GetChannelMessagesResponse get_channel_messages_response = 141;+ RemoveChannelMessage remove_channel_message = 142;+ AckChannelMessage ack_channel_message = 143;+ GetChannelMessagesById get_channel_messages_by_id = 144;++ LinkChannel link_channel = 145;+ UnlinkChannel unlink_channel = 146;+ MoveChannel move_channel = 147;++ SetChannelVisibility set_channel_visibility = 148;+- NewNotification new_notification = 148;- GetNotifications get_notifications = 149;- GetNotificationsResponse get_notifications_response = 150;- DeleteNotification delete_notification = 151;- MarkNotificationsRead mark_notifications_read = 152; // Current max++ NewNotification new_notification = 149;++ GetNotifications get_notifications = 150;++ GetNotificationsResponse get_notifications_response = 151;++ DeleteNotification delete_notification = 152;++ MarkNotificationsRead mark_notifications_read = 153; // Current max}}diff --cc crates/rpc/src/proto.rsindex 2ca799e7ff9,682b2755486..1c46bbbb141--- a/crates/rpc/src/proto.rs+++ b/crates/rpc/src/proto.rs@@@ -225,35 -204,38 +225,36 @@@ messages!(Ping, Foreground),(PrepareRename, Background),(PrepareRenameResponse, Background),- (ExpandProjectEntryResponse, Foreground),(ProjectEntryResponse, Foreground),+ (RefreshInlayHints, Foreground),+ (RejoinChannelBuffers, Foreground),+ (RejoinChannelBuffersResponse, Foreground),(RejoinRoom, Foreground),(RejoinRoomResponse, Foreground),- (RemoveContact, Foreground),- (RemoveChannelMember, Foreground),- (RemoveChannelMessage, Foreground),(ReloadBuffers, Foreground),(ReloadBuffersResponse, Foreground),+ (RemoveChannelMember, Foreground),+ (RemoveChannelMessage, Foreground),+ (RemoveContact, Foreground),(RemoveProjectCollaborator, Foreground),+ (RenameChannel, Foreground),+ (RenameChannelResponse, Foreground),(RenameProjectEntry, Foreground),(RequestContact, Foreground),- (RespondToContactRequest, Foreground),+ (ResolveCompletionDocumentation, Background),+ (ResolveCompletionDocumentationResponse, Background),+ (ResolveInlayHint, Background),+ (ResolveInlayHintResponse, Background),(RespondToChannelInvite, Foreground),- (JoinChannel, Foreground),+ (RespondToContactRequest, Foreground),(RoomUpdated, Foreground),(SaveBuffer, Foreground),- (RenameChannel, Foreground),- (RenameChannelResponse, Foreground),+ (SetChannelMemberRole, Foreground),+ (SetChannelVisibility, Foreground),(SearchProject, Background),(SearchProjectResponse, Background),+ (SendChannelMessage, Background),+ (SendChannelMessageResponse, Background),- (SetChannelMemberAdmin, Foreground),(ShareProject, Foreground),(ShareProjectResponse, Foreground),(ShowContacts, Foreground),@@@ -351,16 -326,32 +352,17 @@@ request_messages!ResolveCompletionDocumentationResponse),(ResolveInlayHint, ResolveInlayHintResponse),- (RefreshInlayHints, Ack),- (ReloadBuffers, ReloadBuffersResponse),- (RequestContact, Ack),- (RemoveChannelMember, Ack),- (RemoveContact, Ack),- (RespondToContactRequest, Ack),(RespondToChannelInvite, Ack),- (SetChannelMemberRole, Ack),- (SetChannelVisibility, Ack),- (SendChannelMessage, SendChannelMessageResponse),- (GetChannelMessages, GetChannelMessagesResponse),- (GetChannelMembers, GetChannelMembersResponse),- (JoinChannel, JoinRoomResponse),- (RemoveChannelMessage, Ack),- (DeleteChannel, Ack),- (RenameProjectEntry, ProjectEntryResponse),- (RenameChannel, RenameChannelResponse),- (LinkChannel, Ack),- (UnlinkChannel, Ack),- (MoveChannel, Ack),+ (RespondToContactRequest, Ack),(SaveBuffer, BufferSaved),(SearchProject, SearchProjectResponse),+ (SendChannelMessage, SendChannelMessageResponse),- (SetChannelMemberAdmin, Ack),++ (SetChannelMemberRole, Ack),++ (SetChannelVisibility, Ack),(ShareProject, ShareProjectResponse),(SynchronizeBuffers, SynchronizeBuffersResponse),- (RejoinChannelBuffers, RejoinChannelBuffersResponse),(Test, Test),+ (UnlinkChannel, Ack),(UpdateBuffer, Ack),(UpdateParticipantLocation, Ack),(UpdateProject, Ack),