rpc.rs

   1mod store;
   2
   3use super::{
   4    auth::process_auth_header,
   5    db::{ChannelId, MessageId, UserId},
   6    AppState,
   7};
   8use anyhow::anyhow;
   9use async_io::Timer;
  10use async_std::task;
  11use async_tungstenite::{tungstenite::protocol::Role, WebSocketStream};
  12use collections::{HashMap, HashSet};
  13use futures::{channel::mpsc, future::BoxFuture, FutureExt, SinkExt, StreamExt};
  14use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard};
  15use rpc::{
  16    proto::{self, AnyTypedEnvelope, EntityMessage, EnvelopedMessage, RequestMessage},
  17    Connection, ConnectionId, Peer, TypedEnvelope,
  18};
  19use sha1::{Digest as _, Sha1};
  20use std::{
  21    any::TypeId,
  22    future::Future,
  23    sync::Arc,
  24    time::{Duration, Instant},
  25};
  26use store::{Store, Worktree};
  27use surf::StatusCode;
  28use tide::log;
  29use tide::{
  30    http::headers::{HeaderName, CONNECTION, UPGRADE},
  31    Request, Response,
  32};
  33use time::OffsetDateTime;
  34
  35type MessageHandler = Box<
  36    dyn Send
  37        + Sync
  38        + Fn(Arc<Server>, Box<dyn AnyTypedEnvelope>) -> BoxFuture<'static, tide::Result<()>>,
  39>;
  40
  41pub struct Server {
  42    peer: Arc<Peer>,
  43    store: RwLock<Store>,
  44    app_state: Arc<AppState>,
  45    handlers: HashMap<TypeId, MessageHandler>,
  46    notifications: Option<mpsc::UnboundedSender<()>>,
  47}
  48
  49pub trait Executor: Send + Clone {
  50    type Timer: Send + Future;
  51    fn spawn_detached<F: 'static + Send + Future<Output = ()>>(&self, future: F);
  52    fn timer(&self, duration: Duration) -> Self::Timer;
  53}
  54
  55#[derive(Clone)]
  56pub struct RealExecutor;
  57
  58const MESSAGE_COUNT_PER_PAGE: usize = 100;
  59const MAX_MESSAGE_LEN: usize = 1024;
  60
  61impl Server {
  62    pub fn new(
  63        app_state: Arc<AppState>,
  64        peer: Arc<Peer>,
  65        notifications: Option<mpsc::UnboundedSender<()>>,
  66    ) -> Arc<Self> {
  67        let mut server = Self {
  68            peer,
  69            app_state,
  70            store: Default::default(),
  71            handlers: Default::default(),
  72            notifications,
  73        };
  74
  75        server
  76            .add_request_handler(Server::ping)
  77            .add_request_handler(Server::register_project)
  78            .add_message_handler(Server::unregister_project)
  79            .add_request_handler(Server::share_project)
  80            .add_message_handler(Server::unshare_project)
  81            .add_request_handler(Server::join_project)
  82            .add_message_handler(Server::leave_project)
  83            .add_request_handler(Server::register_worktree)
  84            .add_message_handler(Server::unregister_worktree)
  85            .add_request_handler(Server::update_worktree)
  86            .add_message_handler(Server::start_language_server)
  87            .add_message_handler(Server::update_language_server)
  88            .add_message_handler(Server::update_diagnostic_summary)
  89            .add_request_handler(Server::forward_project_request::<proto::GetDefinition>)
  90            .add_request_handler(Server::forward_project_request::<proto::GetReferences>)
  91            .add_request_handler(Server::forward_project_request::<proto::SearchProject>)
  92            .add_request_handler(Server::forward_project_request::<proto::GetDocumentHighlights>)
  93            .add_request_handler(Server::forward_project_request::<proto::GetProjectSymbols>)
  94            .add_request_handler(Server::forward_project_request::<proto::OpenBufferForSymbol>)
  95            .add_request_handler(Server::forward_project_request::<proto::OpenBufferById>)
  96            .add_request_handler(Server::forward_project_request::<proto::OpenBufferByPath>)
  97            .add_request_handler(Server::forward_project_request::<proto::GetCompletions>)
  98            .add_request_handler(
  99                Server::forward_project_request::<proto::ApplyCompletionAdditionalEdits>,
 100            )
 101            .add_request_handler(Server::forward_project_request::<proto::GetCodeActions>)
 102            .add_request_handler(Server::forward_project_request::<proto::ApplyCodeAction>)
 103            .add_request_handler(Server::forward_project_request::<proto::PrepareRename>)
 104            .add_request_handler(Server::forward_project_request::<proto::PerformRename>)
 105            .add_request_handler(Server::forward_project_request::<proto::ReloadBuffers>)
 106            .add_request_handler(Server::forward_project_request::<proto::FormatBuffers>)
 107            .add_request_handler(Server::update_buffer)
 108            .add_message_handler(Server::update_buffer_file)
 109            .add_message_handler(Server::buffer_reloaded)
 110            .add_message_handler(Server::buffer_saved)
 111            .add_request_handler(Server::save_buffer)
 112            .add_request_handler(Server::get_channels)
 113            .add_request_handler(Server::get_users)
 114            .add_request_handler(Server::join_channel)
 115            .add_message_handler(Server::leave_channel)
 116            .add_request_handler(Server::send_channel_message)
 117            .add_request_handler(Server::follow)
 118            .add_message_handler(Server::unfollow)
 119            .add_message_handler(Server::update_followers)
 120            .add_request_handler(Server::get_channel_messages);
 121
 122        Arc::new(server)
 123    }
 124
 125    fn add_message_handler<F, Fut, M>(&mut self, handler: F) -> &mut Self
 126    where
 127        F: 'static + Send + Sync + Fn(Arc<Self>, TypedEnvelope<M>) -> Fut,
 128        Fut: 'static + Send + Future<Output = tide::Result<()>>,
 129        M: EnvelopedMessage,
 130    {
 131        let prev_handler = self.handlers.insert(
 132            TypeId::of::<M>(),
 133            Box::new(move |server, envelope| {
 134                let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
 135                (handler)(server, *envelope).boxed()
 136            }),
 137        );
 138        if prev_handler.is_some() {
 139            panic!("registered a handler for the same message twice");
 140        }
 141        self
 142    }
 143
 144    fn add_request_handler<F, Fut, M>(&mut self, handler: F) -> &mut Self
 145    where
 146        F: 'static + Send + Sync + Fn(Arc<Self>, TypedEnvelope<M>) -> Fut,
 147        Fut: 'static + Send + Future<Output = tide::Result<M::Response>>,
 148        M: RequestMessage,
 149    {
 150        self.add_message_handler(move |server, envelope| {
 151            let receipt = envelope.receipt();
 152            let response = (handler)(server.clone(), envelope);
 153            async move {
 154                match response.await {
 155                    Ok(response) => {
 156                        server.peer.respond(receipt, response)?;
 157                        Ok(())
 158                    }
 159                    Err(error) => {
 160                        server.peer.respond_with_error(
 161                            receipt,
 162                            proto::Error {
 163                                message: error.to_string(),
 164                            },
 165                        )?;
 166                        Err(error)
 167                    }
 168                }
 169            }
 170        })
 171    }
 172
 173    pub fn handle_connection<E: Executor>(
 174        self: &Arc<Self>,
 175        connection: Connection,
 176        addr: String,
 177        user_id: UserId,
 178        mut send_connection_id: Option<mpsc::Sender<ConnectionId>>,
 179        executor: E,
 180    ) -> impl Future<Output = ()> {
 181        let mut this = self.clone();
 182        async move {
 183            let (connection_id, handle_io, mut incoming_rx) = this
 184                .peer
 185                .add_connection(connection, {
 186                    let executor = executor.clone();
 187                    move |duration| {
 188                        let timer = executor.timer(duration);
 189                        async move {
 190                            timer.await;
 191                        }
 192                    }
 193                })
 194                .await;
 195
 196            if let Some(send_connection_id) = send_connection_id.as_mut() {
 197                let _ = send_connection_id.send(connection_id).await;
 198            }
 199
 200            this.state_mut().add_connection(connection_id, user_id);
 201            if let Err(err) = this.update_contacts_for_users(&[user_id]) {
 202                log::error!("error updating contacts for {:?}: {}", user_id, err);
 203            }
 204
 205            let handle_io = handle_io.fuse();
 206            futures::pin_mut!(handle_io);
 207            loop {
 208                let next_message = incoming_rx.next().fuse();
 209                futures::pin_mut!(next_message);
 210                futures::select_biased! {
 211                    result = handle_io => {
 212                        if let Err(err) = result {
 213                            log::error!("error handling rpc connection {:?} - {:?}", addr, err);
 214                        }
 215                        break;
 216                    }
 217                    message = next_message => {
 218                        if let Some(message) = message {
 219                            let start_time = Instant::now();
 220                            let type_name = message.payload_type_name();
 221                            log::info!("rpc message received. connection:{}, type:{}", connection_id, type_name);
 222                            if let Some(handler) = this.handlers.get(&message.payload_type_id()) {
 223                                let notifications = this.notifications.clone();
 224                                let is_background = message.is_background();
 225                                let handle_message = (handler)(this.clone(), message);
 226                                let handle_message = async move {
 227                                    if let Err(err) = handle_message.await {
 228                                        log::error!("rpc message error. connection:{}, type:{}, error:{:?}", connection_id, type_name, err);
 229                                    } else {
 230                                        log::info!("rpc message handled. connection:{}, type:{}, duration:{:?}", connection_id, type_name, start_time.elapsed());
 231                                    }
 232                                    if let Some(mut notifications) = notifications {
 233                                        let _ = notifications.send(()).await;
 234                                    }
 235                                };
 236                                if is_background {
 237                                    executor.spawn_detached(handle_message);
 238                                } else {
 239                                    handle_message.await;
 240                                }
 241                            } else {
 242                                log::warn!("unhandled message: {}", type_name);
 243                            }
 244                        } else {
 245                            log::info!("rpc connection closed {:?}", addr);
 246                            break;
 247                        }
 248                    }
 249                }
 250            }
 251
 252            if let Err(err) = this.sign_out(connection_id).await {
 253                log::error!("error signing out connection {:?} - {:?}", addr, err);
 254            }
 255        }
 256    }
 257
 258    async fn sign_out(self: &mut Arc<Self>, connection_id: ConnectionId) -> tide::Result<()> {
 259        self.peer.disconnect(connection_id);
 260        let removed_connection = self.state_mut().remove_connection(connection_id)?;
 261
 262        for (project_id, project) in removed_connection.hosted_projects {
 263            if let Some(share) = project.share {
 264                broadcast(
 265                    connection_id,
 266                    share.guests.keys().copied().collect(),
 267                    |conn_id| {
 268                        self.peer
 269                            .send(conn_id, proto::UnshareProject { project_id })
 270                    },
 271                )?;
 272            }
 273        }
 274
 275        for (project_id, peer_ids) in removed_connection.guest_project_ids {
 276            broadcast(connection_id, peer_ids, |conn_id| {
 277                self.peer.send(
 278                    conn_id,
 279                    proto::RemoveProjectCollaborator {
 280                        project_id,
 281                        peer_id: connection_id.0,
 282                    },
 283                )
 284            })?;
 285        }
 286
 287        self.update_contacts_for_users(removed_connection.contact_ids.iter())?;
 288        Ok(())
 289    }
 290
 291    async fn ping(self: Arc<Server>, _: TypedEnvelope<proto::Ping>) -> tide::Result<proto::Ack> {
 292        Ok(proto::Ack {})
 293    }
 294
 295    async fn register_project(
 296        mut self: Arc<Server>,
 297        request: TypedEnvelope<proto::RegisterProject>,
 298    ) -> tide::Result<proto::RegisterProjectResponse> {
 299        let project_id = {
 300            let mut state = self.state_mut();
 301            let user_id = state.user_id_for_connection(request.sender_id)?;
 302            state.register_project(request.sender_id, user_id)
 303        };
 304        Ok(proto::RegisterProjectResponse { project_id })
 305    }
 306
 307    async fn unregister_project(
 308        mut self: Arc<Server>,
 309        request: TypedEnvelope<proto::UnregisterProject>,
 310    ) -> tide::Result<()> {
 311        let project = self
 312            .state_mut()
 313            .unregister_project(request.payload.project_id, request.sender_id)?;
 314        self.update_contacts_for_users(project.authorized_user_ids().iter())?;
 315        Ok(())
 316    }
 317
 318    async fn share_project(
 319        mut self: Arc<Server>,
 320        request: TypedEnvelope<proto::ShareProject>,
 321    ) -> tide::Result<proto::Ack> {
 322        self.state_mut()
 323            .share_project(request.payload.project_id, request.sender_id);
 324        Ok(proto::Ack {})
 325    }
 326
 327    async fn unshare_project(
 328        mut self: Arc<Server>,
 329        request: TypedEnvelope<proto::UnshareProject>,
 330    ) -> tide::Result<()> {
 331        let project_id = request.payload.project_id;
 332        let project = self
 333            .state_mut()
 334            .unshare_project(project_id, request.sender_id)?;
 335
 336        broadcast(request.sender_id, project.connection_ids, |conn_id| {
 337            self.peer
 338                .send(conn_id, proto::UnshareProject { project_id })
 339        })?;
 340        self.update_contacts_for_users(&project.authorized_user_ids)?;
 341        Ok(())
 342    }
 343
 344    async fn join_project(
 345        mut self: Arc<Server>,
 346        request: TypedEnvelope<proto::JoinProject>,
 347    ) -> tide::Result<proto::JoinProjectResponse> {
 348        let project_id = request.payload.project_id;
 349
 350        let user_id = self.state().user_id_for_connection(request.sender_id)?;
 351        let (response, connection_ids, contact_user_ids) = self
 352            .state_mut()
 353            .join_project(request.sender_id, user_id, project_id)
 354            .and_then(|joined| {
 355                let share = joined.project.share()?;
 356                let peer_count = share.guests.len();
 357                let mut collaborators = Vec::with_capacity(peer_count);
 358                collaborators.push(proto::Collaborator {
 359                    peer_id: joined.project.host_connection_id.0,
 360                    replica_id: 0,
 361                    user_id: joined.project.host_user_id.to_proto(),
 362                });
 363                let worktrees = share
 364                    .worktrees
 365                    .iter()
 366                    .filter_map(|(id, shared_worktree)| {
 367                        let worktree = joined.project.worktrees.get(&id)?;
 368                        Some(proto::Worktree {
 369                            id: *id,
 370                            root_name: worktree.root_name.clone(),
 371                            entries: shared_worktree.entries.values().cloned().collect(),
 372                            diagnostic_summaries: shared_worktree
 373                                .diagnostic_summaries
 374                                .values()
 375                                .cloned()
 376                                .collect(),
 377                            visible: worktree.visible,
 378                        })
 379                    })
 380                    .collect();
 381                for (peer_conn_id, (peer_replica_id, peer_user_id)) in &share.guests {
 382                    if *peer_conn_id != request.sender_id {
 383                        collaborators.push(proto::Collaborator {
 384                            peer_id: peer_conn_id.0,
 385                            replica_id: *peer_replica_id as u32,
 386                            user_id: peer_user_id.to_proto(),
 387                        });
 388                    }
 389                }
 390                let response = proto::JoinProjectResponse {
 391                    worktrees,
 392                    replica_id: joined.replica_id as u32,
 393                    collaborators,
 394                    language_servers: joined.project.language_servers.clone(),
 395                };
 396                let connection_ids = joined.project.connection_ids();
 397                let contact_user_ids = joined.project.authorized_user_ids();
 398                Ok((response, connection_ids, contact_user_ids))
 399            })?;
 400
 401        broadcast(request.sender_id, connection_ids, |conn_id| {
 402            self.peer.send(
 403                conn_id,
 404                proto::AddProjectCollaborator {
 405                    project_id,
 406                    collaborator: Some(proto::Collaborator {
 407                        peer_id: request.sender_id.0,
 408                        replica_id: response.replica_id,
 409                        user_id: user_id.to_proto(),
 410                    }),
 411                },
 412            )
 413        })?;
 414        self.update_contacts_for_users(&contact_user_ids)?;
 415        Ok(response)
 416    }
 417
 418    async fn leave_project(
 419        mut self: Arc<Server>,
 420        request: TypedEnvelope<proto::LeaveProject>,
 421    ) -> tide::Result<()> {
 422        let sender_id = request.sender_id;
 423        let project_id = request.payload.project_id;
 424        let worktree = self.state_mut().leave_project(sender_id, project_id)?;
 425
 426        broadcast(sender_id, worktree.connection_ids, |conn_id| {
 427            self.peer.send(
 428                conn_id,
 429                proto::RemoveProjectCollaborator {
 430                    project_id,
 431                    peer_id: sender_id.0,
 432                },
 433            )
 434        })?;
 435        self.update_contacts_for_users(&worktree.authorized_user_ids)?;
 436
 437        Ok(())
 438    }
 439
 440    async fn register_worktree(
 441        mut self: Arc<Server>,
 442        request: TypedEnvelope<proto::RegisterWorktree>,
 443    ) -> tide::Result<proto::Ack> {
 444        let host_user_id = self.state().user_id_for_connection(request.sender_id)?;
 445
 446        let mut contact_user_ids = HashSet::default();
 447        contact_user_ids.insert(host_user_id);
 448        for github_login in &request.payload.authorized_logins {
 449            let contact_user_id = self.app_state.db.create_user(github_login, false).await?;
 450            contact_user_ids.insert(contact_user_id);
 451        }
 452
 453        let contact_user_ids = contact_user_ids.into_iter().collect::<Vec<_>>();
 454        let guest_connection_ids;
 455        {
 456            let mut state = self.state_mut();
 457            guest_connection_ids = state
 458                .read_project(request.payload.project_id, request.sender_id)?
 459                .guest_connection_ids();
 460            state.register_worktree(
 461                request.payload.project_id,
 462                request.payload.worktree_id,
 463                request.sender_id,
 464                Worktree {
 465                    authorized_user_ids: contact_user_ids.clone(),
 466                    root_name: request.payload.root_name.clone(),
 467                    visible: request.payload.visible,
 468                },
 469            )?;
 470        }
 471        broadcast(request.sender_id, guest_connection_ids, |connection_id| {
 472            self.peer
 473                .forward_send(request.sender_id, connection_id, request.payload.clone())
 474        })?;
 475        self.update_contacts_for_users(&contact_user_ids)?;
 476        Ok(proto::Ack {})
 477    }
 478
 479    async fn unregister_worktree(
 480        mut self: Arc<Server>,
 481        request: TypedEnvelope<proto::UnregisterWorktree>,
 482    ) -> tide::Result<()> {
 483        let project_id = request.payload.project_id;
 484        let worktree_id = request.payload.worktree_id;
 485        let (worktree, guest_connection_ids) =
 486            self.state_mut()
 487                .unregister_worktree(project_id, worktree_id, request.sender_id)?;
 488        broadcast(request.sender_id, guest_connection_ids, |conn_id| {
 489            self.peer.send(
 490                conn_id,
 491                proto::UnregisterWorktree {
 492                    project_id,
 493                    worktree_id,
 494                },
 495            )
 496        })?;
 497        self.update_contacts_for_users(&worktree.authorized_user_ids)?;
 498        Ok(())
 499    }
 500
 501    async fn update_worktree(
 502        mut self: Arc<Server>,
 503        request: TypedEnvelope<proto::UpdateWorktree>,
 504    ) -> tide::Result<proto::Ack> {
 505        let connection_ids = self.state_mut().update_worktree(
 506            request.sender_id,
 507            request.payload.project_id,
 508            request.payload.worktree_id,
 509            &request.payload.removed_entries,
 510            &request.payload.updated_entries,
 511        )?;
 512
 513        broadcast(request.sender_id, connection_ids, |connection_id| {
 514            self.peer
 515                .forward_send(request.sender_id, connection_id, request.payload.clone())
 516        })?;
 517
 518        Ok(proto::Ack {})
 519    }
 520
 521    async fn update_diagnostic_summary(
 522        mut self: Arc<Server>,
 523        request: TypedEnvelope<proto::UpdateDiagnosticSummary>,
 524    ) -> tide::Result<()> {
 525        let summary = request
 526            .payload
 527            .summary
 528            .clone()
 529            .ok_or_else(|| anyhow!("invalid summary"))?;
 530        let receiver_ids = self.state_mut().update_diagnostic_summary(
 531            request.payload.project_id,
 532            request.payload.worktree_id,
 533            request.sender_id,
 534            summary,
 535        )?;
 536
 537        broadcast(request.sender_id, receiver_ids, |connection_id| {
 538            self.peer
 539                .forward_send(request.sender_id, connection_id, request.payload.clone())
 540        })?;
 541        Ok(())
 542    }
 543
 544    async fn start_language_server(
 545        mut self: Arc<Server>,
 546        request: TypedEnvelope<proto::StartLanguageServer>,
 547    ) -> tide::Result<()> {
 548        let receiver_ids = self.state_mut().start_language_server(
 549            request.payload.project_id,
 550            request.sender_id,
 551            request
 552                .payload
 553                .server
 554                .clone()
 555                .ok_or_else(|| anyhow!("invalid language server"))?,
 556        )?;
 557        broadcast(request.sender_id, receiver_ids, |connection_id| {
 558            self.peer
 559                .forward_send(request.sender_id, connection_id, request.payload.clone())
 560        })?;
 561        Ok(())
 562    }
 563
 564    async fn update_language_server(
 565        self: Arc<Server>,
 566        request: TypedEnvelope<proto::UpdateLanguageServer>,
 567    ) -> tide::Result<()> {
 568        let receiver_ids = self
 569            .state()
 570            .project_connection_ids(request.payload.project_id, request.sender_id)?;
 571        broadcast(request.sender_id, receiver_ids, |connection_id| {
 572            self.peer
 573                .forward_send(request.sender_id, connection_id, request.payload.clone())
 574        })?;
 575        Ok(())
 576    }
 577
 578    async fn forward_project_request<T>(
 579        self: Arc<Server>,
 580        request: TypedEnvelope<T>,
 581    ) -> tide::Result<T::Response>
 582    where
 583        T: EntityMessage + RequestMessage,
 584    {
 585        let host_connection_id = self
 586            .state()
 587            .read_project(request.payload.remote_entity_id(), request.sender_id)?
 588            .host_connection_id;
 589        Ok(self
 590            .peer
 591            .forward_request(request.sender_id, host_connection_id, request.payload)
 592            .await?)
 593    }
 594
 595    async fn save_buffer(
 596        self: Arc<Server>,
 597        request: TypedEnvelope<proto::SaveBuffer>,
 598    ) -> tide::Result<proto::BufferSaved> {
 599        let host;
 600        let mut guests;
 601        {
 602            let state = self.state();
 603            let project = state.read_project(request.payload.project_id, request.sender_id)?;
 604            host = project.host_connection_id;
 605            guests = project.guest_connection_ids()
 606        }
 607
 608        let response = self
 609            .peer
 610            .forward_request(request.sender_id, host, request.payload.clone())
 611            .await?;
 612
 613        guests.retain(|guest_connection_id| *guest_connection_id != request.sender_id);
 614        broadcast(host, guests, |conn_id| {
 615            self.peer.forward_send(host, conn_id, response.clone())
 616        })?;
 617
 618        Ok(response)
 619    }
 620
 621    async fn update_buffer(
 622        self: Arc<Server>,
 623        request: TypedEnvelope<proto::UpdateBuffer>,
 624    ) -> tide::Result<proto::Ack> {
 625        let receiver_ids = self
 626            .state()
 627            .project_connection_ids(request.payload.project_id, request.sender_id)?;
 628        broadcast(request.sender_id, receiver_ids, |connection_id| {
 629            self.peer
 630                .forward_send(request.sender_id, connection_id, request.payload.clone())
 631        })?;
 632        Ok(proto::Ack {})
 633    }
 634
 635    async fn update_buffer_file(
 636        self: Arc<Server>,
 637        request: TypedEnvelope<proto::UpdateBufferFile>,
 638    ) -> tide::Result<()> {
 639        let receiver_ids = self
 640            .state()
 641            .project_connection_ids(request.payload.project_id, request.sender_id)?;
 642        broadcast(request.sender_id, receiver_ids, |connection_id| {
 643            self.peer
 644                .forward_send(request.sender_id, connection_id, request.payload.clone())
 645        })?;
 646        Ok(())
 647    }
 648
 649    async fn buffer_reloaded(
 650        self: Arc<Server>,
 651        request: TypedEnvelope<proto::BufferReloaded>,
 652    ) -> tide::Result<()> {
 653        let receiver_ids = self
 654            .state()
 655            .project_connection_ids(request.payload.project_id, request.sender_id)?;
 656        broadcast(request.sender_id, receiver_ids, |connection_id| {
 657            self.peer
 658                .forward_send(request.sender_id, connection_id, request.payload.clone())
 659        })?;
 660        Ok(())
 661    }
 662
 663    async fn buffer_saved(
 664        self: Arc<Server>,
 665        request: TypedEnvelope<proto::BufferSaved>,
 666    ) -> tide::Result<()> {
 667        let receiver_ids = self
 668            .state()
 669            .project_connection_ids(request.payload.project_id, request.sender_id)?;
 670        broadcast(request.sender_id, receiver_ids, |connection_id| {
 671            self.peer
 672                .forward_send(request.sender_id, connection_id, request.payload.clone())
 673        })?;
 674        Ok(())
 675    }
 676
 677    async fn follow(
 678        self: Arc<Self>,
 679        request: TypedEnvelope<proto::Follow>,
 680    ) -> tide::Result<proto::FollowResponse> {
 681        let leader_id = ConnectionId(request.payload.leader_id);
 682        let follower_id = request.sender_id;
 683        if !self
 684            .state()
 685            .project_connection_ids(request.payload.project_id, follower_id)?
 686            .contains(&leader_id)
 687        {
 688            Err(anyhow!("no such peer"))?;
 689        }
 690        let mut response = self
 691            .peer
 692            .forward_request(request.sender_id, leader_id, request.payload)
 693            .await?;
 694        response
 695            .views
 696            .retain(|view| view.leader_id != Some(follower_id.0));
 697        Ok(response)
 698    }
 699
 700    async fn unfollow(
 701        self: Arc<Self>,
 702        request: TypedEnvelope<proto::Unfollow>,
 703    ) -> tide::Result<()> {
 704        let leader_id = ConnectionId(request.payload.leader_id);
 705        if !self
 706            .state()
 707            .project_connection_ids(request.payload.project_id, request.sender_id)?
 708            .contains(&leader_id)
 709        {
 710            Err(anyhow!("no such peer"))?;
 711        }
 712        self.peer
 713            .forward_send(request.sender_id, leader_id, request.payload)?;
 714        Ok(())
 715    }
 716
 717    async fn update_followers(
 718        self: Arc<Self>,
 719        request: TypedEnvelope<proto::UpdateFollowers>,
 720    ) -> tide::Result<()> {
 721        let connection_ids = self
 722            .state()
 723            .project_connection_ids(request.payload.project_id, request.sender_id)?;
 724        let leader_id = request
 725            .payload
 726            .variant
 727            .as_ref()
 728            .and_then(|variant| match variant {
 729                proto::update_followers::Variant::CreateView(payload) => payload.leader_id,
 730                proto::update_followers::Variant::UpdateView(payload) => payload.leader_id,
 731                proto::update_followers::Variant::UpdateActiveView(payload) => payload.leader_id,
 732            });
 733        for follower_id in &request.payload.follower_ids {
 734            let follower_id = ConnectionId(*follower_id);
 735            if connection_ids.contains(&follower_id) && Some(follower_id.0) != leader_id {
 736                self.peer
 737                    .forward_send(request.sender_id, follower_id, request.payload.clone())?;
 738            }
 739        }
 740        Ok(())
 741    }
 742
 743    async fn get_channels(
 744        self: Arc<Server>,
 745        request: TypedEnvelope<proto::GetChannels>,
 746    ) -> tide::Result<proto::GetChannelsResponse> {
 747        let user_id = self.state().user_id_for_connection(request.sender_id)?;
 748        let channels = self.app_state.db.get_accessible_channels(user_id).await?;
 749        Ok(proto::GetChannelsResponse {
 750            channels: channels
 751                .into_iter()
 752                .map(|chan| proto::Channel {
 753                    id: chan.id.to_proto(),
 754                    name: chan.name,
 755                })
 756                .collect(),
 757        })
 758    }
 759
 760    async fn get_users(
 761        self: Arc<Server>,
 762        request: TypedEnvelope<proto::GetUsers>,
 763    ) -> tide::Result<proto::GetUsersResponse> {
 764        let user_ids = request
 765            .payload
 766            .user_ids
 767            .into_iter()
 768            .map(UserId::from_proto)
 769            .collect();
 770        let users = self
 771            .app_state
 772            .db
 773            .get_users_by_ids(user_ids)
 774            .await?
 775            .into_iter()
 776            .map(|user| proto::User {
 777                id: user.id.to_proto(),
 778                avatar_url: format!("https://github.com/{}.png?size=128", user.github_login),
 779                github_login: user.github_login,
 780            })
 781            .collect();
 782        Ok(proto::GetUsersResponse { users })
 783    }
 784
 785    fn update_contacts_for_users<'a>(
 786        self: &Arc<Server>,
 787        user_ids: impl IntoIterator<Item = &'a UserId>,
 788    ) -> anyhow::Result<()> {
 789        let mut result = Ok(());
 790        let state = self.state();
 791        for user_id in user_ids {
 792            let contacts = state.contacts_for_user(*user_id);
 793            for connection_id in state.connection_ids_for_user(*user_id) {
 794                if let Err(error) = self.peer.send(
 795                    connection_id,
 796                    proto::UpdateContacts {
 797                        contacts: contacts.clone(),
 798                    },
 799                ) {
 800                    result = Err(error);
 801                }
 802            }
 803        }
 804        result
 805    }
 806
 807    async fn join_channel(
 808        mut self: Arc<Self>,
 809        request: TypedEnvelope<proto::JoinChannel>,
 810    ) -> tide::Result<proto::JoinChannelResponse> {
 811        let user_id = self.state().user_id_for_connection(request.sender_id)?;
 812        let channel_id = ChannelId::from_proto(request.payload.channel_id);
 813        if !self
 814            .app_state
 815            .db
 816            .can_user_access_channel(user_id, channel_id)
 817            .await?
 818        {
 819            Err(anyhow!("access denied"))?;
 820        }
 821
 822        self.state_mut().join_channel(request.sender_id, channel_id);
 823        let messages = self
 824            .app_state
 825            .db
 826            .get_channel_messages(channel_id, MESSAGE_COUNT_PER_PAGE, None)
 827            .await?
 828            .into_iter()
 829            .map(|msg| proto::ChannelMessage {
 830                id: msg.id.to_proto(),
 831                body: msg.body,
 832                timestamp: msg.sent_at.unix_timestamp() as u64,
 833                sender_id: msg.sender_id.to_proto(),
 834                nonce: Some(msg.nonce.as_u128().into()),
 835            })
 836            .collect::<Vec<_>>();
 837        Ok(proto::JoinChannelResponse {
 838            done: messages.len() < MESSAGE_COUNT_PER_PAGE,
 839            messages,
 840        })
 841    }
 842
 843    async fn leave_channel(
 844        mut self: Arc<Self>,
 845        request: TypedEnvelope<proto::LeaveChannel>,
 846    ) -> tide::Result<()> {
 847        let user_id = self.state().user_id_for_connection(request.sender_id)?;
 848        let channel_id = ChannelId::from_proto(request.payload.channel_id);
 849        if !self
 850            .app_state
 851            .db
 852            .can_user_access_channel(user_id, channel_id)
 853            .await?
 854        {
 855            Err(anyhow!("access denied"))?;
 856        }
 857
 858        self.state_mut()
 859            .leave_channel(request.sender_id, channel_id);
 860
 861        Ok(())
 862    }
 863
 864    async fn send_channel_message(
 865        self: Arc<Self>,
 866        request: TypedEnvelope<proto::SendChannelMessage>,
 867    ) -> tide::Result<proto::SendChannelMessageResponse> {
 868        let channel_id = ChannelId::from_proto(request.payload.channel_id);
 869        let user_id;
 870        let connection_ids;
 871        {
 872            let state = self.state();
 873            user_id = state.user_id_for_connection(request.sender_id)?;
 874            connection_ids = state.channel_connection_ids(channel_id)?;
 875        }
 876
 877        // Validate the message body.
 878        let body = request.payload.body.trim().to_string();
 879        if body.len() > MAX_MESSAGE_LEN {
 880            return Err(anyhow!("message is too long"))?;
 881        }
 882        if body.is_empty() {
 883            return Err(anyhow!("message can't be blank"))?;
 884        }
 885
 886        let timestamp = OffsetDateTime::now_utc();
 887        let nonce = request
 888            .payload
 889            .nonce
 890            .ok_or_else(|| anyhow!("nonce can't be blank"))?;
 891
 892        let message_id = self
 893            .app_state
 894            .db
 895            .create_channel_message(channel_id, user_id, &body, timestamp, nonce.clone().into())
 896            .await?
 897            .to_proto();
 898        let message = proto::ChannelMessage {
 899            sender_id: user_id.to_proto(),
 900            id: message_id,
 901            body,
 902            timestamp: timestamp.unix_timestamp() as u64,
 903            nonce: Some(nonce),
 904        };
 905        broadcast(request.sender_id, connection_ids, |conn_id| {
 906            self.peer.send(
 907                conn_id,
 908                proto::ChannelMessageSent {
 909                    channel_id: channel_id.to_proto(),
 910                    message: Some(message.clone()),
 911                },
 912            )
 913        })?;
 914        Ok(proto::SendChannelMessageResponse {
 915            message: Some(message),
 916        })
 917    }
 918
 919    async fn get_channel_messages(
 920        self: Arc<Self>,
 921        request: TypedEnvelope<proto::GetChannelMessages>,
 922    ) -> tide::Result<proto::GetChannelMessagesResponse> {
 923        let user_id = self.state().user_id_for_connection(request.sender_id)?;
 924        let channel_id = ChannelId::from_proto(request.payload.channel_id);
 925        if !self
 926            .app_state
 927            .db
 928            .can_user_access_channel(user_id, channel_id)
 929            .await?
 930        {
 931            Err(anyhow!("access denied"))?;
 932        }
 933
 934        let messages = self
 935            .app_state
 936            .db
 937            .get_channel_messages(
 938                channel_id,
 939                MESSAGE_COUNT_PER_PAGE,
 940                Some(MessageId::from_proto(request.payload.before_message_id)),
 941            )
 942            .await?
 943            .into_iter()
 944            .map(|msg| proto::ChannelMessage {
 945                id: msg.id.to_proto(),
 946                body: msg.body,
 947                timestamp: msg.sent_at.unix_timestamp() as u64,
 948                sender_id: msg.sender_id.to_proto(),
 949                nonce: Some(msg.nonce.as_u128().into()),
 950            })
 951            .collect::<Vec<_>>();
 952
 953        Ok(proto::GetChannelMessagesResponse {
 954            done: messages.len() < MESSAGE_COUNT_PER_PAGE,
 955            messages,
 956        })
 957    }
 958
 959    fn state<'a>(self: &'a Arc<Self>) -> RwLockReadGuard<'a, Store> {
 960        self.store.read()
 961    }
 962
 963    fn state_mut<'a>(self: &'a mut Arc<Self>) -> RwLockWriteGuard<'a, Store> {
 964        self.store.write()
 965    }
 966}
 967
 968impl Executor for RealExecutor {
 969    type Timer = Timer;
 970
 971    fn spawn_detached<F: 'static + Send + Future<Output = ()>>(&self, future: F) {
 972        task::spawn(future);
 973    }
 974
 975    fn timer(&self, duration: Duration) -> Self::Timer {
 976        Timer::after(duration)
 977    }
 978}
 979
 980fn broadcast<F>(
 981    sender_id: ConnectionId,
 982    receiver_ids: Vec<ConnectionId>,
 983    mut f: F,
 984) -> anyhow::Result<()>
 985where
 986    F: FnMut(ConnectionId) -> anyhow::Result<()>,
 987{
 988    let mut result = Ok(());
 989    for receiver_id in receiver_ids {
 990        if receiver_id != sender_id {
 991            if let Err(error) = f(receiver_id) {
 992                if result.is_ok() {
 993                    result = Err(error);
 994                }
 995            }
 996        }
 997    }
 998    result
 999}
1000
1001pub fn add_routes(app: &mut tide::Server<Arc<AppState>>, rpc: &Arc<Peer>) {
1002    let server = Server::new(app.state().clone(), rpc.clone(), None);
1003    app.at("/rpc").get(move |request: Request<Arc<AppState>>| {
1004        let server = server.clone();
1005        async move {
1006            const WEBSOCKET_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
1007
1008            let connection_upgrade = header_contains_ignore_case(&request, CONNECTION, "upgrade");
1009            let upgrade_to_websocket = header_contains_ignore_case(&request, UPGRADE, "websocket");
1010            let upgrade_requested = connection_upgrade && upgrade_to_websocket;
1011            let client_protocol_version: Option<u32> = request
1012                .header("X-Zed-Protocol-Version")
1013                .and_then(|v| v.as_str().parse().ok());
1014
1015            if !upgrade_requested || client_protocol_version != Some(rpc::PROTOCOL_VERSION) {
1016                return Ok(Response::new(StatusCode::UpgradeRequired));
1017            }
1018
1019            let header = match request.header("Sec-Websocket-Key") {
1020                Some(h) => h.as_str(),
1021                None => return Err(anyhow!("expected sec-websocket-key"))?,
1022            };
1023
1024            let user_id = process_auth_header(&request).await?;
1025
1026            let mut response = Response::new(StatusCode::SwitchingProtocols);
1027            response.insert_header(UPGRADE, "websocket");
1028            response.insert_header(CONNECTION, "Upgrade");
1029            let hash = Sha1::new().chain(header).chain(WEBSOCKET_GUID).finalize();
1030            response.insert_header("Sec-Websocket-Accept", base64::encode(&hash[..]));
1031            response.insert_header("Sec-Websocket-Version", "13");
1032
1033            let http_res: &mut tide::http::Response = response.as_mut();
1034            let upgrade_receiver = http_res.recv_upgrade().await;
1035            let addr = request.remote().unwrap_or("unknown").to_string();
1036            task::spawn(async move {
1037                if let Some(stream) = upgrade_receiver.await {
1038                    server
1039                        .handle_connection(
1040                            Connection::new(
1041                                WebSocketStream::from_raw_socket(stream, Role::Server, None).await,
1042                            ),
1043                            addr,
1044                            user_id,
1045                            None,
1046                            RealExecutor,
1047                        )
1048                        .await;
1049                }
1050            });
1051
1052            Ok(response)
1053        }
1054    });
1055}
1056
1057fn header_contains_ignore_case<T>(
1058    request: &tide::Request<T>,
1059    header_name: HeaderName,
1060    value: &str,
1061) -> bool {
1062    request
1063        .header(header_name)
1064        .map(|h| {
1065            h.as_str()
1066                .split(',')
1067                .any(|s| s.trim().eq_ignore_ascii_case(value.trim()))
1068        })
1069        .unwrap_or(false)
1070}
1071
1072#[cfg(test)]
1073mod tests {
1074    use super::*;
1075    use crate::{
1076        auth,
1077        db::{tests::TestDb, UserId},
1078        github, AppState, Config,
1079    };
1080    use ::rpc::Peer;
1081    use client::{
1082        self, test::FakeHttpClient, Channel, ChannelDetails, ChannelList, Client, Credentials,
1083        EstablishConnectionError, UserStore,
1084    };
1085    use collections::BTreeMap;
1086    use editor::{
1087        self, ConfirmCodeAction, ConfirmCompletion, ConfirmRename, Editor, Input, Redo, Rename,
1088        ToOffset, ToggleCodeActions, Undo,
1089    };
1090    use gpui::{executor, geometry::vector::vec2f, ModelHandle, TestAppContext, ViewHandle};
1091    use language::{
1092        range_to_lsp, tree_sitter_rust, Diagnostic, DiagnosticEntry, FakeLspAdapter, Language,
1093        LanguageConfig, LanguageRegistry, OffsetRangeExt, Point, Rope,
1094    };
1095    use lsp::{self, FakeLanguageServer};
1096    use parking_lot::Mutex;
1097    use postage::barrier;
1098    use project::{
1099        fs::{FakeFs, Fs as _},
1100        search::SearchQuery,
1101        worktree::WorktreeHandle,
1102        DiagnosticSummary, Project, ProjectPath, WorktreeId,
1103    };
1104    use rand::prelude::*;
1105    use rpc::PeerId;
1106    use serde_json::json;
1107    use settings::Settings;
1108    use sqlx::types::time::OffsetDateTime;
1109    use std::{
1110        cell::Cell,
1111        env,
1112        ops::Deref,
1113        path::{Path, PathBuf},
1114        rc::Rc,
1115        sync::{
1116            atomic::{AtomicBool, Ordering::SeqCst},
1117            Arc,
1118        },
1119        time::Duration,
1120    };
1121    use workspace::{Item, SplitDirection, Workspace, WorkspaceParams};
1122
1123    #[cfg(test)]
1124    #[ctor::ctor]
1125    fn init_logger() {
1126        if std::env::var("RUST_LOG").is_ok() {
1127            env_logger::init();
1128        }
1129    }
1130
1131    #[gpui::test(iterations = 10)]
1132    async fn test_share_project(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
1133        let (window_b, _) = cx_b.add_window(|_| EmptyView);
1134        let lang_registry = Arc::new(LanguageRegistry::test());
1135        let fs = FakeFs::new(cx_a.background());
1136        cx_a.foreground().forbid_parking();
1137
1138        // Connect to a server as 2 clients.
1139        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1140        let client_a = server.create_client(cx_a, "user_a").await;
1141        let client_b = server.create_client(cx_b, "user_b").await;
1142
1143        // Share a project as client A
1144        fs.insert_tree(
1145            "/a",
1146            json!({
1147                ".zed.toml": r#"collaborators = ["user_b"]"#,
1148                "a.txt": "a-contents",
1149                "b.txt": "b-contents",
1150            }),
1151        )
1152        .await;
1153        let project_a = cx_a.update(|cx| {
1154            Project::local(
1155                client_a.clone(),
1156                client_a.user_store.clone(),
1157                lang_registry.clone(),
1158                fs.clone(),
1159                cx,
1160            )
1161        });
1162        let (worktree_a, _) = project_a
1163            .update(cx_a, |p, cx| {
1164                p.find_or_create_local_worktree("/a", true, cx)
1165            })
1166            .await
1167            .unwrap();
1168        let worktree_id = worktree_a.read_with(cx_a, |tree, _| tree.id());
1169        worktree_a
1170            .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1171            .await;
1172        let project_id = project_a.update(cx_a, |p, _| p.next_remote_id()).await;
1173        project_a.update(cx_a, |p, cx| p.share(cx)).await.unwrap();
1174
1175        // Join that project as client B
1176        let project_b = Project::remote(
1177            project_id,
1178            client_b.clone(),
1179            client_b.user_store.clone(),
1180            lang_registry.clone(),
1181            fs.clone(),
1182            &mut cx_b.to_async(),
1183        )
1184        .await
1185        .unwrap();
1186
1187        let replica_id_b = project_b.read_with(cx_b, |project, _| {
1188            assert_eq!(
1189                project
1190                    .collaborators()
1191                    .get(&client_a.peer_id)
1192                    .unwrap()
1193                    .user
1194                    .github_login,
1195                "user_a"
1196            );
1197            project.replica_id()
1198        });
1199        project_a
1200            .condition(&cx_a, |tree, _| {
1201                tree.collaborators()
1202                    .get(&client_b.peer_id)
1203                    .map_or(false, |collaborator| {
1204                        collaborator.replica_id == replica_id_b
1205                            && collaborator.user.github_login == "user_b"
1206                    })
1207            })
1208            .await;
1209
1210        // Open the same file as client B and client A.
1211        let buffer_b = project_b
1212            .update(cx_b, |p, cx| p.open_buffer((worktree_id, "b.txt"), cx))
1213            .await
1214            .unwrap();
1215        buffer_b.read_with(cx_b, |buf, _| assert_eq!(buf.text(), "b-contents"));
1216        project_a.read_with(cx_a, |project, cx| {
1217            assert!(project.has_open_buffer((worktree_id, "b.txt"), cx))
1218        });
1219        let buffer_a = project_a
1220            .update(cx_a, |p, cx| p.open_buffer((worktree_id, "b.txt"), cx))
1221            .await
1222            .unwrap();
1223
1224        let editor_b = cx_b.add_view(window_b, |cx| Editor::for_buffer(buffer_b, None, cx));
1225
1226        // TODO
1227        // // Create a selection set as client B and see that selection set as client A.
1228        // buffer_a
1229        //     .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 1)
1230        //     .await;
1231
1232        // Edit the buffer as client B and see that edit as client A.
1233        editor_b.update(cx_b, |editor, cx| {
1234            editor.handle_input(&Input("ok, ".into()), cx)
1235        });
1236        buffer_a
1237            .condition(&cx_a, |buffer, _| buffer.text() == "ok, b-contents")
1238            .await;
1239
1240        // TODO
1241        // // Remove the selection set as client B, see those selections disappear as client A.
1242        cx_b.update(move |_| drop(editor_b));
1243        // buffer_a
1244        //     .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 0)
1245        //     .await;
1246
1247        // Dropping the client B's project removes client B from client A's collaborators.
1248        cx_b.update(move |_| drop(project_b));
1249        project_a
1250            .condition(&cx_a, |project, _| project.collaborators().is_empty())
1251            .await;
1252    }
1253
1254    #[gpui::test(iterations = 10)]
1255    async fn test_unshare_project(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
1256        let lang_registry = Arc::new(LanguageRegistry::test());
1257        let fs = FakeFs::new(cx_a.background());
1258        cx_a.foreground().forbid_parking();
1259
1260        // Connect to a server as 2 clients.
1261        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1262        let client_a = server.create_client(cx_a, "user_a").await;
1263        let client_b = server.create_client(cx_b, "user_b").await;
1264
1265        // Share a project as client A
1266        fs.insert_tree(
1267            "/a",
1268            json!({
1269                ".zed.toml": r#"collaborators = ["user_b"]"#,
1270                "a.txt": "a-contents",
1271                "b.txt": "b-contents",
1272            }),
1273        )
1274        .await;
1275        let project_a = cx_a.update(|cx| {
1276            Project::local(
1277                client_a.clone(),
1278                client_a.user_store.clone(),
1279                lang_registry.clone(),
1280                fs.clone(),
1281                cx,
1282            )
1283        });
1284        let (worktree_a, _) = project_a
1285            .update(cx_a, |p, cx| {
1286                p.find_or_create_local_worktree("/a", true, cx)
1287            })
1288            .await
1289            .unwrap();
1290        worktree_a
1291            .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1292            .await;
1293        let project_id = project_a.update(cx_a, |p, _| p.next_remote_id()).await;
1294        let worktree_id = worktree_a.read_with(cx_a, |tree, _| tree.id());
1295        project_a.update(cx_a, |p, cx| p.share(cx)).await.unwrap();
1296        assert!(worktree_a.read_with(cx_a, |tree, _| tree.as_local().unwrap().is_shared()));
1297
1298        // Join that project as client B
1299        let project_b = Project::remote(
1300            project_id,
1301            client_b.clone(),
1302            client_b.user_store.clone(),
1303            lang_registry.clone(),
1304            fs.clone(),
1305            &mut cx_b.to_async(),
1306        )
1307        .await
1308        .unwrap();
1309        project_b
1310            .update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1311            .await
1312            .unwrap();
1313
1314        // Unshare the project as client A
1315        project_a.update(cx_a, |project, cx| project.unshare(cx));
1316        project_b
1317            .condition(cx_b, |project, _| project.is_read_only())
1318            .await;
1319        assert!(worktree_a.read_with(cx_a, |tree, _| !tree.as_local().unwrap().is_shared()));
1320        cx_b.update(|_| {
1321            drop(project_b);
1322        });
1323
1324        // Share the project again and ensure guests can still join.
1325        project_a
1326            .update(cx_a, |project, cx| project.share(cx))
1327            .await
1328            .unwrap();
1329        assert!(worktree_a.read_with(cx_a, |tree, _| tree.as_local().unwrap().is_shared()));
1330
1331        let project_b2 = Project::remote(
1332            project_id,
1333            client_b.clone(),
1334            client_b.user_store.clone(),
1335            lang_registry.clone(),
1336            fs.clone(),
1337            &mut cx_b.to_async(),
1338        )
1339        .await
1340        .unwrap();
1341        project_b2
1342            .update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1343            .await
1344            .unwrap();
1345    }
1346
1347    #[gpui::test(iterations = 10)]
1348    async fn test_host_disconnect(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
1349        let lang_registry = Arc::new(LanguageRegistry::test());
1350        let fs = FakeFs::new(cx_a.background());
1351        cx_a.foreground().forbid_parking();
1352
1353        // Connect to a server as 2 clients.
1354        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1355        let client_a = server.create_client(cx_a, "user_a").await;
1356        let client_b = server.create_client(cx_b, "user_b").await;
1357
1358        // Share a project as client A
1359        fs.insert_tree(
1360            "/a",
1361            json!({
1362                ".zed.toml": r#"collaborators = ["user_b"]"#,
1363                "a.txt": "a-contents",
1364                "b.txt": "b-contents",
1365            }),
1366        )
1367        .await;
1368        let project_a = cx_a.update(|cx| {
1369            Project::local(
1370                client_a.clone(),
1371                client_a.user_store.clone(),
1372                lang_registry.clone(),
1373                fs.clone(),
1374                cx,
1375            )
1376        });
1377        let (worktree_a, _) = project_a
1378            .update(cx_a, |p, cx| {
1379                p.find_or_create_local_worktree("/a", true, cx)
1380            })
1381            .await
1382            .unwrap();
1383        worktree_a
1384            .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1385            .await;
1386        let project_id = project_a.update(cx_a, |p, _| p.next_remote_id()).await;
1387        let worktree_id = worktree_a.read_with(cx_a, |tree, _| tree.id());
1388        project_a.update(cx_a, |p, cx| p.share(cx)).await.unwrap();
1389        assert!(worktree_a.read_with(cx_a, |tree, _| tree.as_local().unwrap().is_shared()));
1390
1391        // Join that project as client B
1392        let project_b = Project::remote(
1393            project_id,
1394            client_b.clone(),
1395            client_b.user_store.clone(),
1396            lang_registry.clone(),
1397            fs.clone(),
1398            &mut cx_b.to_async(),
1399        )
1400        .await
1401        .unwrap();
1402        project_b
1403            .update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1404            .await
1405            .unwrap();
1406
1407        // Drop client A's connection. Collaborators should disappear and the project should not be shown as shared.
1408        server.disconnect_client(client_a.current_user_id(cx_a));
1409        cx_a.foreground().advance_clock(rpc::RECEIVE_TIMEOUT);
1410        project_a
1411            .condition(cx_a, |project, _| project.collaborators().is_empty())
1412            .await;
1413        project_a.read_with(cx_a, |project, _| assert!(!project.is_shared()));
1414        project_b
1415            .condition(cx_b, |project, _| project.is_read_only())
1416            .await;
1417        assert!(worktree_a.read_with(cx_a, |tree, _| !tree.as_local().unwrap().is_shared()));
1418        cx_b.update(|_| {
1419            drop(project_b);
1420        });
1421
1422        // Await reconnection
1423        let project_id = project_a.update(cx_a, |p, _| p.next_remote_id()).await;
1424
1425        // Share the project again and ensure guests can still join.
1426        project_a
1427            .update(cx_a, |project, cx| project.share(cx))
1428            .await
1429            .unwrap();
1430        assert!(worktree_a.read_with(cx_a, |tree, _| tree.as_local().unwrap().is_shared()));
1431
1432        let project_b2 = Project::remote(
1433            project_id,
1434            client_b.clone(),
1435            client_b.user_store.clone(),
1436            lang_registry.clone(),
1437            fs.clone(),
1438            &mut cx_b.to_async(),
1439        )
1440        .await
1441        .unwrap();
1442        project_b2
1443            .update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1444            .await
1445            .unwrap();
1446    }
1447
1448    #[gpui::test(iterations = 10)]
1449    async fn test_propagate_saves_and_fs_changes(
1450        cx_a: &mut TestAppContext,
1451        cx_b: &mut TestAppContext,
1452        cx_c: &mut TestAppContext,
1453    ) {
1454        let lang_registry = Arc::new(LanguageRegistry::test());
1455        let fs = FakeFs::new(cx_a.background());
1456        cx_a.foreground().forbid_parking();
1457
1458        // Connect to a server as 3 clients.
1459        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1460        let client_a = server.create_client(cx_a, "user_a").await;
1461        let client_b = server.create_client(cx_b, "user_b").await;
1462        let client_c = server.create_client(cx_c, "user_c").await;
1463
1464        // Share a worktree as client A.
1465        fs.insert_tree(
1466            "/a",
1467            json!({
1468                ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
1469                "file1": "",
1470                "file2": ""
1471            }),
1472        )
1473        .await;
1474        let project_a = cx_a.update(|cx| {
1475            Project::local(
1476                client_a.clone(),
1477                client_a.user_store.clone(),
1478                lang_registry.clone(),
1479                fs.clone(),
1480                cx,
1481            )
1482        });
1483        let (worktree_a, _) = project_a
1484            .update(cx_a, |p, cx| {
1485                p.find_or_create_local_worktree("/a", true, cx)
1486            })
1487            .await
1488            .unwrap();
1489        worktree_a
1490            .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1491            .await;
1492        let project_id = project_a.update(cx_a, |p, _| p.next_remote_id()).await;
1493        let worktree_id = worktree_a.read_with(cx_a, |tree, _| tree.id());
1494        project_a.update(cx_a, |p, cx| p.share(cx)).await.unwrap();
1495
1496        // Join that worktree as clients B and C.
1497        let project_b = Project::remote(
1498            project_id,
1499            client_b.clone(),
1500            client_b.user_store.clone(),
1501            lang_registry.clone(),
1502            fs.clone(),
1503            &mut cx_b.to_async(),
1504        )
1505        .await
1506        .unwrap();
1507        let project_c = Project::remote(
1508            project_id,
1509            client_c.clone(),
1510            client_c.user_store.clone(),
1511            lang_registry.clone(),
1512            fs.clone(),
1513            &mut cx_c.to_async(),
1514        )
1515        .await
1516        .unwrap();
1517        let worktree_b = project_b.read_with(cx_b, |p, cx| p.worktrees(cx).next().unwrap());
1518        let worktree_c = project_c.read_with(cx_c, |p, cx| p.worktrees(cx).next().unwrap());
1519
1520        // Open and edit a buffer as both guests B and C.
1521        let buffer_b = project_b
1522            .update(cx_b, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
1523            .await
1524            .unwrap();
1525        let buffer_c = project_c
1526            .update(cx_c, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
1527            .await
1528            .unwrap();
1529        buffer_b.update(cx_b, |buf, cx| buf.edit([0..0], "i-am-b, ", cx));
1530        buffer_c.update(cx_c, |buf, cx| buf.edit([0..0], "i-am-c, ", cx));
1531
1532        // Open and edit that buffer as the host.
1533        let buffer_a = project_a
1534            .update(cx_a, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
1535            .await
1536            .unwrap();
1537
1538        buffer_a
1539            .condition(cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, ")
1540            .await;
1541        buffer_a.update(cx_a, |buf, cx| {
1542            buf.edit([buf.len()..buf.len()], "i-am-a", cx)
1543        });
1544
1545        // Wait for edits to propagate
1546        buffer_a
1547            .condition(cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1548            .await;
1549        buffer_b
1550            .condition(cx_b, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1551            .await;
1552        buffer_c
1553            .condition(cx_c, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1554            .await;
1555
1556        // Edit the buffer as the host and concurrently save as guest B.
1557        let save_b = buffer_b.update(cx_b, |buf, cx| buf.save(cx));
1558        buffer_a.update(cx_a, |buf, cx| buf.edit([0..0], "hi-a, ", cx));
1559        save_b.await.unwrap();
1560        assert_eq!(
1561            fs.load("/a/file1".as_ref()).await.unwrap(),
1562            "hi-a, i-am-c, i-am-b, i-am-a"
1563        );
1564        buffer_a.read_with(cx_a, |buf, _| assert!(!buf.is_dirty()));
1565        buffer_b.read_with(cx_b, |buf, _| assert!(!buf.is_dirty()));
1566        buffer_c.condition(cx_c, |buf, _| !buf.is_dirty()).await;
1567
1568        worktree_a.flush_fs_events(cx_a).await;
1569
1570        // Make changes on host's file system, see those changes on guest worktrees.
1571        fs.rename(
1572            "/a/file1".as_ref(),
1573            "/a/file1-renamed".as_ref(),
1574            Default::default(),
1575        )
1576        .await
1577        .unwrap();
1578
1579        fs.rename("/a/file2".as_ref(), "/a/file3".as_ref(), Default::default())
1580            .await
1581            .unwrap();
1582        fs.insert_file(Path::new("/a/file4"), "4".into()).await;
1583
1584        worktree_a
1585            .condition(&cx_a, |tree, _| {
1586                tree.paths()
1587                    .map(|p| p.to_string_lossy())
1588                    .collect::<Vec<_>>()
1589                    == [".zed.toml", "file1-renamed", "file3", "file4"]
1590            })
1591            .await;
1592        worktree_b
1593            .condition(&cx_b, |tree, _| {
1594                tree.paths()
1595                    .map(|p| p.to_string_lossy())
1596                    .collect::<Vec<_>>()
1597                    == [".zed.toml", "file1-renamed", "file3", "file4"]
1598            })
1599            .await;
1600        worktree_c
1601            .condition(&cx_c, |tree, _| {
1602                tree.paths()
1603                    .map(|p| p.to_string_lossy())
1604                    .collect::<Vec<_>>()
1605                    == [".zed.toml", "file1-renamed", "file3", "file4"]
1606            })
1607            .await;
1608
1609        // Ensure buffer files are updated as well.
1610        buffer_a
1611            .condition(&cx_a, |buf, _| {
1612                buf.file().unwrap().path().to_str() == Some("file1-renamed")
1613            })
1614            .await;
1615        buffer_b
1616            .condition(&cx_b, |buf, _| {
1617                buf.file().unwrap().path().to_str() == Some("file1-renamed")
1618            })
1619            .await;
1620        buffer_c
1621            .condition(&cx_c, |buf, _| {
1622                buf.file().unwrap().path().to_str() == Some("file1-renamed")
1623            })
1624            .await;
1625    }
1626
1627    #[gpui::test(iterations = 10)]
1628    async fn test_buffer_conflict_after_save(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
1629        cx_a.foreground().forbid_parking();
1630        let lang_registry = Arc::new(LanguageRegistry::test());
1631        let fs = FakeFs::new(cx_a.background());
1632
1633        // Connect to a server as 2 clients.
1634        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1635        let client_a = server.create_client(cx_a, "user_a").await;
1636        let client_b = server.create_client(cx_b, "user_b").await;
1637
1638        // Share a project as client A
1639        fs.insert_tree(
1640            "/dir",
1641            json!({
1642                ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
1643                "a.txt": "a-contents",
1644            }),
1645        )
1646        .await;
1647
1648        let project_a = cx_a.update(|cx| {
1649            Project::local(
1650                client_a.clone(),
1651                client_a.user_store.clone(),
1652                lang_registry.clone(),
1653                fs.clone(),
1654                cx,
1655            )
1656        });
1657        let (worktree_a, _) = project_a
1658            .update(cx_a, |p, cx| {
1659                p.find_or_create_local_worktree("/dir", true, cx)
1660            })
1661            .await
1662            .unwrap();
1663        worktree_a
1664            .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1665            .await;
1666        let project_id = project_a.update(cx_a, |p, _| p.next_remote_id()).await;
1667        let worktree_id = worktree_a.read_with(cx_a, |tree, _| tree.id());
1668        project_a.update(cx_a, |p, cx| p.share(cx)).await.unwrap();
1669
1670        // Join that project as client B
1671        let project_b = Project::remote(
1672            project_id,
1673            client_b.clone(),
1674            client_b.user_store.clone(),
1675            lang_registry.clone(),
1676            fs.clone(),
1677            &mut cx_b.to_async(),
1678        )
1679        .await
1680        .unwrap();
1681
1682        // Open a buffer as client B
1683        let buffer_b = project_b
1684            .update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1685            .await
1686            .unwrap();
1687
1688        buffer_b.update(cx_b, |buf, cx| buf.edit([0..0], "world ", cx));
1689        buffer_b.read_with(cx_b, |buf, _| {
1690            assert!(buf.is_dirty());
1691            assert!(!buf.has_conflict());
1692        });
1693
1694        buffer_b.update(cx_b, |buf, cx| buf.save(cx)).await.unwrap();
1695        buffer_b
1696            .condition(&cx_b, |buffer_b, _| !buffer_b.is_dirty())
1697            .await;
1698        buffer_b.read_with(cx_b, |buf, _| {
1699            assert!(!buf.has_conflict());
1700        });
1701
1702        buffer_b.update(cx_b, |buf, cx| buf.edit([0..0], "hello ", cx));
1703        buffer_b.read_with(cx_b, |buf, _| {
1704            assert!(buf.is_dirty());
1705            assert!(!buf.has_conflict());
1706        });
1707    }
1708
1709    #[gpui::test(iterations = 10)]
1710    async fn test_buffer_reloading(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
1711        cx_a.foreground().forbid_parking();
1712        let lang_registry = Arc::new(LanguageRegistry::test());
1713        let fs = FakeFs::new(cx_a.background());
1714
1715        // Connect to a server as 2 clients.
1716        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1717        let client_a = server.create_client(cx_a, "user_a").await;
1718        let client_b = server.create_client(cx_b, "user_b").await;
1719
1720        // Share a project as client A
1721        fs.insert_tree(
1722            "/dir",
1723            json!({
1724                ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
1725                "a.txt": "a-contents",
1726            }),
1727        )
1728        .await;
1729
1730        let project_a = cx_a.update(|cx| {
1731            Project::local(
1732                client_a.clone(),
1733                client_a.user_store.clone(),
1734                lang_registry.clone(),
1735                fs.clone(),
1736                cx,
1737            )
1738        });
1739        let (worktree_a, _) = project_a
1740            .update(cx_a, |p, cx| {
1741                p.find_or_create_local_worktree("/dir", true, cx)
1742            })
1743            .await
1744            .unwrap();
1745        worktree_a
1746            .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1747            .await;
1748        let project_id = project_a.update(cx_a, |p, _| p.next_remote_id()).await;
1749        let worktree_id = worktree_a.read_with(cx_a, |tree, _| tree.id());
1750        project_a.update(cx_a, |p, cx| p.share(cx)).await.unwrap();
1751
1752        // Join that project as client B
1753        let project_b = Project::remote(
1754            project_id,
1755            client_b.clone(),
1756            client_b.user_store.clone(),
1757            lang_registry.clone(),
1758            fs.clone(),
1759            &mut cx_b.to_async(),
1760        )
1761        .await
1762        .unwrap();
1763        let _worktree_b = project_b.update(cx_b, |p, cx| p.worktrees(cx).next().unwrap());
1764
1765        // Open a buffer as client B
1766        let buffer_b = project_b
1767            .update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1768            .await
1769            .unwrap();
1770        buffer_b.read_with(cx_b, |buf, _| {
1771            assert!(!buf.is_dirty());
1772            assert!(!buf.has_conflict());
1773        });
1774
1775        fs.save(Path::new("/dir/a.txt"), &"new contents".into())
1776            .await
1777            .unwrap();
1778        buffer_b
1779            .condition(&cx_b, |buf, _| {
1780                buf.text() == "new contents" && !buf.is_dirty()
1781            })
1782            .await;
1783        buffer_b.read_with(cx_b, |buf, _| {
1784            assert!(!buf.has_conflict());
1785        });
1786    }
1787
1788    #[gpui::test(iterations = 10)]
1789    async fn test_editing_while_guest_opens_buffer(
1790        cx_a: &mut TestAppContext,
1791        cx_b: &mut TestAppContext,
1792    ) {
1793        cx_a.foreground().forbid_parking();
1794        let lang_registry = Arc::new(LanguageRegistry::test());
1795        let fs = FakeFs::new(cx_a.background());
1796
1797        // Connect to a server as 2 clients.
1798        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1799        let client_a = server.create_client(cx_a, "user_a").await;
1800        let client_b = server.create_client(cx_b, "user_b").await;
1801
1802        // Share a project as client A
1803        fs.insert_tree(
1804            "/dir",
1805            json!({
1806                ".zed.toml": r#"collaborators = ["user_b"]"#,
1807                "a.txt": "a-contents",
1808            }),
1809        )
1810        .await;
1811        let project_a = cx_a.update(|cx| {
1812            Project::local(
1813                client_a.clone(),
1814                client_a.user_store.clone(),
1815                lang_registry.clone(),
1816                fs.clone(),
1817                cx,
1818            )
1819        });
1820        let (worktree_a, _) = project_a
1821            .update(cx_a, |p, cx| {
1822                p.find_or_create_local_worktree("/dir", true, cx)
1823            })
1824            .await
1825            .unwrap();
1826        worktree_a
1827            .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1828            .await;
1829        let project_id = project_a.update(cx_a, |p, _| p.next_remote_id()).await;
1830        let worktree_id = worktree_a.read_with(cx_a, |tree, _| tree.id());
1831        project_a.update(cx_a, |p, cx| p.share(cx)).await.unwrap();
1832
1833        // Join that project as client B
1834        let project_b = Project::remote(
1835            project_id,
1836            client_b.clone(),
1837            client_b.user_store.clone(),
1838            lang_registry.clone(),
1839            fs.clone(),
1840            &mut cx_b.to_async(),
1841        )
1842        .await
1843        .unwrap();
1844
1845        // Open a buffer as client A
1846        let buffer_a = project_a
1847            .update(cx_a, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1848            .await
1849            .unwrap();
1850
1851        // Start opening the same buffer as client B
1852        let buffer_b = cx_b
1853            .background()
1854            .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx)));
1855
1856        // Edit the buffer as client A while client B is still opening it.
1857        cx_b.background().simulate_random_delay().await;
1858        buffer_a.update(cx_a, |buf, cx| buf.edit([0..0], "X", cx));
1859        cx_b.background().simulate_random_delay().await;
1860        buffer_a.update(cx_a, |buf, cx| buf.edit([1..1], "Y", cx));
1861
1862        let text = buffer_a.read_with(cx_a, |buf, _| buf.text());
1863        let buffer_b = buffer_b.await.unwrap();
1864        buffer_b.condition(&cx_b, |buf, _| buf.text() == text).await;
1865    }
1866
1867    #[gpui::test(iterations = 10)]
1868    async fn test_leaving_worktree_while_opening_buffer(
1869        cx_a: &mut TestAppContext,
1870        cx_b: &mut TestAppContext,
1871    ) {
1872        cx_a.foreground().forbid_parking();
1873        let lang_registry = Arc::new(LanguageRegistry::test());
1874        let fs = FakeFs::new(cx_a.background());
1875
1876        // Connect to a server as 2 clients.
1877        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1878        let client_a = server.create_client(cx_a, "user_a").await;
1879        let client_b = server.create_client(cx_b, "user_b").await;
1880
1881        // Share a project as client A
1882        fs.insert_tree(
1883            "/dir",
1884            json!({
1885                ".zed.toml": r#"collaborators = ["user_b"]"#,
1886                "a.txt": "a-contents",
1887            }),
1888        )
1889        .await;
1890        let project_a = cx_a.update(|cx| {
1891            Project::local(
1892                client_a.clone(),
1893                client_a.user_store.clone(),
1894                lang_registry.clone(),
1895                fs.clone(),
1896                cx,
1897            )
1898        });
1899        let (worktree_a, _) = project_a
1900            .update(cx_a, |p, cx| {
1901                p.find_or_create_local_worktree("/dir", true, cx)
1902            })
1903            .await
1904            .unwrap();
1905        worktree_a
1906            .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1907            .await;
1908        let project_id = project_a.update(cx_a, |p, _| p.next_remote_id()).await;
1909        let worktree_id = worktree_a.read_with(cx_a, |tree, _| tree.id());
1910        project_a.update(cx_a, |p, cx| p.share(cx)).await.unwrap();
1911
1912        // Join that project as client B
1913        let project_b = Project::remote(
1914            project_id,
1915            client_b.clone(),
1916            client_b.user_store.clone(),
1917            lang_registry.clone(),
1918            fs.clone(),
1919            &mut cx_b.to_async(),
1920        )
1921        .await
1922        .unwrap();
1923
1924        // See that a guest has joined as client A.
1925        project_a
1926            .condition(&cx_a, |p, _| p.collaborators().len() == 1)
1927            .await;
1928
1929        // Begin opening a buffer as client B, but leave the project before the open completes.
1930        let buffer_b = cx_b
1931            .background()
1932            .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx)));
1933        cx_b.update(|_| drop(project_b));
1934        drop(buffer_b);
1935
1936        // See that the guest has left.
1937        project_a
1938            .condition(&cx_a, |p, _| p.collaborators().len() == 0)
1939            .await;
1940    }
1941
1942    #[gpui::test(iterations = 10)]
1943    async fn test_leaving_project(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
1944        cx_a.foreground().forbid_parking();
1945        let lang_registry = Arc::new(LanguageRegistry::test());
1946        let fs = FakeFs::new(cx_a.background());
1947
1948        // Connect to a server as 2 clients.
1949        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1950        let client_a = server.create_client(cx_a, "user_a").await;
1951        let client_b = server.create_client(cx_b, "user_b").await;
1952
1953        // Share a project as client A
1954        fs.insert_tree(
1955            "/a",
1956            json!({
1957                ".zed.toml": r#"collaborators = ["user_b"]"#,
1958                "a.txt": "a-contents",
1959                "b.txt": "b-contents",
1960            }),
1961        )
1962        .await;
1963        let project_a = cx_a.update(|cx| {
1964            Project::local(
1965                client_a.clone(),
1966                client_a.user_store.clone(),
1967                lang_registry.clone(),
1968                fs.clone(),
1969                cx,
1970            )
1971        });
1972        let (worktree_a, _) = project_a
1973            .update(cx_a, |p, cx| {
1974                p.find_or_create_local_worktree("/a", true, cx)
1975            })
1976            .await
1977            .unwrap();
1978        worktree_a
1979            .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1980            .await;
1981        let project_id = project_a
1982            .update(cx_a, |project, _| project.next_remote_id())
1983            .await;
1984        project_a
1985            .update(cx_a, |project, cx| project.share(cx))
1986            .await
1987            .unwrap();
1988
1989        // Join that project as client B
1990        let _project_b = Project::remote(
1991            project_id,
1992            client_b.clone(),
1993            client_b.user_store.clone(),
1994            lang_registry.clone(),
1995            fs.clone(),
1996            &mut cx_b.to_async(),
1997        )
1998        .await
1999        .unwrap();
2000
2001        // Client A sees that a guest has joined.
2002        project_a
2003            .condition(cx_a, |p, _| p.collaborators().len() == 1)
2004            .await;
2005
2006        // Drop client B's connection and ensure client A observes client B leaving the project.
2007        client_b.disconnect(&cx_b.to_async()).unwrap();
2008        project_a
2009            .condition(cx_a, |p, _| p.collaborators().len() == 0)
2010            .await;
2011
2012        // Rejoin the project as client B
2013        let _project_b = Project::remote(
2014            project_id,
2015            client_b.clone(),
2016            client_b.user_store.clone(),
2017            lang_registry.clone(),
2018            fs.clone(),
2019            &mut cx_b.to_async(),
2020        )
2021        .await
2022        .unwrap();
2023
2024        // Client A sees that a guest has re-joined.
2025        project_a
2026            .condition(cx_a, |p, _| p.collaborators().len() == 1)
2027            .await;
2028
2029        // Simulate connection loss for client B and ensure client A observes client B leaving the project.
2030        client_b.wait_for_current_user(cx_b).await;
2031        server.disconnect_client(client_b.current_user_id(cx_b));
2032        cx_a.foreground().advance_clock(Duration::from_secs(3));
2033        project_a
2034            .condition(cx_a, |p, _| p.collaborators().len() == 0)
2035            .await;
2036    }
2037
2038    #[gpui::test(iterations = 10)]
2039    async fn test_collaborating_with_diagnostics(
2040        cx_a: &mut TestAppContext,
2041        cx_b: &mut TestAppContext,
2042    ) {
2043        cx_a.foreground().forbid_parking();
2044        let lang_registry = Arc::new(LanguageRegistry::test());
2045        let fs = FakeFs::new(cx_a.background());
2046
2047        // Set up a fake language server.
2048        let mut language = Language::new(
2049            LanguageConfig {
2050                name: "Rust".into(),
2051                path_suffixes: vec!["rs".to_string()],
2052                ..Default::default()
2053            },
2054            Some(tree_sitter_rust::language()),
2055        );
2056        let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default());
2057        lang_registry.add(Arc::new(language));
2058
2059        // Connect to a server as 2 clients.
2060        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
2061        let client_a = server.create_client(cx_a, "user_a").await;
2062        let client_b = server.create_client(cx_b, "user_b").await;
2063
2064        // Share a project as client A
2065        fs.insert_tree(
2066            "/a",
2067            json!({
2068                ".zed.toml": r#"collaborators = ["user_b"]"#,
2069                "a.rs": "let one = two",
2070                "other.rs": "",
2071            }),
2072        )
2073        .await;
2074        let project_a = cx_a.update(|cx| {
2075            Project::local(
2076                client_a.clone(),
2077                client_a.user_store.clone(),
2078                lang_registry.clone(),
2079                fs.clone(),
2080                cx,
2081            )
2082        });
2083        let (worktree_a, _) = project_a
2084            .update(cx_a, |p, cx| {
2085                p.find_or_create_local_worktree("/a", true, cx)
2086            })
2087            .await
2088            .unwrap();
2089        worktree_a
2090            .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2091            .await;
2092        let project_id = project_a.update(cx_a, |p, _| p.next_remote_id()).await;
2093        let worktree_id = worktree_a.read_with(cx_a, |tree, _| tree.id());
2094        project_a.update(cx_a, |p, cx| p.share(cx)).await.unwrap();
2095
2096        // Cause the language server to start.
2097        let _ = cx_a
2098            .background()
2099            .spawn(project_a.update(cx_a, |project, cx| {
2100                project.open_buffer(
2101                    ProjectPath {
2102                        worktree_id,
2103                        path: Path::new("other.rs").into(),
2104                    },
2105                    cx,
2106                )
2107            }))
2108            .await
2109            .unwrap();
2110
2111        // Simulate a language server reporting errors for a file.
2112        let mut fake_language_server = fake_language_servers.next().await.unwrap();
2113        fake_language_server
2114            .receive_notification::<lsp::notification::DidOpenTextDocument>()
2115            .await;
2116        fake_language_server.notify::<lsp::notification::PublishDiagnostics>(
2117            lsp::PublishDiagnosticsParams {
2118                uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
2119                version: None,
2120                diagnostics: vec![lsp::Diagnostic {
2121                    severity: Some(lsp::DiagnosticSeverity::ERROR),
2122                    range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
2123                    message: "message 1".to_string(),
2124                    ..Default::default()
2125                }],
2126            },
2127        );
2128
2129        // Wait for server to see the diagnostics update.
2130        server
2131            .condition(|store| {
2132                let worktree = store
2133                    .project(project_id)
2134                    .unwrap()
2135                    .share
2136                    .as_ref()
2137                    .unwrap()
2138                    .worktrees
2139                    .get(&worktree_id.to_proto())
2140                    .unwrap();
2141
2142                !worktree.diagnostic_summaries.is_empty()
2143            })
2144            .await;
2145
2146        // Join the worktree as client B.
2147        let project_b = Project::remote(
2148            project_id,
2149            client_b.clone(),
2150            client_b.user_store.clone(),
2151            lang_registry.clone(),
2152            fs.clone(),
2153            &mut cx_b.to_async(),
2154        )
2155        .await
2156        .unwrap();
2157
2158        project_b.read_with(cx_b, |project, cx| {
2159            assert_eq!(
2160                project.diagnostic_summaries(cx).collect::<Vec<_>>(),
2161                &[(
2162                    ProjectPath {
2163                        worktree_id,
2164                        path: Arc::from(Path::new("a.rs")),
2165                    },
2166                    DiagnosticSummary {
2167                        error_count: 1,
2168                        warning_count: 0,
2169                        ..Default::default()
2170                    },
2171                )]
2172            )
2173        });
2174
2175        // Simulate a language server reporting more errors for a file.
2176        fake_language_server.notify::<lsp::notification::PublishDiagnostics>(
2177            lsp::PublishDiagnosticsParams {
2178                uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
2179                version: None,
2180                diagnostics: vec![
2181                    lsp::Diagnostic {
2182                        severity: Some(lsp::DiagnosticSeverity::ERROR),
2183                        range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
2184                        message: "message 1".to_string(),
2185                        ..Default::default()
2186                    },
2187                    lsp::Diagnostic {
2188                        severity: Some(lsp::DiagnosticSeverity::WARNING),
2189                        range: lsp::Range::new(
2190                            lsp::Position::new(0, 10),
2191                            lsp::Position::new(0, 13),
2192                        ),
2193                        message: "message 2".to_string(),
2194                        ..Default::default()
2195                    },
2196                ],
2197            },
2198        );
2199
2200        // Client b gets the updated summaries
2201        project_b
2202            .condition(&cx_b, |project, cx| {
2203                project.diagnostic_summaries(cx).collect::<Vec<_>>()
2204                    == &[(
2205                        ProjectPath {
2206                            worktree_id,
2207                            path: Arc::from(Path::new("a.rs")),
2208                        },
2209                        DiagnosticSummary {
2210                            error_count: 1,
2211                            warning_count: 1,
2212                            ..Default::default()
2213                        },
2214                    )]
2215            })
2216            .await;
2217
2218        // Open the file with the errors on client B. They should be present.
2219        let buffer_b = cx_b
2220            .background()
2221            .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
2222            .await
2223            .unwrap();
2224
2225        buffer_b.read_with(cx_b, |buffer, _| {
2226            assert_eq!(
2227                buffer
2228                    .snapshot()
2229                    .diagnostics_in_range::<_, Point>(0..buffer.len(), false)
2230                    .map(|entry| entry)
2231                    .collect::<Vec<_>>(),
2232                &[
2233                    DiagnosticEntry {
2234                        range: Point::new(0, 4)..Point::new(0, 7),
2235                        diagnostic: Diagnostic {
2236                            group_id: 0,
2237                            message: "message 1".to_string(),
2238                            severity: lsp::DiagnosticSeverity::ERROR,
2239                            is_primary: true,
2240                            ..Default::default()
2241                        }
2242                    },
2243                    DiagnosticEntry {
2244                        range: Point::new(0, 10)..Point::new(0, 13),
2245                        diagnostic: Diagnostic {
2246                            group_id: 1,
2247                            severity: lsp::DiagnosticSeverity::WARNING,
2248                            message: "message 2".to_string(),
2249                            is_primary: true,
2250                            ..Default::default()
2251                        }
2252                    }
2253                ]
2254            );
2255        });
2256    }
2257
2258    #[gpui::test(iterations = 10)]
2259    async fn test_collaborating_with_completion(
2260        cx_a: &mut TestAppContext,
2261        cx_b: &mut TestAppContext,
2262    ) {
2263        cx_a.foreground().forbid_parking();
2264        let lang_registry = Arc::new(LanguageRegistry::test());
2265        let fs = FakeFs::new(cx_a.background());
2266
2267        // Set up a fake language server.
2268        let mut language = Language::new(
2269            LanguageConfig {
2270                name: "Rust".into(),
2271                path_suffixes: vec!["rs".to_string()],
2272                ..Default::default()
2273            },
2274            Some(tree_sitter_rust::language()),
2275        );
2276        let mut fake_language_servers = language.set_fake_lsp_adapter(FakeLspAdapter {
2277            capabilities: lsp::ServerCapabilities {
2278                completion_provider: Some(lsp::CompletionOptions {
2279                    trigger_characters: Some(vec![".".to_string()]),
2280                    ..Default::default()
2281                }),
2282                ..Default::default()
2283            },
2284            ..Default::default()
2285        });
2286        lang_registry.add(Arc::new(language));
2287
2288        // Connect to a server as 2 clients.
2289        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
2290        let client_a = server.create_client(cx_a, "user_a").await;
2291        let client_b = server.create_client(cx_b, "user_b").await;
2292
2293        // Share a project as client A
2294        fs.insert_tree(
2295            "/a",
2296            json!({
2297                ".zed.toml": r#"collaborators = ["user_b"]"#,
2298                "main.rs": "fn main() { a }",
2299                "other.rs": "",
2300            }),
2301        )
2302        .await;
2303        let project_a = cx_a.update(|cx| {
2304            Project::local(
2305                client_a.clone(),
2306                client_a.user_store.clone(),
2307                lang_registry.clone(),
2308                fs.clone(),
2309                cx,
2310            )
2311        });
2312        let (worktree_a, _) = project_a
2313            .update(cx_a, |p, cx| {
2314                p.find_or_create_local_worktree("/a", true, cx)
2315            })
2316            .await
2317            .unwrap();
2318        worktree_a
2319            .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2320            .await;
2321        let project_id = project_a.update(cx_a, |p, _| p.next_remote_id()).await;
2322        let worktree_id = worktree_a.read_with(cx_a, |tree, _| tree.id());
2323        project_a.update(cx_a, |p, cx| p.share(cx)).await.unwrap();
2324
2325        // Join the worktree as client B.
2326        let project_b = Project::remote(
2327            project_id,
2328            client_b.clone(),
2329            client_b.user_store.clone(),
2330            lang_registry.clone(),
2331            fs.clone(),
2332            &mut cx_b.to_async(),
2333        )
2334        .await
2335        .unwrap();
2336
2337        // Open a file in an editor as the guest.
2338        let buffer_b = project_b
2339            .update(cx_b, |p, cx| p.open_buffer((worktree_id, "main.rs"), cx))
2340            .await
2341            .unwrap();
2342        let (window_b, _) = cx_b.add_window(|_| EmptyView);
2343        let editor_b = cx_b.add_view(window_b, |cx| {
2344            Editor::for_buffer(buffer_b.clone(), Some(project_b.clone()), cx)
2345        });
2346
2347        let fake_language_server = fake_language_servers.next().await.unwrap();
2348        buffer_b
2349            .condition(&cx_b, |buffer, _| !buffer.completion_triggers().is_empty())
2350            .await;
2351
2352        // Type a completion trigger character as the guest.
2353        editor_b.update(cx_b, |editor, cx| {
2354            editor.select_ranges([13..13], None, cx);
2355            editor.handle_input(&Input(".".into()), cx);
2356            cx.focus(&editor_b);
2357        });
2358
2359        // Receive a completion request as the host's language server.
2360        // Return some completions from the host's language server.
2361        cx_a.foreground().start_waiting();
2362        fake_language_server
2363            .handle_request::<lsp::request::Completion, _, _>(|params, _| async move {
2364                assert_eq!(
2365                    params.text_document_position.text_document.uri,
2366                    lsp::Url::from_file_path("/a/main.rs").unwrap(),
2367                );
2368                assert_eq!(
2369                    params.text_document_position.position,
2370                    lsp::Position::new(0, 14),
2371                );
2372
2373                Ok(Some(lsp::CompletionResponse::Array(vec![
2374                    lsp::CompletionItem {
2375                        label: "first_method(…)".into(),
2376                        detail: Some("fn(&mut self, B) -> C".into()),
2377                        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
2378                            new_text: "first_method($1)".to_string(),
2379                            range: lsp::Range::new(
2380                                lsp::Position::new(0, 14),
2381                                lsp::Position::new(0, 14),
2382                            ),
2383                        })),
2384                        insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
2385                        ..Default::default()
2386                    },
2387                    lsp::CompletionItem {
2388                        label: "second_method(…)".into(),
2389                        detail: Some("fn(&mut self, C) -> D<E>".into()),
2390                        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
2391                            new_text: "second_method()".to_string(),
2392                            range: lsp::Range::new(
2393                                lsp::Position::new(0, 14),
2394                                lsp::Position::new(0, 14),
2395                            ),
2396                        })),
2397                        insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
2398                        ..Default::default()
2399                    },
2400                ])))
2401            })
2402            .next()
2403            .await
2404            .unwrap();
2405        cx_a.foreground().finish_waiting();
2406
2407        // Open the buffer on the host.
2408        let buffer_a = project_a
2409            .update(cx_a, |p, cx| p.open_buffer((worktree_id, "main.rs"), cx))
2410            .await
2411            .unwrap();
2412        buffer_a
2413            .condition(&cx_a, |buffer, _| buffer.text() == "fn main() { a. }")
2414            .await;
2415
2416        // Confirm a completion on the guest.
2417        editor_b
2418            .condition(&cx_b, |editor, _| editor.context_menu_visible())
2419            .await;
2420        editor_b.update(cx_b, |editor, cx| {
2421            editor.confirm_completion(&ConfirmCompletion(Some(0)), cx);
2422            assert_eq!(editor.text(cx), "fn main() { a.first_method() }");
2423        });
2424
2425        // Return a resolved completion from the host's language server.
2426        // The resolved completion has an additional text edit.
2427        fake_language_server.handle_request::<lsp::request::ResolveCompletionItem, _, _>(
2428            |params, _| async move {
2429                assert_eq!(params.label, "first_method(…)");
2430                Ok(lsp::CompletionItem {
2431                    label: "first_method(…)".into(),
2432                    detail: Some("fn(&mut self, B) -> C".into()),
2433                    text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
2434                        new_text: "first_method($1)".to_string(),
2435                        range: lsp::Range::new(
2436                            lsp::Position::new(0, 14),
2437                            lsp::Position::new(0, 14),
2438                        ),
2439                    })),
2440                    additional_text_edits: Some(vec![lsp::TextEdit {
2441                        new_text: "use d::SomeTrait;\n".to_string(),
2442                        range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
2443                    }]),
2444                    insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
2445                    ..Default::default()
2446                })
2447            },
2448        );
2449
2450        // The additional edit is applied.
2451        buffer_a
2452            .condition(&cx_a, |buffer, _| {
2453                buffer.text() == "use d::SomeTrait;\nfn main() { a.first_method() }"
2454            })
2455            .await;
2456        buffer_b
2457            .condition(&cx_b, |buffer, _| {
2458                buffer.text() == "use d::SomeTrait;\nfn main() { a.first_method() }"
2459            })
2460            .await;
2461    }
2462
2463    #[gpui::test(iterations = 10)]
2464    async fn test_reloading_buffer_manually(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
2465        cx_a.foreground().forbid_parking();
2466        let lang_registry = Arc::new(LanguageRegistry::test());
2467        let fs = FakeFs::new(cx_a.background());
2468
2469        // Connect to a server as 2 clients.
2470        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
2471        let client_a = server.create_client(cx_a, "user_a").await;
2472        let client_b = server.create_client(cx_b, "user_b").await;
2473
2474        // Share a project as client A
2475        fs.insert_tree(
2476            "/a",
2477            json!({
2478                ".zed.toml": r#"collaborators = ["user_b"]"#,
2479                "a.rs": "let one = 1;",
2480            }),
2481        )
2482        .await;
2483        let project_a = cx_a.update(|cx| {
2484            Project::local(
2485                client_a.clone(),
2486                client_a.user_store.clone(),
2487                lang_registry.clone(),
2488                fs.clone(),
2489                cx,
2490            )
2491        });
2492        let (worktree_a, _) = project_a
2493            .update(cx_a, |p, cx| {
2494                p.find_or_create_local_worktree("/a", true, cx)
2495            })
2496            .await
2497            .unwrap();
2498        worktree_a
2499            .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2500            .await;
2501        let project_id = project_a.update(cx_a, |p, _| p.next_remote_id()).await;
2502        let worktree_id = worktree_a.read_with(cx_a, |tree, _| tree.id());
2503        project_a.update(cx_a, |p, cx| p.share(cx)).await.unwrap();
2504        let buffer_a = project_a
2505            .update(cx_a, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
2506            .await
2507            .unwrap();
2508
2509        // Join the worktree as client B.
2510        let project_b = Project::remote(
2511            project_id,
2512            client_b.clone(),
2513            client_b.user_store.clone(),
2514            lang_registry.clone(),
2515            fs.clone(),
2516            &mut cx_b.to_async(),
2517        )
2518        .await
2519        .unwrap();
2520
2521        let buffer_b = cx_b
2522            .background()
2523            .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
2524            .await
2525            .unwrap();
2526        buffer_b.update(cx_b, |buffer, cx| {
2527            buffer.edit([4..7], "six", cx);
2528            buffer.edit([10..11], "6", cx);
2529            assert_eq!(buffer.text(), "let six = 6;");
2530            assert!(buffer.is_dirty());
2531            assert!(!buffer.has_conflict());
2532        });
2533        buffer_a
2534            .condition(cx_a, |buffer, _| buffer.text() == "let six = 6;")
2535            .await;
2536
2537        fs.save(Path::new("/a/a.rs"), &Rope::from("let seven = 7;"))
2538            .await
2539            .unwrap();
2540        buffer_a
2541            .condition(cx_a, |buffer, _| buffer.has_conflict())
2542            .await;
2543        buffer_b
2544            .condition(cx_b, |buffer, _| buffer.has_conflict())
2545            .await;
2546
2547        project_b
2548            .update(cx_b, |project, cx| {
2549                project.reload_buffers(HashSet::from_iter([buffer_b.clone()]), true, cx)
2550            })
2551            .await
2552            .unwrap();
2553        buffer_a.read_with(cx_a, |buffer, _| {
2554            assert_eq!(buffer.text(), "let seven = 7;");
2555            assert!(!buffer.is_dirty());
2556            assert!(!buffer.has_conflict());
2557        });
2558        buffer_b.read_with(cx_b, |buffer, _| {
2559            assert_eq!(buffer.text(), "let seven = 7;");
2560            assert!(!buffer.is_dirty());
2561            assert!(!buffer.has_conflict());
2562        });
2563
2564        buffer_a.update(cx_a, |buffer, cx| {
2565            // Undoing on the host is a no-op when the reload was initiated by the guest.
2566            buffer.undo(cx);
2567            assert_eq!(buffer.text(), "let seven = 7;");
2568            assert!(!buffer.is_dirty());
2569            assert!(!buffer.has_conflict());
2570        });
2571        buffer_b.update(cx_b, |buffer, cx| {
2572            // Undoing on the guest rolls back the buffer to before it was reloaded but the conflict gets cleared.
2573            buffer.undo(cx);
2574            assert_eq!(buffer.text(), "let six = 6;");
2575            assert!(buffer.is_dirty());
2576            assert!(!buffer.has_conflict());
2577        });
2578    }
2579
2580    #[gpui::test(iterations = 10)]
2581    async fn test_formatting_buffer(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
2582        cx_a.foreground().forbid_parking();
2583        let lang_registry = Arc::new(LanguageRegistry::test());
2584        let fs = FakeFs::new(cx_a.background());
2585
2586        // Set up a fake language server.
2587        let mut language = Language::new(
2588            LanguageConfig {
2589                name: "Rust".into(),
2590                path_suffixes: vec!["rs".to_string()],
2591                ..Default::default()
2592            },
2593            Some(tree_sitter_rust::language()),
2594        );
2595        let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default());
2596        lang_registry.add(Arc::new(language));
2597
2598        // Connect to a server as 2 clients.
2599        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
2600        let client_a = server.create_client(cx_a, "user_a").await;
2601        let client_b = server.create_client(cx_b, "user_b").await;
2602
2603        // Share a project as client A
2604        fs.insert_tree(
2605            "/a",
2606            json!({
2607                ".zed.toml": r#"collaborators = ["user_b"]"#,
2608                "a.rs": "let one = two",
2609            }),
2610        )
2611        .await;
2612        let project_a = cx_a.update(|cx| {
2613            Project::local(
2614                client_a.clone(),
2615                client_a.user_store.clone(),
2616                lang_registry.clone(),
2617                fs.clone(),
2618                cx,
2619            )
2620        });
2621        let (worktree_a, _) = project_a
2622            .update(cx_a, |p, cx| {
2623                p.find_or_create_local_worktree("/a", true, cx)
2624            })
2625            .await
2626            .unwrap();
2627        worktree_a
2628            .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2629            .await;
2630        let project_id = project_a.update(cx_a, |p, _| p.next_remote_id()).await;
2631        let worktree_id = worktree_a.read_with(cx_a, |tree, _| tree.id());
2632        project_a.update(cx_a, |p, cx| p.share(cx)).await.unwrap();
2633
2634        // Join the worktree as client B.
2635        let project_b = Project::remote(
2636            project_id,
2637            client_b.clone(),
2638            client_b.user_store.clone(),
2639            lang_registry.clone(),
2640            fs.clone(),
2641            &mut cx_b.to_async(),
2642        )
2643        .await
2644        .unwrap();
2645
2646        let buffer_b = cx_b
2647            .background()
2648            .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
2649            .await
2650            .unwrap();
2651
2652        let fake_language_server = fake_language_servers.next().await.unwrap();
2653        fake_language_server.handle_request::<lsp::request::Formatting, _, _>(|_, _| async move {
2654            Ok(Some(vec![
2655                lsp::TextEdit {
2656                    range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 4)),
2657                    new_text: "h".to_string(),
2658                },
2659                lsp::TextEdit {
2660                    range: lsp::Range::new(lsp::Position::new(0, 7), lsp::Position::new(0, 7)),
2661                    new_text: "y".to_string(),
2662                },
2663            ]))
2664        });
2665
2666        project_b
2667            .update(cx_b, |project, cx| {
2668                project.format(HashSet::from_iter([buffer_b.clone()]), true, cx)
2669            })
2670            .await
2671            .unwrap();
2672        assert_eq!(
2673            buffer_b.read_with(cx_b, |buffer, _| buffer.text()),
2674            "let honey = two"
2675        );
2676    }
2677
2678    #[gpui::test(iterations = 10)]
2679    async fn test_definition(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
2680        cx_a.foreground().forbid_parking();
2681        let lang_registry = Arc::new(LanguageRegistry::test());
2682        let fs = FakeFs::new(cx_a.background());
2683        fs.insert_tree(
2684            "/root-1",
2685            json!({
2686                ".zed.toml": r#"collaborators = ["user_b"]"#,
2687                "a.rs": "const ONE: usize = b::TWO + b::THREE;",
2688            }),
2689        )
2690        .await;
2691        fs.insert_tree(
2692            "/root-2",
2693            json!({
2694                "b.rs": "const TWO: usize = 2;\nconst THREE: usize = 3;",
2695            }),
2696        )
2697        .await;
2698
2699        // Set up a fake language server.
2700        let mut language = Language::new(
2701            LanguageConfig {
2702                name: "Rust".into(),
2703                path_suffixes: vec!["rs".to_string()],
2704                ..Default::default()
2705            },
2706            Some(tree_sitter_rust::language()),
2707        );
2708        let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default());
2709        lang_registry.add(Arc::new(language));
2710
2711        // Connect to a server as 2 clients.
2712        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
2713        let client_a = server.create_client(cx_a, "user_a").await;
2714        let client_b = server.create_client(cx_b, "user_b").await;
2715
2716        // Share a project as client A
2717        let project_a = cx_a.update(|cx| {
2718            Project::local(
2719                client_a.clone(),
2720                client_a.user_store.clone(),
2721                lang_registry.clone(),
2722                fs.clone(),
2723                cx,
2724            )
2725        });
2726        let (worktree_a, _) = project_a
2727            .update(cx_a, |p, cx| {
2728                p.find_or_create_local_worktree("/root-1", true, cx)
2729            })
2730            .await
2731            .unwrap();
2732        worktree_a
2733            .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2734            .await;
2735        let project_id = project_a.update(cx_a, |p, _| p.next_remote_id()).await;
2736        let worktree_id = worktree_a.read_with(cx_a, |tree, _| tree.id());
2737        project_a.update(cx_a, |p, cx| p.share(cx)).await.unwrap();
2738
2739        // Join the worktree as client B.
2740        let project_b = Project::remote(
2741            project_id,
2742            client_b.clone(),
2743            client_b.user_store.clone(),
2744            lang_registry.clone(),
2745            fs.clone(),
2746            &mut cx_b.to_async(),
2747        )
2748        .await
2749        .unwrap();
2750
2751        // Open the file on client B.
2752        let buffer_b = cx_b
2753            .background()
2754            .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
2755            .await
2756            .unwrap();
2757
2758        // Request the definition of a symbol as the guest.
2759        let fake_language_server = fake_language_servers.next().await.unwrap();
2760        fake_language_server.handle_request::<lsp::request::GotoDefinition, _, _>(
2761            |_, _| async move {
2762                Ok(Some(lsp::GotoDefinitionResponse::Scalar(
2763                    lsp::Location::new(
2764                        lsp::Url::from_file_path("/root-2/b.rs").unwrap(),
2765                        lsp::Range::new(lsp::Position::new(0, 6), lsp::Position::new(0, 9)),
2766                    ),
2767                )))
2768            },
2769        );
2770
2771        let definitions_1 = project_b
2772            .update(cx_b, |p, cx| p.definition(&buffer_b, 23, cx))
2773            .await
2774            .unwrap();
2775        cx_b.read(|cx| {
2776            assert_eq!(definitions_1.len(), 1);
2777            assert_eq!(project_b.read(cx).worktrees(cx).count(), 2);
2778            let target_buffer = definitions_1[0].buffer.read(cx);
2779            assert_eq!(
2780                target_buffer.text(),
2781                "const TWO: usize = 2;\nconst THREE: usize = 3;"
2782            );
2783            assert_eq!(
2784                definitions_1[0].range.to_point(target_buffer),
2785                Point::new(0, 6)..Point::new(0, 9)
2786            );
2787        });
2788
2789        // Try getting more definitions for the same buffer, ensuring the buffer gets reused from
2790        // the previous call to `definition`.
2791        fake_language_server.handle_request::<lsp::request::GotoDefinition, _, _>(
2792            |_, _| async move {
2793                Ok(Some(lsp::GotoDefinitionResponse::Scalar(
2794                    lsp::Location::new(
2795                        lsp::Url::from_file_path("/root-2/b.rs").unwrap(),
2796                        lsp::Range::new(lsp::Position::new(1, 6), lsp::Position::new(1, 11)),
2797                    ),
2798                )))
2799            },
2800        );
2801
2802        let definitions_2 = project_b
2803            .update(cx_b, |p, cx| p.definition(&buffer_b, 33, cx))
2804            .await
2805            .unwrap();
2806        cx_b.read(|cx| {
2807            assert_eq!(definitions_2.len(), 1);
2808            assert_eq!(project_b.read(cx).worktrees(cx).count(), 2);
2809            let target_buffer = definitions_2[0].buffer.read(cx);
2810            assert_eq!(
2811                target_buffer.text(),
2812                "const TWO: usize = 2;\nconst THREE: usize = 3;"
2813            );
2814            assert_eq!(
2815                definitions_2[0].range.to_point(target_buffer),
2816                Point::new(1, 6)..Point::new(1, 11)
2817            );
2818        });
2819        assert_eq!(definitions_1[0].buffer, definitions_2[0].buffer);
2820    }
2821
2822    #[gpui::test(iterations = 10)]
2823    async fn test_references(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
2824        cx_a.foreground().forbid_parking();
2825        let lang_registry = Arc::new(LanguageRegistry::test());
2826        let fs = FakeFs::new(cx_a.background());
2827        fs.insert_tree(
2828            "/root-1",
2829            json!({
2830                ".zed.toml": r#"collaborators = ["user_b"]"#,
2831                "one.rs": "const ONE: usize = 1;",
2832                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2833            }),
2834        )
2835        .await;
2836        fs.insert_tree(
2837            "/root-2",
2838            json!({
2839                "three.rs": "const THREE: usize = two::TWO + one::ONE;",
2840            }),
2841        )
2842        .await;
2843
2844        // Set up a fake language server.
2845        let mut language = Language::new(
2846            LanguageConfig {
2847                name: "Rust".into(),
2848                path_suffixes: vec!["rs".to_string()],
2849                ..Default::default()
2850            },
2851            Some(tree_sitter_rust::language()),
2852        );
2853        let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default());
2854        lang_registry.add(Arc::new(language));
2855
2856        // Connect to a server as 2 clients.
2857        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
2858        let client_a = server.create_client(cx_a, "user_a").await;
2859        let client_b = server.create_client(cx_b, "user_b").await;
2860
2861        // Share a project as client A
2862        let project_a = cx_a.update(|cx| {
2863            Project::local(
2864                client_a.clone(),
2865                client_a.user_store.clone(),
2866                lang_registry.clone(),
2867                fs.clone(),
2868                cx,
2869            )
2870        });
2871        let (worktree_a, _) = project_a
2872            .update(cx_a, |p, cx| {
2873                p.find_or_create_local_worktree("/root-1", true, cx)
2874            })
2875            .await
2876            .unwrap();
2877        worktree_a
2878            .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2879            .await;
2880        let project_id = project_a.update(cx_a, |p, _| p.next_remote_id()).await;
2881        let worktree_id = worktree_a.read_with(cx_a, |tree, _| tree.id());
2882        project_a.update(cx_a, |p, cx| p.share(cx)).await.unwrap();
2883
2884        // Join the worktree as client B.
2885        let project_b = Project::remote(
2886            project_id,
2887            client_b.clone(),
2888            client_b.user_store.clone(),
2889            lang_registry.clone(),
2890            fs.clone(),
2891            &mut cx_b.to_async(),
2892        )
2893        .await
2894        .unwrap();
2895
2896        // Open the file on client B.
2897        let buffer_b = cx_b
2898            .background()
2899            .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "one.rs"), cx)))
2900            .await
2901            .unwrap();
2902
2903        // Request references to a symbol as the guest.
2904        let fake_language_server = fake_language_servers.next().await.unwrap();
2905        fake_language_server.handle_request::<lsp::request::References, _, _>(
2906            |params, _| async move {
2907                assert_eq!(
2908                    params.text_document_position.text_document.uri.as_str(),
2909                    "file:///root-1/one.rs"
2910                );
2911                Ok(Some(vec![
2912                    lsp::Location {
2913                        uri: lsp::Url::from_file_path("/root-1/two.rs").unwrap(),
2914                        range: lsp::Range::new(
2915                            lsp::Position::new(0, 24),
2916                            lsp::Position::new(0, 27),
2917                        ),
2918                    },
2919                    lsp::Location {
2920                        uri: lsp::Url::from_file_path("/root-1/two.rs").unwrap(),
2921                        range: lsp::Range::new(
2922                            lsp::Position::new(0, 35),
2923                            lsp::Position::new(0, 38),
2924                        ),
2925                    },
2926                    lsp::Location {
2927                        uri: lsp::Url::from_file_path("/root-2/three.rs").unwrap(),
2928                        range: lsp::Range::new(
2929                            lsp::Position::new(0, 37),
2930                            lsp::Position::new(0, 40),
2931                        ),
2932                    },
2933                ]))
2934            },
2935        );
2936
2937        let references = project_b
2938            .update(cx_b, |p, cx| p.references(&buffer_b, 7, cx))
2939            .await
2940            .unwrap();
2941        cx_b.read(|cx| {
2942            assert_eq!(references.len(), 3);
2943            assert_eq!(project_b.read(cx).worktrees(cx).count(), 2);
2944
2945            let two_buffer = references[0].buffer.read(cx);
2946            let three_buffer = references[2].buffer.read(cx);
2947            assert_eq!(
2948                two_buffer.file().unwrap().path().as_ref(),
2949                Path::new("two.rs")
2950            );
2951            assert_eq!(references[1].buffer, references[0].buffer);
2952            assert_eq!(
2953                three_buffer.file().unwrap().full_path(cx),
2954                Path::new("three.rs")
2955            );
2956
2957            assert_eq!(references[0].range.to_offset(&two_buffer), 24..27);
2958            assert_eq!(references[1].range.to_offset(&two_buffer), 35..38);
2959            assert_eq!(references[2].range.to_offset(&three_buffer), 37..40);
2960        });
2961    }
2962
2963    #[gpui::test(iterations = 10)]
2964    async fn test_project_search(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
2965        cx_a.foreground().forbid_parking();
2966        let lang_registry = Arc::new(LanguageRegistry::test());
2967        let fs = FakeFs::new(cx_a.background());
2968        fs.insert_tree(
2969            "/root-1",
2970            json!({
2971                ".zed.toml": r#"collaborators = ["user_b"]"#,
2972                "a": "hello world",
2973                "b": "goodnight moon",
2974                "c": "a world of goo",
2975                "d": "world champion of clown world",
2976            }),
2977        )
2978        .await;
2979        fs.insert_tree(
2980            "/root-2",
2981            json!({
2982                "e": "disney world is fun",
2983            }),
2984        )
2985        .await;
2986
2987        // Connect to a server as 2 clients.
2988        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
2989        let client_a = server.create_client(cx_a, "user_a").await;
2990        let client_b = server.create_client(cx_b, "user_b").await;
2991
2992        // Share a project as client A
2993        let project_a = cx_a.update(|cx| {
2994            Project::local(
2995                client_a.clone(),
2996                client_a.user_store.clone(),
2997                lang_registry.clone(),
2998                fs.clone(),
2999                cx,
3000            )
3001        });
3002        let project_id = project_a.update(cx_a, |p, _| p.next_remote_id()).await;
3003
3004        let (worktree_1, _) = project_a
3005            .update(cx_a, |p, cx| {
3006                p.find_or_create_local_worktree("/root-1", true, cx)
3007            })
3008            .await
3009            .unwrap();
3010        worktree_1
3011            .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
3012            .await;
3013        let (worktree_2, _) = project_a
3014            .update(cx_a, |p, cx| {
3015                p.find_or_create_local_worktree("/root-2", true, cx)
3016            })
3017            .await
3018            .unwrap();
3019        worktree_2
3020            .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
3021            .await;
3022
3023        project_a.update(cx_a, |p, cx| p.share(cx)).await.unwrap();
3024
3025        // Join the worktree as client B.
3026        let project_b = Project::remote(
3027            project_id,
3028            client_b.clone(),
3029            client_b.user_store.clone(),
3030            lang_registry.clone(),
3031            fs.clone(),
3032            &mut cx_b.to_async(),
3033        )
3034        .await
3035        .unwrap();
3036
3037        let results = project_b
3038            .update(cx_b, |project, cx| {
3039                project.search(SearchQuery::text("world", false, false), cx)
3040            })
3041            .await
3042            .unwrap();
3043
3044        let mut ranges_by_path = results
3045            .into_iter()
3046            .map(|(buffer, ranges)| {
3047                buffer.read_with(cx_b, |buffer, cx| {
3048                    let path = buffer.file().unwrap().full_path(cx);
3049                    let offset_ranges = ranges
3050                        .into_iter()
3051                        .map(|range| range.to_offset(buffer))
3052                        .collect::<Vec<_>>();
3053                    (path, offset_ranges)
3054                })
3055            })
3056            .collect::<Vec<_>>();
3057        ranges_by_path.sort_by_key(|(path, _)| path.clone());
3058
3059        assert_eq!(
3060            ranges_by_path,
3061            &[
3062                (PathBuf::from("root-1/a"), vec![6..11]),
3063                (PathBuf::from("root-1/c"), vec![2..7]),
3064                (PathBuf::from("root-1/d"), vec![0..5, 24..29]),
3065                (PathBuf::from("root-2/e"), vec![7..12]),
3066            ]
3067        );
3068    }
3069
3070    #[gpui::test(iterations = 10)]
3071    async fn test_document_highlights(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
3072        cx_a.foreground().forbid_parking();
3073        let lang_registry = Arc::new(LanguageRegistry::test());
3074        let fs = FakeFs::new(cx_a.background());
3075        fs.insert_tree(
3076            "/root-1",
3077            json!({
3078                ".zed.toml": r#"collaborators = ["user_b"]"#,
3079                "main.rs": "fn double(number: i32) -> i32 { number + number }",
3080            }),
3081        )
3082        .await;
3083
3084        // Set up a fake language server.
3085        let mut language = Language::new(
3086            LanguageConfig {
3087                name: "Rust".into(),
3088                path_suffixes: vec!["rs".to_string()],
3089                ..Default::default()
3090            },
3091            Some(tree_sitter_rust::language()),
3092        );
3093        let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default());
3094        lang_registry.add(Arc::new(language));
3095
3096        // Connect to a server as 2 clients.
3097        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
3098        let client_a = server.create_client(cx_a, "user_a").await;
3099        let client_b = server.create_client(cx_b, "user_b").await;
3100
3101        // Share a project as client A
3102        let project_a = cx_a.update(|cx| {
3103            Project::local(
3104                client_a.clone(),
3105                client_a.user_store.clone(),
3106                lang_registry.clone(),
3107                fs.clone(),
3108                cx,
3109            )
3110        });
3111        let (worktree_a, _) = project_a
3112            .update(cx_a, |p, cx| {
3113                p.find_or_create_local_worktree("/root-1", true, cx)
3114            })
3115            .await
3116            .unwrap();
3117        worktree_a
3118            .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
3119            .await;
3120        let project_id = project_a.update(cx_a, |p, _| p.next_remote_id()).await;
3121        let worktree_id = worktree_a.read_with(cx_a, |tree, _| tree.id());
3122        project_a.update(cx_a, |p, cx| p.share(cx)).await.unwrap();
3123
3124        // Join the worktree as client B.
3125        let project_b = Project::remote(
3126            project_id,
3127            client_b.clone(),
3128            client_b.user_store.clone(),
3129            lang_registry.clone(),
3130            fs.clone(),
3131            &mut cx_b.to_async(),
3132        )
3133        .await
3134        .unwrap();
3135
3136        // Open the file on client B.
3137        let buffer_b = cx_b
3138            .background()
3139            .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "main.rs"), cx)))
3140            .await
3141            .unwrap();
3142
3143        // Request document highlights as the guest.
3144        let fake_language_server = fake_language_servers.next().await.unwrap();
3145        fake_language_server.handle_request::<lsp::request::DocumentHighlightRequest, _, _>(
3146            |params, _| async move {
3147                assert_eq!(
3148                    params
3149                        .text_document_position_params
3150                        .text_document
3151                        .uri
3152                        .as_str(),
3153                    "file:///root-1/main.rs"
3154                );
3155                assert_eq!(
3156                    params.text_document_position_params.position,
3157                    lsp::Position::new(0, 34)
3158                );
3159                Ok(Some(vec![
3160                    lsp::DocumentHighlight {
3161                        kind: Some(lsp::DocumentHighlightKind::WRITE),
3162                        range: lsp::Range::new(
3163                            lsp::Position::new(0, 10),
3164                            lsp::Position::new(0, 16),
3165                        ),
3166                    },
3167                    lsp::DocumentHighlight {
3168                        kind: Some(lsp::DocumentHighlightKind::READ),
3169                        range: lsp::Range::new(
3170                            lsp::Position::new(0, 32),
3171                            lsp::Position::new(0, 38),
3172                        ),
3173                    },
3174                    lsp::DocumentHighlight {
3175                        kind: Some(lsp::DocumentHighlightKind::READ),
3176                        range: lsp::Range::new(
3177                            lsp::Position::new(0, 41),
3178                            lsp::Position::new(0, 47),
3179                        ),
3180                    },
3181                ]))
3182            },
3183        );
3184
3185        let highlights = project_b
3186            .update(cx_b, |p, cx| p.document_highlights(&buffer_b, 34, cx))
3187            .await
3188            .unwrap();
3189        buffer_b.read_with(cx_b, |buffer, _| {
3190            let snapshot = buffer.snapshot();
3191
3192            let highlights = highlights
3193                .into_iter()
3194                .map(|highlight| (highlight.kind, highlight.range.to_offset(&snapshot)))
3195                .collect::<Vec<_>>();
3196            assert_eq!(
3197                highlights,
3198                &[
3199                    (lsp::DocumentHighlightKind::WRITE, 10..16),
3200                    (lsp::DocumentHighlightKind::READ, 32..38),
3201                    (lsp::DocumentHighlightKind::READ, 41..47)
3202                ]
3203            )
3204        });
3205    }
3206
3207    #[gpui::test(iterations = 10)]
3208    async fn test_project_symbols(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
3209        cx_a.foreground().forbid_parking();
3210        let lang_registry = Arc::new(LanguageRegistry::test());
3211        let fs = FakeFs::new(cx_a.background());
3212        fs.insert_tree(
3213            "/code",
3214            json!({
3215                "crate-1": {
3216                    ".zed.toml": r#"collaborators = ["user_b"]"#,
3217                    "one.rs": "const ONE: usize = 1;",
3218                },
3219                "crate-2": {
3220                    "two.rs": "const TWO: usize = 2; const THREE: usize = 3;",
3221                },
3222                "private": {
3223                    "passwords.txt": "the-password",
3224                }
3225            }),
3226        )
3227        .await;
3228
3229        // Set up a fake language server.
3230        let mut language = Language::new(
3231            LanguageConfig {
3232                name: "Rust".into(),
3233                path_suffixes: vec!["rs".to_string()],
3234                ..Default::default()
3235            },
3236            Some(tree_sitter_rust::language()),
3237        );
3238        let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default());
3239        lang_registry.add(Arc::new(language));
3240
3241        // Connect to a server as 2 clients.
3242        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
3243        let client_a = server.create_client(cx_a, "user_a").await;
3244        let client_b = server.create_client(cx_b, "user_b").await;
3245
3246        // Share a project as client A
3247        let project_a = cx_a.update(|cx| {
3248            Project::local(
3249                client_a.clone(),
3250                client_a.user_store.clone(),
3251                lang_registry.clone(),
3252                fs.clone(),
3253                cx,
3254            )
3255        });
3256        let (worktree_a, _) = project_a
3257            .update(cx_a, |p, cx| {
3258                p.find_or_create_local_worktree("/code/crate-1", true, cx)
3259            })
3260            .await
3261            .unwrap();
3262        worktree_a
3263            .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
3264            .await;
3265        let project_id = project_a.update(cx_a, |p, _| p.next_remote_id()).await;
3266        let worktree_id = worktree_a.read_with(cx_a, |tree, _| tree.id());
3267        project_a.update(cx_a, |p, cx| p.share(cx)).await.unwrap();
3268
3269        // Join the worktree as client B.
3270        let project_b = Project::remote(
3271            project_id,
3272            client_b.clone(),
3273            client_b.user_store.clone(),
3274            lang_registry.clone(),
3275            fs.clone(),
3276            &mut cx_b.to_async(),
3277        )
3278        .await
3279        .unwrap();
3280
3281        // Cause the language server to start.
3282        let _buffer = cx_b
3283            .background()
3284            .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "one.rs"), cx)))
3285            .await
3286            .unwrap();
3287
3288        let fake_language_server = fake_language_servers.next().await.unwrap();
3289        fake_language_server.handle_request::<lsp::request::WorkspaceSymbol, _, _>(
3290            |_, _| async move {
3291                #[allow(deprecated)]
3292                Ok(Some(vec![lsp::SymbolInformation {
3293                    name: "TWO".into(),
3294                    location: lsp::Location {
3295                        uri: lsp::Url::from_file_path("/code/crate-2/two.rs").unwrap(),
3296                        range: lsp::Range::new(lsp::Position::new(0, 6), lsp::Position::new(0, 9)),
3297                    },
3298                    kind: lsp::SymbolKind::CONSTANT,
3299                    tags: None,
3300                    container_name: None,
3301                    deprecated: None,
3302                }]))
3303            },
3304        );
3305
3306        // Request the definition of a symbol as the guest.
3307        let symbols = project_b
3308            .update(cx_b, |p, cx| p.symbols("two", cx))
3309            .await
3310            .unwrap();
3311        assert_eq!(symbols.len(), 1);
3312        assert_eq!(symbols[0].name, "TWO");
3313
3314        // Open one of the returned symbols.
3315        let buffer_b_2 = project_b
3316            .update(cx_b, |project, cx| {
3317                project.open_buffer_for_symbol(&symbols[0], cx)
3318            })
3319            .await
3320            .unwrap();
3321        buffer_b_2.read_with(cx_b, |buffer, _| {
3322            assert_eq!(
3323                buffer.file().unwrap().path().as_ref(),
3324                Path::new("../crate-2/two.rs")
3325            );
3326        });
3327
3328        // Attempt to craft a symbol and violate host's privacy by opening an arbitrary file.
3329        let mut fake_symbol = symbols[0].clone();
3330        fake_symbol.path = Path::new("/code/secrets").into();
3331        let error = project_b
3332            .update(cx_b, |project, cx| {
3333                project.open_buffer_for_symbol(&fake_symbol, cx)
3334            })
3335            .await
3336            .unwrap_err();
3337        assert!(error.to_string().contains("invalid symbol signature"));
3338    }
3339
3340    #[gpui::test(iterations = 10)]
3341    async fn test_open_buffer_while_getting_definition_pointing_to_it(
3342        cx_a: &mut TestAppContext,
3343        cx_b: &mut TestAppContext,
3344        mut rng: StdRng,
3345    ) {
3346        cx_a.foreground().forbid_parking();
3347        let lang_registry = Arc::new(LanguageRegistry::test());
3348        let fs = FakeFs::new(cx_a.background());
3349        fs.insert_tree(
3350            "/root",
3351            json!({
3352                ".zed.toml": r#"collaborators = ["user_b"]"#,
3353                "a.rs": "const ONE: usize = b::TWO;",
3354                "b.rs": "const TWO: usize = 2",
3355            }),
3356        )
3357        .await;
3358
3359        // Set up a fake language server.
3360        let mut language = Language::new(
3361            LanguageConfig {
3362                name: "Rust".into(),
3363                path_suffixes: vec!["rs".to_string()],
3364                ..Default::default()
3365            },
3366            Some(tree_sitter_rust::language()),
3367        );
3368        let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default());
3369        lang_registry.add(Arc::new(language));
3370
3371        // Connect to a server as 2 clients.
3372        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
3373        let client_a = server.create_client(cx_a, "user_a").await;
3374        let client_b = server.create_client(cx_b, "user_b").await;
3375
3376        // Share a project as client A
3377        let project_a = cx_a.update(|cx| {
3378            Project::local(
3379                client_a.clone(),
3380                client_a.user_store.clone(),
3381                lang_registry.clone(),
3382                fs.clone(),
3383                cx,
3384            )
3385        });
3386
3387        let (worktree_a, _) = project_a
3388            .update(cx_a, |p, cx| {
3389                p.find_or_create_local_worktree("/root", true, cx)
3390            })
3391            .await
3392            .unwrap();
3393        worktree_a
3394            .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
3395            .await;
3396        let project_id = project_a.update(cx_a, |p, _| p.next_remote_id()).await;
3397        let worktree_id = worktree_a.read_with(cx_a, |tree, _| tree.id());
3398        project_a.update(cx_a, |p, cx| p.share(cx)).await.unwrap();
3399
3400        // Join the worktree as client B.
3401        let project_b = Project::remote(
3402            project_id,
3403            client_b.clone(),
3404            client_b.user_store.clone(),
3405            lang_registry.clone(),
3406            fs.clone(),
3407            &mut cx_b.to_async(),
3408        )
3409        .await
3410        .unwrap();
3411
3412        let buffer_b1 = cx_b
3413            .background()
3414            .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
3415            .await
3416            .unwrap();
3417
3418        let fake_language_server = fake_language_servers.next().await.unwrap();
3419        fake_language_server.handle_request::<lsp::request::GotoDefinition, _, _>(
3420            |_, _| async move {
3421                Ok(Some(lsp::GotoDefinitionResponse::Scalar(
3422                    lsp::Location::new(
3423                        lsp::Url::from_file_path("/root/b.rs").unwrap(),
3424                        lsp::Range::new(lsp::Position::new(0, 6), lsp::Position::new(0, 9)),
3425                    ),
3426                )))
3427            },
3428        );
3429
3430        let definitions;
3431        let buffer_b2;
3432        if rng.gen() {
3433            definitions = project_b.update(cx_b, |p, cx| p.definition(&buffer_b1, 23, cx));
3434            buffer_b2 = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "b.rs"), cx));
3435        } else {
3436            buffer_b2 = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "b.rs"), cx));
3437            definitions = project_b.update(cx_b, |p, cx| p.definition(&buffer_b1, 23, cx));
3438        }
3439
3440        let buffer_b2 = buffer_b2.await.unwrap();
3441        let definitions = definitions.await.unwrap();
3442        assert_eq!(definitions.len(), 1);
3443        assert_eq!(definitions[0].buffer, buffer_b2);
3444    }
3445
3446    #[gpui::test(iterations = 10)]
3447    async fn test_collaborating_with_code_actions(
3448        cx_a: &mut TestAppContext,
3449        cx_b: &mut TestAppContext,
3450    ) {
3451        cx_a.foreground().forbid_parking();
3452        let lang_registry = Arc::new(LanguageRegistry::test());
3453        let fs = FakeFs::new(cx_a.background());
3454        cx_b.update(|cx| editor::init(cx));
3455
3456        // Set up a fake language server.
3457        let mut language = Language::new(
3458            LanguageConfig {
3459                name: "Rust".into(),
3460                path_suffixes: vec!["rs".to_string()],
3461                ..Default::default()
3462            },
3463            Some(tree_sitter_rust::language()),
3464        );
3465        let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default());
3466        lang_registry.add(Arc::new(language));
3467
3468        // Connect to a server as 2 clients.
3469        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
3470        let client_a = server.create_client(cx_a, "user_a").await;
3471        let client_b = server.create_client(cx_b, "user_b").await;
3472
3473        // Share a project as client A
3474        fs.insert_tree(
3475            "/a",
3476            json!({
3477                ".zed.toml": r#"collaborators = ["user_b"]"#,
3478                "main.rs": "mod other;\nfn main() { let foo = other::foo(); }",
3479                "other.rs": "pub fn foo() -> usize { 4 }",
3480            }),
3481        )
3482        .await;
3483        let project_a = cx_a.update(|cx| {
3484            Project::local(
3485                client_a.clone(),
3486                client_a.user_store.clone(),
3487                lang_registry.clone(),
3488                fs.clone(),
3489                cx,
3490            )
3491        });
3492        let (worktree_a, _) = project_a
3493            .update(cx_a, |p, cx| {
3494                p.find_or_create_local_worktree("/a", true, cx)
3495            })
3496            .await
3497            .unwrap();
3498        worktree_a
3499            .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
3500            .await;
3501        let project_id = project_a.update(cx_a, |p, _| p.next_remote_id()).await;
3502        let worktree_id = worktree_a.read_with(cx_a, |tree, _| tree.id());
3503        project_a.update(cx_a, |p, cx| p.share(cx)).await.unwrap();
3504
3505        // Join the worktree as client B.
3506        let project_b = Project::remote(
3507            project_id,
3508            client_b.clone(),
3509            client_b.user_store.clone(),
3510            lang_registry.clone(),
3511            fs.clone(),
3512            &mut cx_b.to_async(),
3513        )
3514        .await
3515        .unwrap();
3516        let mut params = cx_b.update(WorkspaceParams::test);
3517        params.languages = lang_registry.clone();
3518        params.client = client_b.client.clone();
3519        params.user_store = client_b.user_store.clone();
3520        params.project = project_b;
3521
3522        let (_window_b, workspace_b) = cx_b.add_window(|cx| Workspace::new(&params, cx));
3523        let editor_b = workspace_b
3524            .update(cx_b, |workspace, cx| {
3525                workspace.open_path((worktree_id, "main.rs"), cx)
3526            })
3527            .await
3528            .unwrap()
3529            .downcast::<Editor>()
3530            .unwrap();
3531
3532        let mut fake_language_server = fake_language_servers.next().await.unwrap();
3533        fake_language_server
3534            .handle_request::<lsp::request::CodeActionRequest, _, _>(|params, _| async move {
3535                assert_eq!(
3536                    params.text_document.uri,
3537                    lsp::Url::from_file_path("/a/main.rs").unwrap(),
3538                );
3539                assert_eq!(params.range.start, lsp::Position::new(0, 0));
3540                assert_eq!(params.range.end, lsp::Position::new(0, 0));
3541                Ok(None)
3542            })
3543            .next()
3544            .await;
3545
3546        // Move cursor to a location that contains code actions.
3547        editor_b.update(cx_b, |editor, cx| {
3548            editor.select_ranges([Point::new(1, 31)..Point::new(1, 31)], None, cx);
3549            cx.focus(&editor_b);
3550        });
3551
3552        fake_language_server
3553            .handle_request::<lsp::request::CodeActionRequest, _, _>(|params, _| async move {
3554                assert_eq!(
3555                    params.text_document.uri,
3556                    lsp::Url::from_file_path("/a/main.rs").unwrap(),
3557                );
3558                assert_eq!(params.range.start, lsp::Position::new(1, 31));
3559                assert_eq!(params.range.end, lsp::Position::new(1, 31));
3560
3561                Ok(Some(vec![lsp::CodeActionOrCommand::CodeAction(
3562                    lsp::CodeAction {
3563                        title: "Inline into all callers".to_string(),
3564                        edit: Some(lsp::WorkspaceEdit {
3565                            changes: Some(
3566                                [
3567                                    (
3568                                        lsp::Url::from_file_path("/a/main.rs").unwrap(),
3569                                        vec![lsp::TextEdit::new(
3570                                            lsp::Range::new(
3571                                                lsp::Position::new(1, 22),
3572                                                lsp::Position::new(1, 34),
3573                                            ),
3574                                            "4".to_string(),
3575                                        )],
3576                                    ),
3577                                    (
3578                                        lsp::Url::from_file_path("/a/other.rs").unwrap(),
3579                                        vec![lsp::TextEdit::new(
3580                                            lsp::Range::new(
3581                                                lsp::Position::new(0, 0),
3582                                                lsp::Position::new(0, 27),
3583                                            ),
3584                                            "".to_string(),
3585                                        )],
3586                                    ),
3587                                ]
3588                                .into_iter()
3589                                .collect(),
3590                            ),
3591                            ..Default::default()
3592                        }),
3593                        data: Some(json!({
3594                            "codeActionParams": {
3595                                "range": {
3596                                    "start": {"line": 1, "column": 31},
3597                                    "end": {"line": 1, "column": 31},
3598                                }
3599                            }
3600                        })),
3601                        ..Default::default()
3602                    },
3603                )]))
3604            })
3605            .next()
3606            .await;
3607
3608        // Toggle code actions and wait for them to display.
3609        editor_b.update(cx_b, |editor, cx| {
3610            editor.toggle_code_actions(&ToggleCodeActions(false), cx);
3611        });
3612        editor_b
3613            .condition(&cx_b, |editor, _| editor.context_menu_visible())
3614            .await;
3615
3616        fake_language_server.remove_request_handler::<lsp::request::CodeActionRequest>();
3617
3618        // Confirming the code action will trigger a resolve request.
3619        let confirm_action = workspace_b
3620            .update(cx_b, |workspace, cx| {
3621                Editor::confirm_code_action(workspace, &ConfirmCodeAction(Some(0)), cx)
3622            })
3623            .unwrap();
3624        fake_language_server.handle_request::<lsp::request::CodeActionResolveRequest, _, _>(
3625            |_, _| async move {
3626                Ok(lsp::CodeAction {
3627                    title: "Inline into all callers".to_string(),
3628                    edit: Some(lsp::WorkspaceEdit {
3629                        changes: Some(
3630                            [
3631                                (
3632                                    lsp::Url::from_file_path("/a/main.rs").unwrap(),
3633                                    vec![lsp::TextEdit::new(
3634                                        lsp::Range::new(
3635                                            lsp::Position::new(1, 22),
3636                                            lsp::Position::new(1, 34),
3637                                        ),
3638                                        "4".to_string(),
3639                                    )],
3640                                ),
3641                                (
3642                                    lsp::Url::from_file_path("/a/other.rs").unwrap(),
3643                                    vec![lsp::TextEdit::new(
3644                                        lsp::Range::new(
3645                                            lsp::Position::new(0, 0),
3646                                            lsp::Position::new(0, 27),
3647                                        ),
3648                                        "".to_string(),
3649                                    )],
3650                                ),
3651                            ]
3652                            .into_iter()
3653                            .collect(),
3654                        ),
3655                        ..Default::default()
3656                    }),
3657                    ..Default::default()
3658                })
3659            },
3660        );
3661
3662        // After the action is confirmed, an editor containing both modified files is opened.
3663        confirm_action.await.unwrap();
3664        let code_action_editor = workspace_b.read_with(cx_b, |workspace, cx| {
3665            workspace
3666                .active_item(cx)
3667                .unwrap()
3668                .downcast::<Editor>()
3669                .unwrap()
3670        });
3671        code_action_editor.update(cx_b, |editor, cx| {
3672            assert_eq!(editor.text(cx), "\nmod other;\nfn main() { let foo = 4; }");
3673            editor.undo(&Undo, cx);
3674            assert_eq!(
3675                editor.text(cx),
3676                "pub fn foo() -> usize { 4 }\nmod other;\nfn main() { let foo = other::foo(); }"
3677            );
3678            editor.redo(&Redo, cx);
3679            assert_eq!(editor.text(cx), "\nmod other;\nfn main() { let foo = 4; }");
3680        });
3681    }
3682
3683    #[gpui::test(iterations = 10)]
3684    async fn test_collaborating_with_renames(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
3685        cx_a.foreground().forbid_parking();
3686        let lang_registry = Arc::new(LanguageRegistry::test());
3687        let fs = FakeFs::new(cx_a.background());
3688        cx_b.update(|cx| editor::init(cx));
3689
3690        // Set up a fake language server.
3691        let mut language = Language::new(
3692            LanguageConfig {
3693                name: "Rust".into(),
3694                path_suffixes: vec!["rs".to_string()],
3695                ..Default::default()
3696            },
3697            Some(tree_sitter_rust::language()),
3698        );
3699        let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default());
3700        lang_registry.add(Arc::new(language));
3701
3702        // Connect to a server as 2 clients.
3703        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
3704        let client_a = server.create_client(cx_a, "user_a").await;
3705        let client_b = server.create_client(cx_b, "user_b").await;
3706
3707        // Share a project as client A
3708        fs.insert_tree(
3709            "/dir",
3710            json!({
3711                ".zed.toml": r#"collaborators = ["user_b"]"#,
3712                "one.rs": "const ONE: usize = 1;",
3713                "two.rs": "const TWO: usize = one::ONE + one::ONE;"
3714            }),
3715        )
3716        .await;
3717        let project_a = cx_a.update(|cx| {
3718            Project::local(
3719                client_a.clone(),
3720                client_a.user_store.clone(),
3721                lang_registry.clone(),
3722                fs.clone(),
3723                cx,
3724            )
3725        });
3726        let (worktree_a, _) = project_a
3727            .update(cx_a, |p, cx| {
3728                p.find_or_create_local_worktree("/dir", true, cx)
3729            })
3730            .await
3731            .unwrap();
3732        worktree_a
3733            .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
3734            .await;
3735        let project_id = project_a.update(cx_a, |p, _| p.next_remote_id()).await;
3736        let worktree_id = worktree_a.read_with(cx_a, |tree, _| tree.id());
3737        project_a.update(cx_a, |p, cx| p.share(cx)).await.unwrap();
3738
3739        // Join the worktree as client B.
3740        let project_b = Project::remote(
3741            project_id,
3742            client_b.clone(),
3743            client_b.user_store.clone(),
3744            lang_registry.clone(),
3745            fs.clone(),
3746            &mut cx_b.to_async(),
3747        )
3748        .await
3749        .unwrap();
3750        let mut params = cx_b.update(WorkspaceParams::test);
3751        params.languages = lang_registry.clone();
3752        params.client = client_b.client.clone();
3753        params.user_store = client_b.user_store.clone();
3754        params.project = project_b;
3755
3756        let (_window_b, workspace_b) = cx_b.add_window(|cx| Workspace::new(&params, cx));
3757        let editor_b = workspace_b
3758            .update(cx_b, |workspace, cx| {
3759                workspace.open_path((worktree_id, "one.rs"), cx)
3760            })
3761            .await
3762            .unwrap()
3763            .downcast::<Editor>()
3764            .unwrap();
3765        let fake_language_server = fake_language_servers.next().await.unwrap();
3766
3767        // Move cursor to a location that can be renamed.
3768        let prepare_rename = editor_b.update(cx_b, |editor, cx| {
3769            editor.select_ranges([7..7], None, cx);
3770            editor.rename(&Rename, cx).unwrap()
3771        });
3772
3773        fake_language_server
3774            .handle_request::<lsp::request::PrepareRenameRequest, _, _>(|params, _| async move {
3775                assert_eq!(params.text_document.uri.as_str(), "file:///dir/one.rs");
3776                assert_eq!(params.position, lsp::Position::new(0, 7));
3777                Ok(Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(
3778                    lsp::Position::new(0, 6),
3779                    lsp::Position::new(0, 9),
3780                ))))
3781            })
3782            .next()
3783            .await
3784            .unwrap();
3785        prepare_rename.await.unwrap();
3786        editor_b.update(cx_b, |editor, cx| {
3787            let rename = editor.pending_rename().unwrap();
3788            let buffer = editor.buffer().read(cx).snapshot(cx);
3789            assert_eq!(
3790                rename.range.start.to_offset(&buffer)..rename.range.end.to_offset(&buffer),
3791                6..9
3792            );
3793            rename.editor.update(cx, |rename_editor, cx| {
3794                rename_editor.buffer().update(cx, |rename_buffer, cx| {
3795                    rename_buffer.edit([0..3], "THREE", cx);
3796                });
3797            });
3798        });
3799
3800        let confirm_rename = workspace_b.update(cx_b, |workspace, cx| {
3801            Editor::confirm_rename(workspace, &ConfirmRename, cx).unwrap()
3802        });
3803        fake_language_server
3804            .handle_request::<lsp::request::Rename, _, _>(|params, _| async move {
3805                assert_eq!(
3806                    params.text_document_position.text_document.uri.as_str(),
3807                    "file:///dir/one.rs"
3808                );
3809                assert_eq!(
3810                    params.text_document_position.position,
3811                    lsp::Position::new(0, 6)
3812                );
3813                assert_eq!(params.new_name, "THREE");
3814                Ok(Some(lsp::WorkspaceEdit {
3815                    changes: Some(
3816                        [
3817                            (
3818                                lsp::Url::from_file_path("/dir/one.rs").unwrap(),
3819                                vec![lsp::TextEdit::new(
3820                                    lsp::Range::new(
3821                                        lsp::Position::new(0, 6),
3822                                        lsp::Position::new(0, 9),
3823                                    ),
3824                                    "THREE".to_string(),
3825                                )],
3826                            ),
3827                            (
3828                                lsp::Url::from_file_path("/dir/two.rs").unwrap(),
3829                                vec![
3830                                    lsp::TextEdit::new(
3831                                        lsp::Range::new(
3832                                            lsp::Position::new(0, 24),
3833                                            lsp::Position::new(0, 27),
3834                                        ),
3835                                        "THREE".to_string(),
3836                                    ),
3837                                    lsp::TextEdit::new(
3838                                        lsp::Range::new(
3839                                            lsp::Position::new(0, 35),
3840                                            lsp::Position::new(0, 38),
3841                                        ),
3842                                        "THREE".to_string(),
3843                                    ),
3844                                ],
3845                            ),
3846                        ]
3847                        .into_iter()
3848                        .collect(),
3849                    ),
3850                    ..Default::default()
3851                }))
3852            })
3853            .next()
3854            .await
3855            .unwrap();
3856        confirm_rename.await.unwrap();
3857
3858        let rename_editor = workspace_b.read_with(cx_b, |workspace, cx| {
3859            workspace
3860                .active_item(cx)
3861                .unwrap()
3862                .downcast::<Editor>()
3863                .unwrap()
3864        });
3865        rename_editor.update(cx_b, |editor, cx| {
3866            assert_eq!(
3867                editor.text(cx),
3868                "const TWO: usize = one::THREE + one::THREE;\nconst THREE: usize = 1;"
3869            );
3870            editor.undo(&Undo, cx);
3871            assert_eq!(
3872                editor.text(cx),
3873                "const TWO: usize = one::ONE + one::ONE;\nconst ONE: usize = 1;"
3874            );
3875            editor.redo(&Redo, cx);
3876            assert_eq!(
3877                editor.text(cx),
3878                "const TWO: usize = one::THREE + one::THREE;\nconst THREE: usize = 1;"
3879            );
3880        });
3881
3882        // Ensure temporary rename edits cannot be undone/redone.
3883        editor_b.update(cx_b, |editor, cx| {
3884            editor.undo(&Undo, cx);
3885            assert_eq!(editor.text(cx), "const ONE: usize = 1;");
3886            editor.undo(&Undo, cx);
3887            assert_eq!(editor.text(cx), "const ONE: usize = 1;");
3888            editor.redo(&Redo, cx);
3889            assert_eq!(editor.text(cx), "const THREE: usize = 1;");
3890        })
3891    }
3892
3893    #[gpui::test(iterations = 10)]
3894    async fn test_basic_chat(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
3895        cx_a.foreground().forbid_parking();
3896
3897        // Connect to a server as 2 clients.
3898        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
3899        let client_a = server.create_client(cx_a, "user_a").await;
3900        let client_b = server.create_client(cx_b, "user_b").await;
3901
3902        // Create an org that includes these 2 users.
3903        let db = &server.app_state.db;
3904        let org_id = db.create_org("Test Org", "test-org").await.unwrap();
3905        db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
3906            .await
3907            .unwrap();
3908        db.add_org_member(org_id, client_b.current_user_id(&cx_b), false)
3909            .await
3910            .unwrap();
3911
3912        // Create a channel that includes all the users.
3913        let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
3914        db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
3915            .await
3916            .unwrap();
3917        db.add_channel_member(channel_id, client_b.current_user_id(&cx_b), false)
3918            .await
3919            .unwrap();
3920        db.create_channel_message(
3921            channel_id,
3922            client_b.current_user_id(&cx_b),
3923            "hello A, it's B.",
3924            OffsetDateTime::now_utc(),
3925            1,
3926        )
3927        .await
3928        .unwrap();
3929
3930        let channels_a = cx_a
3931            .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
3932        channels_a
3933            .condition(cx_a, |list, _| list.available_channels().is_some())
3934            .await;
3935        channels_a.read_with(cx_a, |list, _| {
3936            assert_eq!(
3937                list.available_channels().unwrap(),
3938                &[ChannelDetails {
3939                    id: channel_id.to_proto(),
3940                    name: "test-channel".to_string()
3941                }]
3942            )
3943        });
3944        let channel_a = channels_a.update(cx_a, |this, cx| {
3945            this.get_channel(channel_id.to_proto(), cx).unwrap()
3946        });
3947        channel_a.read_with(cx_a, |channel, _| assert!(channel.messages().is_empty()));
3948        channel_a
3949            .condition(&cx_a, |channel, _| {
3950                channel_messages(channel)
3951                    == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
3952            })
3953            .await;
3954
3955        let channels_b = cx_b
3956            .add_model(|cx| ChannelList::new(client_b.user_store.clone(), client_b.clone(), cx));
3957        channels_b
3958            .condition(cx_b, |list, _| list.available_channels().is_some())
3959            .await;
3960        channels_b.read_with(cx_b, |list, _| {
3961            assert_eq!(
3962                list.available_channels().unwrap(),
3963                &[ChannelDetails {
3964                    id: channel_id.to_proto(),
3965                    name: "test-channel".to_string()
3966                }]
3967            )
3968        });
3969
3970        let channel_b = channels_b.update(cx_b, |this, cx| {
3971            this.get_channel(channel_id.to_proto(), cx).unwrap()
3972        });
3973        channel_b.read_with(cx_b, |channel, _| assert!(channel.messages().is_empty()));
3974        channel_b
3975            .condition(&cx_b, |channel, _| {
3976                channel_messages(channel)
3977                    == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
3978            })
3979            .await;
3980
3981        channel_a
3982            .update(cx_a, |channel, cx| {
3983                channel
3984                    .send_message("oh, hi B.".to_string(), cx)
3985                    .unwrap()
3986                    .detach();
3987                let task = channel.send_message("sup".to_string(), cx).unwrap();
3988                assert_eq!(
3989                    channel_messages(channel),
3990                    &[
3991                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3992                        ("user_a".to_string(), "oh, hi B.".to_string(), true),
3993                        ("user_a".to_string(), "sup".to_string(), true)
3994                    ]
3995                );
3996                task
3997            })
3998            .await
3999            .unwrap();
4000
4001        channel_b
4002            .condition(&cx_b, |channel, _| {
4003                channel_messages(channel)
4004                    == [
4005                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
4006                        ("user_a".to_string(), "oh, hi B.".to_string(), false),
4007                        ("user_a".to_string(), "sup".to_string(), false),
4008                    ]
4009            })
4010            .await;
4011
4012        assert_eq!(
4013            server
4014                .state()
4015                .await
4016                .channel(channel_id)
4017                .unwrap()
4018                .connection_ids
4019                .len(),
4020            2
4021        );
4022        cx_b.update(|_| drop(channel_b));
4023        server
4024            .condition(|state| state.channel(channel_id).unwrap().connection_ids.len() == 1)
4025            .await;
4026
4027        cx_a.update(|_| drop(channel_a));
4028        server
4029            .condition(|state| state.channel(channel_id).is_none())
4030            .await;
4031    }
4032
4033    #[gpui::test(iterations = 10)]
4034    async fn test_chat_message_validation(cx_a: &mut TestAppContext) {
4035        cx_a.foreground().forbid_parking();
4036
4037        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
4038        let client_a = server.create_client(cx_a, "user_a").await;
4039
4040        let db = &server.app_state.db;
4041        let org_id = db.create_org("Test Org", "test-org").await.unwrap();
4042        let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
4043        db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
4044            .await
4045            .unwrap();
4046        db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
4047            .await
4048            .unwrap();
4049
4050        let channels_a = cx_a
4051            .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
4052        channels_a
4053            .condition(cx_a, |list, _| list.available_channels().is_some())
4054            .await;
4055        let channel_a = channels_a.update(cx_a, |this, cx| {
4056            this.get_channel(channel_id.to_proto(), cx).unwrap()
4057        });
4058
4059        // Messages aren't allowed to be too long.
4060        channel_a
4061            .update(cx_a, |channel, cx| {
4062                let long_body = "this is long.\n".repeat(1024);
4063                channel.send_message(long_body, cx).unwrap()
4064            })
4065            .await
4066            .unwrap_err();
4067
4068        // Messages aren't allowed to be blank.
4069        channel_a.update(cx_a, |channel, cx| {
4070            channel.send_message(String::new(), cx).unwrap_err()
4071        });
4072
4073        // Leading and trailing whitespace are trimmed.
4074        channel_a
4075            .update(cx_a, |channel, cx| {
4076                channel
4077                    .send_message("\n surrounded by whitespace  \n".to_string(), cx)
4078                    .unwrap()
4079            })
4080            .await
4081            .unwrap();
4082        assert_eq!(
4083            db.get_channel_messages(channel_id, 10, None)
4084                .await
4085                .unwrap()
4086                .iter()
4087                .map(|m| &m.body)
4088                .collect::<Vec<_>>(),
4089            &["surrounded by whitespace"]
4090        );
4091    }
4092
4093    #[gpui::test(iterations = 10)]
4094    async fn test_chat_reconnection(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
4095        cx_a.foreground().forbid_parking();
4096
4097        // Connect to a server as 2 clients.
4098        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
4099        let client_a = server.create_client(cx_a, "user_a").await;
4100        let client_b = server.create_client(cx_b, "user_b").await;
4101        let mut status_b = client_b.status();
4102
4103        // Create an org that includes these 2 users.
4104        let db = &server.app_state.db;
4105        let org_id = db.create_org("Test Org", "test-org").await.unwrap();
4106        db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
4107            .await
4108            .unwrap();
4109        db.add_org_member(org_id, client_b.current_user_id(&cx_b), false)
4110            .await
4111            .unwrap();
4112
4113        // Create a channel that includes all the users.
4114        let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
4115        db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
4116            .await
4117            .unwrap();
4118        db.add_channel_member(channel_id, client_b.current_user_id(&cx_b), false)
4119            .await
4120            .unwrap();
4121        db.create_channel_message(
4122            channel_id,
4123            client_b.current_user_id(&cx_b),
4124            "hello A, it's B.",
4125            OffsetDateTime::now_utc(),
4126            2,
4127        )
4128        .await
4129        .unwrap();
4130
4131        let channels_a = cx_a
4132            .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
4133        channels_a
4134            .condition(cx_a, |list, _| list.available_channels().is_some())
4135            .await;
4136
4137        channels_a.read_with(cx_a, |list, _| {
4138            assert_eq!(
4139                list.available_channels().unwrap(),
4140                &[ChannelDetails {
4141                    id: channel_id.to_proto(),
4142                    name: "test-channel".to_string()
4143                }]
4144            )
4145        });
4146        let channel_a = channels_a.update(cx_a, |this, cx| {
4147            this.get_channel(channel_id.to_proto(), cx).unwrap()
4148        });
4149        channel_a.read_with(cx_a, |channel, _| assert!(channel.messages().is_empty()));
4150        channel_a
4151            .condition(&cx_a, |channel, _| {
4152                channel_messages(channel)
4153                    == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
4154            })
4155            .await;
4156
4157        let channels_b = cx_b
4158            .add_model(|cx| ChannelList::new(client_b.user_store.clone(), client_b.clone(), cx));
4159        channels_b
4160            .condition(cx_b, |list, _| list.available_channels().is_some())
4161            .await;
4162        channels_b.read_with(cx_b, |list, _| {
4163            assert_eq!(
4164                list.available_channels().unwrap(),
4165                &[ChannelDetails {
4166                    id: channel_id.to_proto(),
4167                    name: "test-channel".to_string()
4168                }]
4169            )
4170        });
4171
4172        let channel_b = channels_b.update(cx_b, |this, cx| {
4173            this.get_channel(channel_id.to_proto(), cx).unwrap()
4174        });
4175        channel_b.read_with(cx_b, |channel, _| assert!(channel.messages().is_empty()));
4176        channel_b
4177            .condition(&cx_b, |channel, _| {
4178                channel_messages(channel)
4179                    == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
4180            })
4181            .await;
4182
4183        // Disconnect client B, ensuring we can still access its cached channel data.
4184        server.forbid_connections();
4185        server.disconnect_client(client_b.current_user_id(&cx_b));
4186        cx_b.foreground().advance_clock(Duration::from_secs(3));
4187        while !matches!(
4188            status_b.next().await,
4189            Some(client::Status::ReconnectionError { .. })
4190        ) {}
4191
4192        channels_b.read_with(cx_b, |channels, _| {
4193            assert_eq!(
4194                channels.available_channels().unwrap(),
4195                [ChannelDetails {
4196                    id: channel_id.to_proto(),
4197                    name: "test-channel".to_string()
4198                }]
4199            )
4200        });
4201        channel_b.read_with(cx_b, |channel, _| {
4202            assert_eq!(
4203                channel_messages(channel),
4204                [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
4205            )
4206        });
4207
4208        // Send a message from client B while it is disconnected.
4209        channel_b
4210            .update(cx_b, |channel, cx| {
4211                let task = channel
4212                    .send_message("can you see this?".to_string(), cx)
4213                    .unwrap();
4214                assert_eq!(
4215                    channel_messages(channel),
4216                    &[
4217                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
4218                        ("user_b".to_string(), "can you see this?".to_string(), true)
4219                    ]
4220                );
4221                task
4222            })
4223            .await
4224            .unwrap_err();
4225
4226        // Send a message from client A while B is disconnected.
4227        channel_a
4228            .update(cx_a, |channel, cx| {
4229                channel
4230                    .send_message("oh, hi B.".to_string(), cx)
4231                    .unwrap()
4232                    .detach();
4233                let task = channel.send_message("sup".to_string(), cx).unwrap();
4234                assert_eq!(
4235                    channel_messages(channel),
4236                    &[
4237                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
4238                        ("user_a".to_string(), "oh, hi B.".to_string(), true),
4239                        ("user_a".to_string(), "sup".to_string(), true)
4240                    ]
4241                );
4242                task
4243            })
4244            .await
4245            .unwrap();
4246
4247        // Give client B a chance to reconnect.
4248        server.allow_connections();
4249        cx_b.foreground().advance_clock(Duration::from_secs(10));
4250
4251        // Verify that B sees the new messages upon reconnection, as well as the message client B
4252        // sent while offline.
4253        channel_b
4254            .condition(&cx_b, |channel, _| {
4255                channel_messages(channel)
4256                    == [
4257                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
4258                        ("user_a".to_string(), "oh, hi B.".to_string(), false),
4259                        ("user_a".to_string(), "sup".to_string(), false),
4260                        ("user_b".to_string(), "can you see this?".to_string(), false),
4261                    ]
4262            })
4263            .await;
4264
4265        // Ensure client A and B can communicate normally after reconnection.
4266        channel_a
4267            .update(cx_a, |channel, cx| {
4268                channel.send_message("you online?".to_string(), cx).unwrap()
4269            })
4270            .await
4271            .unwrap();
4272        channel_b
4273            .condition(&cx_b, |channel, _| {
4274                channel_messages(channel)
4275                    == [
4276                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
4277                        ("user_a".to_string(), "oh, hi B.".to_string(), false),
4278                        ("user_a".to_string(), "sup".to_string(), false),
4279                        ("user_b".to_string(), "can you see this?".to_string(), false),
4280                        ("user_a".to_string(), "you online?".to_string(), false),
4281                    ]
4282            })
4283            .await;
4284
4285        channel_b
4286            .update(cx_b, |channel, cx| {
4287                channel.send_message("yep".to_string(), cx).unwrap()
4288            })
4289            .await
4290            .unwrap();
4291        channel_a
4292            .condition(&cx_a, |channel, _| {
4293                channel_messages(channel)
4294                    == [
4295                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
4296                        ("user_a".to_string(), "oh, hi B.".to_string(), false),
4297                        ("user_a".to_string(), "sup".to_string(), false),
4298                        ("user_b".to_string(), "can you see this?".to_string(), false),
4299                        ("user_a".to_string(), "you online?".to_string(), false),
4300                        ("user_b".to_string(), "yep".to_string(), false),
4301                    ]
4302            })
4303            .await;
4304    }
4305
4306    #[gpui::test(iterations = 10)]
4307    async fn test_contacts(
4308        cx_a: &mut TestAppContext,
4309        cx_b: &mut TestAppContext,
4310        cx_c: &mut TestAppContext,
4311    ) {
4312        cx_a.foreground().forbid_parking();
4313        let lang_registry = Arc::new(LanguageRegistry::test());
4314        let fs = FakeFs::new(cx_a.background());
4315
4316        // Connect to a server as 3 clients.
4317        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
4318        let client_a = server.create_client(cx_a, "user_a").await;
4319        let client_b = server.create_client(cx_b, "user_b").await;
4320        let client_c = server.create_client(cx_c, "user_c").await;
4321
4322        // Share a worktree as client A.
4323        fs.insert_tree(
4324            "/a",
4325            json!({
4326                ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
4327            }),
4328        )
4329        .await;
4330
4331        let project_a = cx_a.update(|cx| {
4332            Project::local(
4333                client_a.clone(),
4334                client_a.user_store.clone(),
4335                lang_registry.clone(),
4336                fs.clone(),
4337                cx,
4338            )
4339        });
4340        let (worktree_a, _) = project_a
4341            .update(cx_a, |p, cx| {
4342                p.find_or_create_local_worktree("/a", true, cx)
4343            })
4344            .await
4345            .unwrap();
4346        worktree_a
4347            .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
4348            .await;
4349
4350        client_a
4351            .user_store
4352            .condition(&cx_a, |user_store, _| {
4353                contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
4354            })
4355            .await;
4356        client_b
4357            .user_store
4358            .condition(&cx_b, |user_store, _| {
4359                contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
4360            })
4361            .await;
4362        client_c
4363            .user_store
4364            .condition(&cx_c, |user_store, _| {
4365                contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
4366            })
4367            .await;
4368
4369        let project_id = project_a
4370            .update(cx_a, |project, _| project.next_remote_id())
4371            .await;
4372        project_a
4373            .update(cx_a, |project, cx| project.share(cx))
4374            .await
4375            .unwrap();
4376
4377        let _project_b = Project::remote(
4378            project_id,
4379            client_b.clone(),
4380            client_b.user_store.clone(),
4381            lang_registry.clone(),
4382            fs.clone(),
4383            &mut cx_b.to_async(),
4384        )
4385        .await
4386        .unwrap();
4387
4388        client_a
4389            .user_store
4390            .condition(&cx_a, |user_store, _| {
4391                contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
4392            })
4393            .await;
4394        client_b
4395            .user_store
4396            .condition(&cx_b, |user_store, _| {
4397                contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
4398            })
4399            .await;
4400        client_c
4401            .user_store
4402            .condition(&cx_c, |user_store, _| {
4403                contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
4404            })
4405            .await;
4406
4407        project_a
4408            .condition(&cx_a, |project, _| {
4409                project.collaborators().contains_key(&client_b.peer_id)
4410            })
4411            .await;
4412
4413        cx_a.update(move |_| drop(project_a));
4414        client_a
4415            .user_store
4416            .condition(&cx_a, |user_store, _| contacts(user_store) == vec![])
4417            .await;
4418        client_b
4419            .user_store
4420            .condition(&cx_b, |user_store, _| contacts(user_store) == vec![])
4421            .await;
4422        client_c
4423            .user_store
4424            .condition(&cx_c, |user_store, _| contacts(user_store) == vec![])
4425            .await;
4426
4427        fn contacts(user_store: &UserStore) -> Vec<(&str, Vec<(&str, Vec<&str>)>)> {
4428            user_store
4429                .contacts()
4430                .iter()
4431                .map(|contact| {
4432                    let worktrees = contact
4433                        .projects
4434                        .iter()
4435                        .map(|p| {
4436                            (
4437                                p.worktree_root_names[0].as_str(),
4438                                p.guests.iter().map(|p| p.github_login.as_str()).collect(),
4439                            )
4440                        })
4441                        .collect();
4442                    (contact.user.github_login.as_str(), worktrees)
4443                })
4444                .collect()
4445        }
4446    }
4447
4448    #[gpui::test(iterations = 10)]
4449    async fn test_following(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
4450        cx_a.foreground().forbid_parking();
4451        let fs = FakeFs::new(cx_a.background());
4452
4453        // 2 clients connect to a server.
4454        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
4455        let mut client_a = server.create_client(cx_a, "user_a").await;
4456        let mut client_b = server.create_client(cx_b, "user_b").await;
4457        cx_a.update(editor::init);
4458        cx_b.update(editor::init);
4459
4460        // Client A shares a project.
4461        fs.insert_tree(
4462            "/a",
4463            json!({
4464                ".zed.toml": r#"collaborators = ["user_b"]"#,
4465                "1.txt": "one",
4466                "2.txt": "two",
4467                "3.txt": "three",
4468            }),
4469        )
4470        .await;
4471        let (project_a, worktree_id) = client_a.build_local_project(fs.clone(), "/a", cx_a).await;
4472        project_a
4473            .update(cx_a, |project, cx| project.share(cx))
4474            .await
4475            .unwrap();
4476
4477        // Client B joins the project.
4478        let project_b = client_b
4479            .build_remote_project(
4480                project_a
4481                    .read_with(cx_a, |project, _| project.remote_id())
4482                    .unwrap(),
4483                cx_b,
4484            )
4485            .await;
4486
4487        // Client A opens some editors.
4488        let workspace_a = client_a.build_workspace(&project_a, cx_a);
4489        let pane_a = workspace_a.read_with(cx_a, |workspace, _| workspace.active_pane().clone());
4490        let editor_a1 = workspace_a
4491            .update(cx_a, |workspace, cx| {
4492                workspace.open_path((worktree_id, "1.txt"), cx)
4493            })
4494            .await
4495            .unwrap()
4496            .downcast::<Editor>()
4497            .unwrap();
4498        let editor_a2 = workspace_a
4499            .update(cx_a, |workspace, cx| {
4500                workspace.open_path((worktree_id, "2.txt"), cx)
4501            })
4502            .await
4503            .unwrap()
4504            .downcast::<Editor>()
4505            .unwrap();
4506
4507        // Client B opens an editor.
4508        let workspace_b = client_b.build_workspace(&project_b, cx_b);
4509        let editor_b1 = workspace_b
4510            .update(cx_b, |workspace, cx| {
4511                workspace.open_path((worktree_id, "1.txt"), cx)
4512            })
4513            .await
4514            .unwrap()
4515            .downcast::<Editor>()
4516            .unwrap();
4517
4518        let client_a_id = project_b.read_with(cx_b, |project, _| {
4519            project.collaborators().values().next().unwrap().peer_id
4520        });
4521        let client_b_id = project_a.read_with(cx_a, |project, _| {
4522            project.collaborators().values().next().unwrap().peer_id
4523        });
4524
4525        // When client B starts following client A, all visible view states are replicated to client B.
4526        editor_a1.update(cx_a, |editor, cx| editor.select_ranges([0..1], None, cx));
4527        editor_a2.update(cx_a, |editor, cx| editor.select_ranges([2..3], None, cx));
4528        workspace_b
4529            .update(cx_b, |workspace, cx| {
4530                workspace.toggle_follow(&client_a_id.into(), cx).unwrap()
4531            })
4532            .await
4533            .unwrap();
4534        let editor_b2 = workspace_b.read_with(cx_b, |workspace, cx| {
4535            workspace
4536                .active_item(cx)
4537                .unwrap()
4538                .downcast::<Editor>()
4539                .unwrap()
4540        });
4541        assert!(cx_b.read(|cx| editor_b2.is_focused(cx)));
4542        assert_eq!(
4543            editor_b2.read_with(cx_b, |editor, cx| editor.project_path(cx)),
4544            Some((worktree_id, "2.txt").into())
4545        );
4546        assert_eq!(
4547            editor_b2.read_with(cx_b, |editor, cx| editor.selected_ranges(cx)),
4548            vec![2..3]
4549        );
4550        assert_eq!(
4551            editor_b1.read_with(cx_b, |editor, cx| editor.selected_ranges(cx)),
4552            vec![0..1]
4553        );
4554
4555        // When client A activates a different editor, client B does so as well.
4556        workspace_a.update(cx_a, |workspace, cx| {
4557            workspace.activate_item(&editor_a1, cx)
4558        });
4559        workspace_b
4560            .condition(cx_b, |workspace, cx| {
4561                workspace.active_item(cx).unwrap().id() == editor_b1.id()
4562            })
4563            .await;
4564
4565        // When client A navigates back and forth, client B does so as well.
4566        workspace_a
4567            .update(cx_a, |workspace, cx| {
4568                workspace::Pane::go_back(workspace, None, cx)
4569            })
4570            .await;
4571        workspace_b
4572            .condition(cx_b, |workspace, cx| {
4573                workspace.active_item(cx).unwrap().id() == editor_b2.id()
4574            })
4575            .await;
4576
4577        workspace_a
4578            .update(cx_a, |workspace, cx| {
4579                workspace::Pane::go_forward(workspace, None, cx)
4580            })
4581            .await;
4582        workspace_b
4583            .condition(cx_b, |workspace, cx| {
4584                workspace.active_item(cx).unwrap().id() == editor_b1.id()
4585            })
4586            .await;
4587
4588        // Changes to client A's editor are reflected on client B.
4589        editor_a1.update(cx_a, |editor, cx| {
4590            editor.select_ranges([1..1, 2..2], None, cx);
4591        });
4592        editor_b1
4593            .condition(cx_b, |editor, cx| {
4594                editor.selected_ranges(cx) == vec![1..1, 2..2]
4595            })
4596            .await;
4597
4598        editor_a1.update(cx_a, |editor, cx| editor.set_text("TWO", cx));
4599        editor_b1
4600            .condition(cx_b, |editor, cx| editor.text(cx) == "TWO")
4601            .await;
4602
4603        editor_a1.update(cx_a, |editor, cx| {
4604            editor.select_ranges([3..3], None, cx);
4605            editor.set_scroll_position(vec2f(0., 100.), cx);
4606        });
4607        editor_b1
4608            .condition(cx_b, |editor, cx| editor.selected_ranges(cx) == vec![3..3])
4609            .await;
4610
4611        // After unfollowing, client B stops receiving updates from client A.
4612        workspace_b.update(cx_b, |workspace, cx| {
4613            workspace.unfollow(&workspace.active_pane().clone(), cx)
4614        });
4615        workspace_a.update(cx_a, |workspace, cx| {
4616            workspace.activate_item(&editor_a2, cx)
4617        });
4618        cx_a.foreground().run_until_parked();
4619        assert_eq!(
4620            workspace_b.read_with(cx_b, |workspace, cx| workspace
4621                .active_item(cx)
4622                .unwrap()
4623                .id()),
4624            editor_b1.id()
4625        );
4626
4627        // Client A starts following client B.
4628        workspace_a
4629            .update(cx_a, |workspace, cx| {
4630                workspace.toggle_follow(&client_b_id.into(), cx).unwrap()
4631            })
4632            .await
4633            .unwrap();
4634        assert_eq!(
4635            workspace_a.read_with(cx_a, |workspace, _| workspace.leader_for_pane(&pane_a)),
4636            Some(client_b_id)
4637        );
4638        assert_eq!(
4639            workspace_a.read_with(cx_a, |workspace, cx| workspace
4640                .active_item(cx)
4641                .unwrap()
4642                .id()),
4643            editor_a1.id()
4644        );
4645
4646        // Following interrupts when client B disconnects.
4647        client_b.disconnect(&cx_b.to_async()).unwrap();
4648        cx_a.foreground().run_until_parked();
4649        assert_eq!(
4650            workspace_a.read_with(cx_a, |workspace, _| workspace.leader_for_pane(&pane_a)),
4651            None
4652        );
4653    }
4654
4655    #[gpui::test(iterations = 10)]
4656    async fn test_peers_following_each_other(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
4657        cx_a.foreground().forbid_parking();
4658        let fs = FakeFs::new(cx_a.background());
4659
4660        // 2 clients connect to a server.
4661        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
4662        let mut client_a = server.create_client(cx_a, "user_a").await;
4663        let mut client_b = server.create_client(cx_b, "user_b").await;
4664        cx_a.update(editor::init);
4665        cx_b.update(editor::init);
4666
4667        // Client A shares a project.
4668        fs.insert_tree(
4669            "/a",
4670            json!({
4671                ".zed.toml": r#"collaborators = ["user_b"]"#,
4672                "1.txt": "one",
4673                "2.txt": "two",
4674                "3.txt": "three",
4675                "4.txt": "four",
4676            }),
4677        )
4678        .await;
4679        let (project_a, worktree_id) = client_a.build_local_project(fs.clone(), "/a", cx_a).await;
4680        project_a
4681            .update(cx_a, |project, cx| project.share(cx))
4682            .await
4683            .unwrap();
4684
4685        // Client B joins the project.
4686        let project_b = client_b
4687            .build_remote_project(
4688                project_a
4689                    .read_with(cx_a, |project, _| project.remote_id())
4690                    .unwrap(),
4691                cx_b,
4692            )
4693            .await;
4694
4695        // Client A opens some editors.
4696        let workspace_a = client_a.build_workspace(&project_a, cx_a);
4697        let pane_a1 = workspace_a.read_with(cx_a, |workspace, _| workspace.active_pane().clone());
4698        let _editor_a1 = workspace_a
4699            .update(cx_a, |workspace, cx| {
4700                workspace.open_path((worktree_id, "1.txt"), cx)
4701            })
4702            .await
4703            .unwrap()
4704            .downcast::<Editor>()
4705            .unwrap();
4706
4707        // Client B opens an editor.
4708        let workspace_b = client_b.build_workspace(&project_b, cx_b);
4709        let pane_b1 = workspace_b.read_with(cx_b, |workspace, _| workspace.active_pane().clone());
4710        let _editor_b1 = workspace_b
4711            .update(cx_b, |workspace, cx| {
4712                workspace.open_path((worktree_id, "2.txt"), cx)
4713            })
4714            .await
4715            .unwrap()
4716            .downcast::<Editor>()
4717            .unwrap();
4718
4719        // Clients A and B follow each other in split panes
4720        workspace_a
4721            .update(cx_a, |workspace, cx| {
4722                workspace.split_pane(workspace.active_pane().clone(), SplitDirection::Right, cx);
4723                assert_ne!(*workspace.active_pane(), pane_a1);
4724                let leader_id = *project_a.read(cx).collaborators().keys().next().unwrap();
4725                workspace
4726                    .toggle_follow(&workspace::ToggleFollow(leader_id), cx)
4727                    .unwrap()
4728            })
4729            .await
4730            .unwrap();
4731        workspace_b
4732            .update(cx_b, |workspace, cx| {
4733                workspace.split_pane(workspace.active_pane().clone(), SplitDirection::Right, cx);
4734                assert_ne!(*workspace.active_pane(), pane_b1);
4735                let leader_id = *project_b.read(cx).collaborators().keys().next().unwrap();
4736                workspace
4737                    .toggle_follow(&workspace::ToggleFollow(leader_id), cx)
4738                    .unwrap()
4739            })
4740            .await
4741            .unwrap();
4742
4743        workspace_a
4744            .update(cx_a, |workspace, cx| {
4745                workspace.activate_next_pane(cx);
4746                assert_eq!(*workspace.active_pane(), pane_a1);
4747                workspace.open_path((worktree_id, "3.txt"), cx)
4748            })
4749            .await
4750            .unwrap();
4751        workspace_b
4752            .update(cx_b, |workspace, cx| {
4753                workspace.activate_next_pane(cx);
4754                assert_eq!(*workspace.active_pane(), pane_b1);
4755                workspace.open_path((worktree_id, "4.txt"), cx)
4756            })
4757            .await
4758            .unwrap();
4759        cx_a.foreground().run_until_parked();
4760
4761        // Ensure leader updates don't change the active pane of followers
4762        workspace_a.read_with(cx_a, |workspace, _| {
4763            assert_eq!(*workspace.active_pane(), pane_a1);
4764        });
4765        workspace_b.read_with(cx_b, |workspace, _| {
4766            assert_eq!(*workspace.active_pane(), pane_b1);
4767        });
4768
4769        // Ensure peers following each other doesn't cause an infinite loop.
4770        assert_eq!(
4771            workspace_a.read_with(cx_a, |workspace, cx| workspace
4772                .active_item(cx)
4773                .unwrap()
4774                .project_path(cx)),
4775            Some((worktree_id, "3.txt").into())
4776        );
4777        workspace_a.update(cx_a, |workspace, cx| {
4778            assert_eq!(
4779                workspace.active_item(cx).unwrap().project_path(cx),
4780                Some((worktree_id, "3.txt").into())
4781            );
4782            workspace.activate_next_pane(cx);
4783            assert_eq!(
4784                workspace.active_item(cx).unwrap().project_path(cx),
4785                Some((worktree_id, "4.txt").into())
4786            );
4787        });
4788        workspace_b.update(cx_b, |workspace, cx| {
4789            assert_eq!(
4790                workspace.active_item(cx).unwrap().project_path(cx),
4791                Some((worktree_id, "4.txt").into())
4792            );
4793            workspace.activate_next_pane(cx);
4794            assert_eq!(
4795                workspace.active_item(cx).unwrap().project_path(cx),
4796                Some((worktree_id, "3.txt").into())
4797            );
4798        });
4799    }
4800
4801    #[gpui::test(iterations = 10)]
4802    async fn test_auto_unfollowing(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
4803        cx_a.foreground().forbid_parking();
4804        let fs = FakeFs::new(cx_a.background());
4805
4806        // 2 clients connect to a server.
4807        let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
4808        let mut client_a = server.create_client(cx_a, "user_a").await;
4809        let mut client_b = server.create_client(cx_b, "user_b").await;
4810        cx_a.update(editor::init);
4811        cx_b.update(editor::init);
4812
4813        // Client A shares a project.
4814        fs.insert_tree(
4815            "/a",
4816            json!({
4817                ".zed.toml": r#"collaborators = ["user_b"]"#,
4818                "1.txt": "one",
4819                "2.txt": "two",
4820                "3.txt": "three",
4821            }),
4822        )
4823        .await;
4824        let (project_a, worktree_id) = client_a.build_local_project(fs.clone(), "/a", cx_a).await;
4825        project_a
4826            .update(cx_a, |project, cx| project.share(cx))
4827            .await
4828            .unwrap();
4829
4830        // Client B joins the project.
4831        let project_b = client_b
4832            .build_remote_project(
4833                project_a
4834                    .read_with(cx_a, |project, _| project.remote_id())
4835                    .unwrap(),
4836                cx_b,
4837            )
4838            .await;
4839
4840        // Client A opens some editors.
4841        let workspace_a = client_a.build_workspace(&project_a, cx_a);
4842        let _editor_a1 = workspace_a
4843            .update(cx_a, |workspace, cx| {
4844                workspace.open_path((worktree_id, "1.txt"), cx)
4845            })
4846            .await
4847            .unwrap()
4848            .downcast::<Editor>()
4849            .unwrap();
4850
4851        // Client B starts following client A.
4852        let workspace_b = client_b.build_workspace(&project_b, cx_b);
4853        let pane_b = workspace_b.read_with(cx_b, |workspace, _| workspace.active_pane().clone());
4854        let leader_id = project_b.read_with(cx_b, |project, _| {
4855            project.collaborators().values().next().unwrap().peer_id
4856        });
4857        workspace_b
4858            .update(cx_b, |workspace, cx| {
4859                workspace.toggle_follow(&leader_id.into(), cx).unwrap()
4860            })
4861            .await
4862            .unwrap();
4863        assert_eq!(
4864            workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
4865            Some(leader_id)
4866        );
4867        let editor_b2 = workspace_b.read_with(cx_b, |workspace, cx| {
4868            workspace
4869                .active_item(cx)
4870                .unwrap()
4871                .downcast::<Editor>()
4872                .unwrap()
4873        });
4874
4875        // When client B moves, it automatically stops following client A.
4876        editor_b2.update(cx_b, |editor, cx| editor.move_right(&editor::MoveRight, cx));
4877        assert_eq!(
4878            workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
4879            None
4880        );
4881
4882        workspace_b
4883            .update(cx_b, |workspace, cx| {
4884                workspace.toggle_follow(&leader_id.into(), cx).unwrap()
4885            })
4886            .await
4887            .unwrap();
4888        assert_eq!(
4889            workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
4890            Some(leader_id)
4891        );
4892
4893        // When client B edits, it automatically stops following client A.
4894        editor_b2.update(cx_b, |editor, cx| editor.insert("X", cx));
4895        assert_eq!(
4896            workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
4897            None
4898        );
4899
4900        workspace_b
4901            .update(cx_b, |workspace, cx| {
4902                workspace.toggle_follow(&leader_id.into(), cx).unwrap()
4903            })
4904            .await
4905            .unwrap();
4906        assert_eq!(
4907            workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
4908            Some(leader_id)
4909        );
4910
4911        // When client B scrolls, it automatically stops following client A.
4912        editor_b2.update(cx_b, |editor, cx| {
4913            editor.set_scroll_position(vec2f(0., 3.), cx)
4914        });
4915        assert_eq!(
4916            workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
4917            None
4918        );
4919
4920        workspace_b
4921            .update(cx_b, |workspace, cx| {
4922                workspace.toggle_follow(&leader_id.into(), cx).unwrap()
4923            })
4924            .await
4925            .unwrap();
4926        assert_eq!(
4927            workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
4928            Some(leader_id)
4929        );
4930
4931        // When client B activates a different pane, it continues following client A in the original pane.
4932        workspace_b.update(cx_b, |workspace, cx| {
4933            workspace.split_pane(pane_b.clone(), SplitDirection::Right, cx)
4934        });
4935        assert_eq!(
4936            workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
4937            Some(leader_id)
4938        );
4939
4940        workspace_b.update(cx_b, |workspace, cx| workspace.activate_next_pane(cx));
4941        assert_eq!(
4942            workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
4943            Some(leader_id)
4944        );
4945
4946        // When client B activates a different item in the original pane, it automatically stops following client A.
4947        workspace_b
4948            .update(cx_b, |workspace, cx| {
4949                workspace.open_path((worktree_id, "2.txt"), cx)
4950            })
4951            .await
4952            .unwrap();
4953        assert_eq!(
4954            workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
4955            None
4956        );
4957    }
4958
4959    #[gpui::test(iterations = 100)]
4960    async fn test_random_collaboration(cx: &mut TestAppContext, rng: StdRng) {
4961        cx.foreground().forbid_parking();
4962        let max_peers = env::var("MAX_PEERS")
4963            .map(|i| i.parse().expect("invalid `MAX_PEERS` variable"))
4964            .unwrap_or(5);
4965        let max_operations = env::var("OPERATIONS")
4966            .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
4967            .unwrap_or(10);
4968
4969        let rng = Arc::new(Mutex::new(rng));
4970
4971        let guest_lang_registry = Arc::new(LanguageRegistry::test());
4972        let host_language_registry = Arc::new(LanguageRegistry::test());
4973
4974        let fs = FakeFs::new(cx.background());
4975        fs.insert_tree(
4976            "/_collab",
4977            json!({
4978                ".zed.toml": r#"collaborators = ["guest-1", "guest-2", "guest-3", "guest-4", "guest-5"]"#
4979            }),
4980        )
4981        .await;
4982
4983        let operations = Rc::new(Cell::new(0));
4984        let mut server = TestServer::start(cx.foreground(), cx.background()).await;
4985        let mut clients = Vec::new();
4986        let files = Arc::new(Mutex::new(Vec::new()));
4987
4988        let mut next_entity_id = 100000;
4989        let mut host_cx = TestAppContext::new(
4990            cx.foreground_platform(),
4991            cx.platform(),
4992            cx.foreground(),
4993            cx.background(),
4994            cx.font_cache(),
4995            cx.leak_detector(),
4996            next_entity_id,
4997        );
4998        let host = server.create_client(&mut host_cx, "host").await;
4999        let host_project = host_cx.update(|cx| {
5000            Project::local(
5001                host.client.clone(),
5002                host.user_store.clone(),
5003                host_language_registry.clone(),
5004                fs.clone(),
5005                cx,
5006            )
5007        });
5008        let host_project_id = host_project
5009            .update(&mut host_cx, |p, _| p.next_remote_id())
5010            .await;
5011
5012        let (collab_worktree, _) = host_project
5013            .update(&mut host_cx, |project, cx| {
5014                project.find_or_create_local_worktree("/_collab", true, cx)
5015            })
5016            .await
5017            .unwrap();
5018        collab_worktree
5019            .read_with(&host_cx, |tree, _| tree.as_local().unwrap().scan_complete())
5020            .await;
5021        host_project
5022            .update(&mut host_cx, |project, cx| project.share(cx))
5023            .await
5024            .unwrap();
5025
5026        // Set up fake language servers.
5027        let mut language = Language::new(
5028            LanguageConfig {
5029                name: "Rust".into(),
5030                path_suffixes: vec!["rs".to_string()],
5031                ..Default::default()
5032            },
5033            None,
5034        );
5035        let _fake_servers = language.set_fake_lsp_adapter(FakeLspAdapter {
5036            name: "the-fake-language-server",
5037            capabilities: lsp::LanguageServer::full_capabilities(),
5038            initializer: Some(Box::new({
5039                let rng = rng.clone();
5040                let files = files.clone();
5041                let project = host_project.downgrade();
5042                move |fake_server: &mut FakeLanguageServer| {
5043                    fake_server.handle_request::<lsp::request::Completion, _, _>(
5044                        |_, _| async move {
5045                            Ok(Some(lsp::CompletionResponse::Array(vec![
5046                                lsp::CompletionItem {
5047                                    text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
5048                                        range: lsp::Range::new(
5049                                            lsp::Position::new(0, 0),
5050                                            lsp::Position::new(0, 0),
5051                                        ),
5052                                        new_text: "the-new-text".to_string(),
5053                                    })),
5054                                    ..Default::default()
5055                                },
5056                            ])))
5057                        },
5058                    );
5059
5060                    fake_server.handle_request::<lsp::request::CodeActionRequest, _, _>(
5061                        |_, _| async move {
5062                            Ok(Some(vec![lsp::CodeActionOrCommand::CodeAction(
5063                                lsp::CodeAction {
5064                                    title: "the-code-action".to_string(),
5065                                    ..Default::default()
5066                                },
5067                            )]))
5068                        },
5069                    );
5070
5071                    fake_server.handle_request::<lsp::request::PrepareRenameRequest, _, _>(
5072                        |params, _| async move {
5073                            Ok(Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(
5074                                params.position,
5075                                params.position,
5076                            ))))
5077                        },
5078                    );
5079
5080                    fake_server.handle_request::<lsp::request::GotoDefinition, _, _>({
5081                        let files = files.clone();
5082                        let rng = rng.clone();
5083                        move |_, _| {
5084                            let files = files.clone();
5085                            let rng = rng.clone();
5086                            async move {
5087                                let files = files.lock();
5088                                let mut rng = rng.lock();
5089                                let count = rng.gen_range::<usize, _>(1..3);
5090                                let files = (0..count)
5091                                    .map(|_| files.choose(&mut *rng).unwrap())
5092                                    .collect::<Vec<_>>();
5093                                log::info!("LSP: Returning definitions in files {:?}", &files);
5094                                Ok(Some(lsp::GotoDefinitionResponse::Array(
5095                                    files
5096                                        .into_iter()
5097                                        .map(|file| lsp::Location {
5098                                            uri: lsp::Url::from_file_path(file).unwrap(),
5099                                            range: Default::default(),
5100                                        })
5101                                        .collect(),
5102                                )))
5103                            }
5104                        }
5105                    });
5106
5107                    fake_server.handle_request::<lsp::request::DocumentHighlightRequest, _, _>({
5108                        let rng = rng.clone();
5109                        let project = project.clone();
5110                        move |params, mut cx| {
5111                            let highlights = if let Some(project) = project.upgrade(&cx) {
5112                                project.update(&mut cx, |project, cx| {
5113                                    let path = params
5114                                        .text_document_position_params
5115                                        .text_document
5116                                        .uri
5117                                        .to_file_path()
5118                                        .unwrap();
5119                                    let (worktree, relative_path) =
5120                                        project.find_local_worktree(&path, cx)?;
5121                                    let project_path =
5122                                        ProjectPath::from((worktree.read(cx).id(), relative_path));
5123                                    let buffer =
5124                                        project.get_open_buffer(&project_path, cx)?.read(cx);
5125
5126                                    let mut highlights = Vec::new();
5127                                    let highlight_count = rng.lock().gen_range(1..=5);
5128                                    let mut prev_end = 0;
5129                                    for _ in 0..highlight_count {
5130                                        let range =
5131                                            buffer.random_byte_range(prev_end, &mut *rng.lock());
5132
5133                                        highlights.push(lsp::DocumentHighlight {
5134                                            range: range_to_lsp(range.to_point_utf16(buffer)),
5135                                            kind: Some(lsp::DocumentHighlightKind::READ),
5136                                        });
5137                                        prev_end = range.end;
5138                                    }
5139                                    Some(highlights)
5140                                })
5141                            } else {
5142                                None
5143                            };
5144                            async move { Ok(highlights) }
5145                        }
5146                    });
5147                }
5148            })),
5149            ..Default::default()
5150        });
5151        host_language_registry.add(Arc::new(language));
5152
5153        clients.push(cx.foreground().spawn(host.simulate_host(
5154            host_project,
5155            files,
5156            operations.clone(),
5157            max_operations,
5158            rng.clone(),
5159            host_cx,
5160        )));
5161
5162        while operations.get() < max_operations {
5163            cx.background().simulate_random_delay().await;
5164            if clients.len() >= max_peers {
5165                break;
5166            } else if rng.lock().gen_bool(0.05) {
5167                operations.set(operations.get() + 1);
5168
5169                let guest_id = clients.len();
5170                log::info!("Adding guest {}", guest_id);
5171                next_entity_id += 100000;
5172                let mut guest_cx = TestAppContext::new(
5173                    cx.foreground_platform(),
5174                    cx.platform(),
5175                    cx.foreground(),
5176                    cx.background(),
5177                    cx.font_cache(),
5178                    cx.leak_detector(),
5179                    next_entity_id,
5180                );
5181                let guest = server
5182                    .create_client(&mut guest_cx, &format!("guest-{}", guest_id))
5183                    .await;
5184                let guest_project = Project::remote(
5185                    host_project_id,
5186                    guest.client.clone(),
5187                    guest.user_store.clone(),
5188                    guest_lang_registry.clone(),
5189                    FakeFs::new(cx.background()),
5190                    &mut guest_cx.to_async(),
5191                )
5192                .await
5193                .unwrap();
5194                clients.push(cx.foreground().spawn(guest.simulate_guest(
5195                    guest_id,
5196                    guest_project,
5197                    operations.clone(),
5198                    max_operations,
5199                    rng.clone(),
5200                    guest_cx,
5201                )));
5202
5203                log::info!("Guest {} added", guest_id);
5204            }
5205        }
5206
5207        let mut clients = futures::future::join_all(clients).await;
5208        cx.foreground().run_until_parked();
5209
5210        let (host_client, mut host_cx) = clients.remove(0);
5211        let host_project = host_client.project.as_ref().unwrap();
5212        let host_worktree_snapshots = host_project.read_with(&host_cx, |project, cx| {
5213            project
5214                .worktrees(cx)
5215                .map(|worktree| {
5216                    let snapshot = worktree.read(cx).snapshot();
5217                    (snapshot.id(), snapshot)
5218                })
5219                .collect::<BTreeMap<_, _>>()
5220        });
5221
5222        host_client
5223            .project
5224            .as_ref()
5225            .unwrap()
5226            .read_with(&host_cx, |project, cx| project.check_invariants(cx));
5227
5228        for (guest_client, mut guest_cx) in clients.into_iter() {
5229            let guest_id = guest_client.client.id();
5230            let worktree_snapshots =
5231                guest_client
5232                    .project
5233                    .as_ref()
5234                    .unwrap()
5235                    .read_with(&guest_cx, |project, cx| {
5236                        project
5237                            .worktrees(cx)
5238                            .map(|worktree| {
5239                                let worktree = worktree.read(cx);
5240                                (worktree.id(), worktree.snapshot())
5241                            })
5242                            .collect::<BTreeMap<_, _>>()
5243                    });
5244
5245            assert_eq!(
5246                worktree_snapshots.keys().collect::<Vec<_>>(),
5247                host_worktree_snapshots.keys().collect::<Vec<_>>(),
5248                "guest {} has different worktrees than the host",
5249                guest_id
5250            );
5251            for (id, host_snapshot) in &host_worktree_snapshots {
5252                let guest_snapshot = &worktree_snapshots[id];
5253                assert_eq!(
5254                    guest_snapshot.root_name(),
5255                    host_snapshot.root_name(),
5256                    "guest {} has different root name than the host for worktree {}",
5257                    guest_id,
5258                    id
5259                );
5260                assert_eq!(
5261                    guest_snapshot.entries(false).collect::<Vec<_>>(),
5262                    host_snapshot.entries(false).collect::<Vec<_>>(),
5263                    "guest {} has different snapshot than the host for worktree {}",
5264                    guest_id,
5265                    id
5266                );
5267            }
5268
5269            guest_client
5270                .project
5271                .as_ref()
5272                .unwrap()
5273                .read_with(&guest_cx, |project, cx| project.check_invariants(cx));
5274
5275            for guest_buffer in &guest_client.buffers {
5276                let buffer_id = guest_buffer.read_with(&guest_cx, |buffer, _| buffer.remote_id());
5277                let host_buffer = host_project.read_with(&host_cx, |project, cx| {
5278                    project.buffer_for_id(buffer_id, cx).expect(&format!(
5279                        "host does not have buffer for guest:{}, peer:{}, id:{}",
5280                        guest_id, guest_client.peer_id, buffer_id
5281                    ))
5282                });
5283                let path = host_buffer
5284                    .read_with(&host_cx, |buffer, cx| buffer.file().unwrap().full_path(cx));
5285
5286                assert_eq!(
5287                    guest_buffer.read_with(&guest_cx, |buffer, _| buffer.deferred_ops_len()),
5288                    0,
5289                    "guest {}, buffer {}, path {:?} has deferred operations",
5290                    guest_id,
5291                    buffer_id,
5292                    path,
5293                );
5294                assert_eq!(
5295                    guest_buffer.read_with(&guest_cx, |buffer, _| buffer.text()),
5296                    host_buffer.read_with(&host_cx, |buffer, _| buffer.text()),
5297                    "guest {}, buffer {}, path {:?}, differs from the host's buffer",
5298                    guest_id,
5299                    buffer_id,
5300                    path
5301                );
5302            }
5303
5304            guest_cx.update(|_| drop(guest_client));
5305        }
5306
5307        host_cx.update(|_| drop(host_client));
5308    }
5309
5310    struct TestServer {
5311        peer: Arc<Peer>,
5312        app_state: Arc<AppState>,
5313        server: Arc<Server>,
5314        foreground: Rc<executor::Foreground>,
5315        notifications: mpsc::UnboundedReceiver<()>,
5316        connection_killers: Arc<Mutex<HashMap<UserId, barrier::Sender>>>,
5317        forbid_connections: Arc<AtomicBool>,
5318        _test_db: TestDb,
5319    }
5320
5321    impl TestServer {
5322        async fn start(
5323            foreground: Rc<executor::Foreground>,
5324            background: Arc<executor::Background>,
5325        ) -> Self {
5326            let test_db = TestDb::fake(background);
5327            let app_state = Self::build_app_state(&test_db).await;
5328            let peer = Peer::new();
5329            let notifications = mpsc::unbounded();
5330            let server = Server::new(app_state.clone(), peer.clone(), Some(notifications.0));
5331            Self {
5332                peer,
5333                app_state,
5334                server,
5335                foreground,
5336                notifications: notifications.1,
5337                connection_killers: Default::default(),
5338                forbid_connections: Default::default(),
5339                _test_db: test_db,
5340            }
5341        }
5342
5343        async fn create_client(&mut self, cx: &mut TestAppContext, name: &str) -> TestClient {
5344            cx.update(|cx| {
5345                let settings = Settings::test(cx);
5346                cx.set_global(settings);
5347            });
5348
5349            let http = FakeHttpClient::with_404_response();
5350            let user_id = self.app_state.db.create_user(name, false).await.unwrap();
5351            let client_name = name.to_string();
5352            let mut client = Client::new(http.clone());
5353            let server = self.server.clone();
5354            let connection_killers = self.connection_killers.clone();
5355            let forbid_connections = self.forbid_connections.clone();
5356            let (connection_id_tx, mut connection_id_rx) = mpsc::channel(16);
5357
5358            Arc::get_mut(&mut client)
5359                .unwrap()
5360                .override_authenticate(move |cx| {
5361                    cx.spawn(|_| async move {
5362                        let access_token = "the-token".to_string();
5363                        Ok(Credentials {
5364                            user_id: user_id.0 as u64,
5365                            access_token,
5366                        })
5367                    })
5368                })
5369                .override_establish_connection(move |credentials, cx| {
5370                    assert_eq!(credentials.user_id, user_id.0 as u64);
5371                    assert_eq!(credentials.access_token, "the-token");
5372
5373                    let server = server.clone();
5374                    let connection_killers = connection_killers.clone();
5375                    let forbid_connections = forbid_connections.clone();
5376                    let client_name = client_name.clone();
5377                    let connection_id_tx = connection_id_tx.clone();
5378                    cx.spawn(move |cx| async move {
5379                        if forbid_connections.load(SeqCst) {
5380                            Err(EstablishConnectionError::other(anyhow!(
5381                                "server is forbidding connections"
5382                            )))
5383                        } else {
5384                            let (client_conn, server_conn, kill_conn) =
5385                                Connection::in_memory(cx.background());
5386                            connection_killers.lock().insert(user_id, kill_conn);
5387                            cx.background()
5388                                .spawn(server.handle_connection(
5389                                    server_conn,
5390                                    client_name,
5391                                    user_id,
5392                                    Some(connection_id_tx),
5393                                    cx.background(),
5394                                ))
5395                                .detach();
5396                            Ok(client_conn)
5397                        }
5398                    })
5399                });
5400
5401            client
5402                .authenticate_and_connect(false, &cx.to_async())
5403                .await
5404                .unwrap();
5405
5406            Channel::init(&client);
5407            Project::init(&client);
5408            cx.update(|cx| {
5409                workspace::init(&client, cx);
5410            });
5411
5412            let peer_id = PeerId(connection_id_rx.next().await.unwrap().0);
5413            let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http, cx));
5414
5415            let client = TestClient {
5416                client,
5417                peer_id,
5418                user_store,
5419                language_registry: Arc::new(LanguageRegistry::test()),
5420                project: Default::default(),
5421                buffers: Default::default(),
5422            };
5423            client.wait_for_current_user(cx).await;
5424            client
5425        }
5426
5427        fn disconnect_client(&self, user_id: UserId) {
5428            self.connection_killers.lock().remove(&user_id);
5429        }
5430
5431        fn forbid_connections(&self) {
5432            self.forbid_connections.store(true, SeqCst);
5433        }
5434
5435        fn allow_connections(&self) {
5436            self.forbid_connections.store(false, SeqCst);
5437        }
5438
5439        async fn build_app_state(test_db: &TestDb) -> Arc<AppState> {
5440            let mut config = Config::default();
5441            config.session_secret = "a".repeat(32);
5442            config.database_url = test_db.url.clone();
5443            let github_client = github::AppClient::test();
5444            Arc::new(AppState {
5445                db: test_db.db().clone(),
5446                handlebars: Default::default(),
5447                auth_client: auth::build_client("", ""),
5448                repo_client: github::RepoClient::test(&github_client),
5449                github_client,
5450                config,
5451            })
5452        }
5453
5454        async fn state<'a>(&'a self) -> RwLockReadGuard<'a, Store> {
5455            self.server.store.read()
5456        }
5457
5458        async fn condition<F>(&mut self, mut predicate: F)
5459        where
5460            F: FnMut(&Store) -> bool,
5461        {
5462            async_std::future::timeout(Duration::from_millis(500), async {
5463                while !(predicate)(&*self.server.store.read()) {
5464                    self.foreground.start_waiting();
5465                    self.notifications.next().await;
5466                    self.foreground.finish_waiting();
5467                }
5468            })
5469            .await
5470            .expect("condition timed out");
5471        }
5472    }
5473
5474    impl Drop for TestServer {
5475        fn drop(&mut self) {
5476            self.peer.reset();
5477        }
5478    }
5479
5480    struct TestClient {
5481        client: Arc<Client>,
5482        pub peer_id: PeerId,
5483        pub user_store: ModelHandle<UserStore>,
5484        language_registry: Arc<LanguageRegistry>,
5485        project: Option<ModelHandle<Project>>,
5486        buffers: HashSet<ModelHandle<language::Buffer>>,
5487    }
5488
5489    impl Deref for TestClient {
5490        type Target = Arc<Client>;
5491
5492        fn deref(&self) -> &Self::Target {
5493            &self.client
5494        }
5495    }
5496
5497    impl TestClient {
5498        pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
5499            UserId::from_proto(
5500                self.user_store
5501                    .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
5502            )
5503        }
5504
5505        async fn wait_for_current_user(&self, cx: &TestAppContext) {
5506            let mut authed_user = self
5507                .user_store
5508                .read_with(cx, |user_store, _| user_store.watch_current_user());
5509            while authed_user.next().await.unwrap().is_none() {}
5510        }
5511
5512        async fn build_local_project(
5513            &mut self,
5514            fs: Arc<FakeFs>,
5515            root_path: impl AsRef<Path>,
5516            cx: &mut TestAppContext,
5517        ) -> (ModelHandle<Project>, WorktreeId) {
5518            let project = cx.update(|cx| {
5519                Project::local(
5520                    self.client.clone(),
5521                    self.user_store.clone(),
5522                    self.language_registry.clone(),
5523                    fs,
5524                    cx,
5525                )
5526            });
5527            self.project = Some(project.clone());
5528            let (worktree, _) = project
5529                .update(cx, |p, cx| {
5530                    p.find_or_create_local_worktree(root_path, true, cx)
5531                })
5532                .await
5533                .unwrap();
5534            worktree
5535                .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
5536                .await;
5537            project
5538                .update(cx, |project, _| project.next_remote_id())
5539                .await;
5540            (project, worktree.read_with(cx, |tree, _| tree.id()))
5541        }
5542
5543        async fn build_remote_project(
5544            &mut self,
5545            project_id: u64,
5546            cx: &mut TestAppContext,
5547        ) -> ModelHandle<Project> {
5548            let project = Project::remote(
5549                project_id,
5550                self.client.clone(),
5551                self.user_store.clone(),
5552                self.language_registry.clone(),
5553                FakeFs::new(cx.background()),
5554                &mut cx.to_async(),
5555            )
5556            .await
5557            .unwrap();
5558            self.project = Some(project.clone());
5559            project
5560        }
5561
5562        fn build_workspace(
5563            &self,
5564            project: &ModelHandle<Project>,
5565            cx: &mut TestAppContext,
5566        ) -> ViewHandle<Workspace> {
5567            let (window_id, _) = cx.add_window(|_| EmptyView);
5568            cx.add_view(window_id, |cx| {
5569                let fs = project.read(cx).fs().clone();
5570                Workspace::new(
5571                    &WorkspaceParams {
5572                        fs,
5573                        project: project.clone(),
5574                        user_store: self.user_store.clone(),
5575                        languages: self.language_registry.clone(),
5576                        channel_list: cx.add_model(|cx| {
5577                            ChannelList::new(self.user_store.clone(), self.client.clone(), cx)
5578                        }),
5579                        client: self.client.clone(),
5580                    },
5581                    cx,
5582                )
5583            })
5584        }
5585
5586        async fn simulate_host(
5587            mut self,
5588            project: ModelHandle<Project>,
5589            files: Arc<Mutex<Vec<PathBuf>>>,
5590            operations: Rc<Cell<usize>>,
5591            max_operations: usize,
5592            rng: Arc<Mutex<StdRng>>,
5593            mut cx: TestAppContext,
5594        ) -> (Self, TestAppContext) {
5595            let fs = project.read_with(&cx, |project, _| project.fs().clone());
5596            while operations.get() < max_operations {
5597                operations.set(operations.get() + 1);
5598
5599                let distribution = rng.lock().gen_range::<usize, _>(0..100);
5600                match distribution {
5601                    0..=20 if !files.lock().is_empty() => {
5602                        let path = files.lock().choose(&mut *rng.lock()).unwrap().clone();
5603                        let mut path = path.as_path();
5604                        while let Some(parent_path) = path.parent() {
5605                            path = parent_path;
5606                            if rng.lock().gen() {
5607                                break;
5608                            }
5609                        }
5610
5611                        log::info!("Host: find/create local worktree {:?}", path);
5612                        let find_or_create_worktree = project.update(&mut cx, |project, cx| {
5613                            project.find_or_create_local_worktree(path, true, cx)
5614                        });
5615                        let find_or_create_worktree = async move {
5616                            find_or_create_worktree.await.unwrap();
5617                        };
5618                        if rng.lock().gen() {
5619                            cx.background().spawn(find_or_create_worktree).detach();
5620                        } else {
5621                            find_or_create_worktree.await;
5622                        }
5623                    }
5624                    10..=80 if !files.lock().is_empty() => {
5625                        let buffer = if self.buffers.is_empty() || rng.lock().gen() {
5626                            let file = files.lock().choose(&mut *rng.lock()).unwrap().clone();
5627                            let (worktree, path) = project
5628                                .update(&mut cx, |project, cx| {
5629                                    project.find_or_create_local_worktree(file.clone(), true, cx)
5630                                })
5631                                .await
5632                                .unwrap();
5633                            let project_path =
5634                                worktree.read_with(&cx, |worktree, _| (worktree.id(), path));
5635                            log::info!(
5636                                "Host: opening path {:?}, worktree {}, relative_path {:?}",
5637                                file,
5638                                project_path.0,
5639                                project_path.1
5640                            );
5641                            let buffer = project
5642                                .update(&mut cx, |project, cx| {
5643                                    project.open_buffer(project_path, cx)
5644                                })
5645                                .await
5646                                .unwrap();
5647                            self.buffers.insert(buffer.clone());
5648                            buffer
5649                        } else {
5650                            self.buffers
5651                                .iter()
5652                                .choose(&mut *rng.lock())
5653                                .unwrap()
5654                                .clone()
5655                        };
5656
5657                        if rng.lock().gen_bool(0.1) {
5658                            cx.update(|cx| {
5659                                log::info!(
5660                                    "Host: dropping buffer {:?}",
5661                                    buffer.read(cx).file().unwrap().full_path(cx)
5662                                );
5663                                self.buffers.remove(&buffer);
5664                                drop(buffer);
5665                            });
5666                        } else {
5667                            buffer.update(&mut cx, |buffer, cx| {
5668                                log::info!(
5669                                    "Host: updating buffer {:?} ({})",
5670                                    buffer.file().unwrap().full_path(cx),
5671                                    buffer.remote_id()
5672                                );
5673                                buffer.randomly_edit(&mut *rng.lock(), 5, cx)
5674                            });
5675                        }
5676                    }
5677                    _ => loop {
5678                        let path_component_count = rng.lock().gen_range::<usize, _>(1..=5);
5679                        let mut path = PathBuf::new();
5680                        path.push("/");
5681                        for _ in 0..path_component_count {
5682                            let letter = rng.lock().gen_range(b'a'..=b'z');
5683                            path.push(std::str::from_utf8(&[letter]).unwrap());
5684                        }
5685                        path.set_extension("rs");
5686                        let parent_path = path.parent().unwrap();
5687
5688                        log::info!("Host: creating file {:?}", path,);
5689
5690                        if fs.create_dir(&parent_path).await.is_ok()
5691                            && fs.create_file(&path, Default::default()).await.is_ok()
5692                        {
5693                            files.lock().push(path);
5694                            break;
5695                        } else {
5696                            log::info!("Host: cannot create file");
5697                        }
5698                    },
5699                }
5700
5701                cx.background().simulate_random_delay().await;
5702            }
5703
5704            log::info!("Host done");
5705
5706            self.project = Some(project);
5707            (self, cx)
5708        }
5709
5710        pub async fn simulate_guest(
5711            mut self,
5712            guest_id: usize,
5713            project: ModelHandle<Project>,
5714            operations: Rc<Cell<usize>>,
5715            max_operations: usize,
5716            rng: Arc<Mutex<StdRng>>,
5717            mut cx: TestAppContext,
5718        ) -> (Self, TestAppContext) {
5719            while operations.get() < max_operations {
5720                let buffer = if self.buffers.is_empty() || rng.lock().gen() {
5721                    let worktree = if let Some(worktree) = project.read_with(&cx, |project, cx| {
5722                        project
5723                            .worktrees(&cx)
5724                            .filter(|worktree| {
5725                                let worktree = worktree.read(cx);
5726                                worktree.is_visible()
5727                                    && worktree.entries(false).any(|e| e.is_file())
5728                            })
5729                            .choose(&mut *rng.lock())
5730                    }) {
5731                        worktree
5732                    } else {
5733                        cx.background().simulate_random_delay().await;
5734                        continue;
5735                    };
5736
5737                    operations.set(operations.get() + 1);
5738                    let (worktree_root_name, project_path) =
5739                        worktree.read_with(&cx, |worktree, _| {
5740                            let entry = worktree
5741                                .entries(false)
5742                                .filter(|e| e.is_file())
5743                                .choose(&mut *rng.lock())
5744                                .unwrap();
5745                            (
5746                                worktree.root_name().to_string(),
5747                                (worktree.id(), entry.path.clone()),
5748                            )
5749                        });
5750                    log::info!(
5751                        "Guest {}: opening path {:?} in worktree {} ({})",
5752                        guest_id,
5753                        project_path.1,
5754                        project_path.0,
5755                        worktree_root_name,
5756                    );
5757                    let buffer = project
5758                        .update(&mut cx, |project, cx| {
5759                            project.open_buffer(project_path.clone(), cx)
5760                        })
5761                        .await
5762                        .unwrap();
5763                    log::info!(
5764                        "Guest {}: opened path {:?} in worktree {} ({}) with buffer id {}",
5765                        guest_id,
5766                        project_path.1,
5767                        project_path.0,
5768                        worktree_root_name,
5769                        buffer.read_with(&cx, |buffer, _| buffer.remote_id())
5770                    );
5771                    self.buffers.insert(buffer.clone());
5772                    buffer
5773                } else {
5774                    operations.set(operations.get() + 1);
5775
5776                    self.buffers
5777                        .iter()
5778                        .choose(&mut *rng.lock())
5779                        .unwrap()
5780                        .clone()
5781                };
5782
5783                let choice = rng.lock().gen_range(0..100);
5784                match choice {
5785                    0..=9 => {
5786                        cx.update(|cx| {
5787                            log::info!(
5788                                "Guest {}: dropping buffer {:?}",
5789                                guest_id,
5790                                buffer.read(cx).file().unwrap().full_path(cx)
5791                            );
5792                            self.buffers.remove(&buffer);
5793                            drop(buffer);
5794                        });
5795                    }
5796                    10..=19 => {
5797                        let completions = project.update(&mut cx, |project, cx| {
5798                            log::info!(
5799                                "Guest {}: requesting completions for buffer {} ({:?})",
5800                                guest_id,
5801                                buffer.read(cx).remote_id(),
5802                                buffer.read(cx).file().unwrap().full_path(cx)
5803                            );
5804                            let offset = rng.lock().gen_range(0..=buffer.read(cx).len());
5805                            project.completions(&buffer, offset, cx)
5806                        });
5807                        let completions = cx.background().spawn(async move {
5808                            completions.await.expect("completions request failed");
5809                        });
5810                        if rng.lock().gen_bool(0.3) {
5811                            log::info!("Guest {}: detaching completions request", guest_id);
5812                            completions.detach();
5813                        } else {
5814                            completions.await;
5815                        }
5816                    }
5817                    20..=29 => {
5818                        let code_actions = project.update(&mut cx, |project, cx| {
5819                            log::info!(
5820                                "Guest {}: requesting code actions for buffer {} ({:?})",
5821                                guest_id,
5822                                buffer.read(cx).remote_id(),
5823                                buffer.read(cx).file().unwrap().full_path(cx)
5824                            );
5825                            let range = buffer.read(cx).random_byte_range(0, &mut *rng.lock());
5826                            project.code_actions(&buffer, range, cx)
5827                        });
5828                        let code_actions = cx.background().spawn(async move {
5829                            code_actions.await.expect("code actions request failed");
5830                        });
5831                        if rng.lock().gen_bool(0.3) {
5832                            log::info!("Guest {}: detaching code actions request", guest_id);
5833                            code_actions.detach();
5834                        } else {
5835                            code_actions.await;
5836                        }
5837                    }
5838                    30..=39 if buffer.read_with(&cx, |buffer, _| buffer.is_dirty()) => {
5839                        let (requested_version, save) = buffer.update(&mut cx, |buffer, cx| {
5840                            log::info!(
5841                                "Guest {}: saving buffer {} ({:?})",
5842                                guest_id,
5843                                buffer.remote_id(),
5844                                buffer.file().unwrap().full_path(cx)
5845                            );
5846                            (buffer.version(), buffer.save(cx))
5847                        });
5848                        let save = cx.background().spawn(async move {
5849                            let (saved_version, _) = save.await.expect("save request failed");
5850                            assert!(saved_version.observed_all(&requested_version));
5851                        });
5852                        if rng.lock().gen_bool(0.3) {
5853                            log::info!("Guest {}: detaching save request", guest_id);
5854                            save.detach();
5855                        } else {
5856                            save.await;
5857                        }
5858                    }
5859                    40..=44 => {
5860                        let prepare_rename = project.update(&mut cx, |project, cx| {
5861                            log::info!(
5862                                "Guest {}: preparing rename for buffer {} ({:?})",
5863                                guest_id,
5864                                buffer.read(cx).remote_id(),
5865                                buffer.read(cx).file().unwrap().full_path(cx)
5866                            );
5867                            let offset = rng.lock().gen_range(0..=buffer.read(cx).len());
5868                            project.prepare_rename(buffer, offset, cx)
5869                        });
5870                        let prepare_rename = cx.background().spawn(async move {
5871                            prepare_rename.await.expect("prepare rename request failed");
5872                        });
5873                        if rng.lock().gen_bool(0.3) {
5874                            log::info!("Guest {}: detaching prepare rename request", guest_id);
5875                            prepare_rename.detach();
5876                        } else {
5877                            prepare_rename.await;
5878                        }
5879                    }
5880                    45..=49 => {
5881                        let definitions = project.update(&mut cx, |project, cx| {
5882                            log::info!(
5883                                "Guest {}: requesting definitions for buffer {} ({:?})",
5884                                guest_id,
5885                                buffer.read(cx).remote_id(),
5886                                buffer.read(cx).file().unwrap().full_path(cx)
5887                            );
5888                            let offset = rng.lock().gen_range(0..=buffer.read(cx).len());
5889                            project.definition(&buffer, offset, cx)
5890                        });
5891                        let definitions = cx.background().spawn(async move {
5892                            definitions.await.expect("definitions request failed")
5893                        });
5894                        if rng.lock().gen_bool(0.3) {
5895                            log::info!("Guest {}: detaching definitions request", guest_id);
5896                            definitions.detach();
5897                        } else {
5898                            self.buffers
5899                                .extend(definitions.await.into_iter().map(|loc| loc.buffer));
5900                        }
5901                    }
5902                    50..=54 => {
5903                        let highlights = project.update(&mut cx, |project, cx| {
5904                            log::info!(
5905                                "Guest {}: requesting highlights for buffer {} ({:?})",
5906                                guest_id,
5907                                buffer.read(cx).remote_id(),
5908                                buffer.read(cx).file().unwrap().full_path(cx)
5909                            );
5910                            let offset = rng.lock().gen_range(0..=buffer.read(cx).len());
5911                            project.document_highlights(&buffer, offset, cx)
5912                        });
5913                        let highlights = cx.background().spawn(async move {
5914                            highlights.await.expect("highlights request failed");
5915                        });
5916                        if rng.lock().gen_bool(0.3) {
5917                            log::info!("Guest {}: detaching highlights request", guest_id);
5918                            highlights.detach();
5919                        } else {
5920                            highlights.await;
5921                        }
5922                    }
5923                    55..=59 => {
5924                        let search = project.update(&mut cx, |project, cx| {
5925                            let query = rng.lock().gen_range('a'..='z');
5926                            log::info!("Guest {}: project-wide search {:?}", guest_id, query);
5927                            project.search(SearchQuery::text(query, false, false), cx)
5928                        });
5929                        let search = cx
5930                            .background()
5931                            .spawn(async move { search.await.expect("search request failed") });
5932                        if rng.lock().gen_bool(0.3) {
5933                            log::info!("Guest {}: detaching search request", guest_id);
5934                            search.detach();
5935                        } else {
5936                            self.buffers.extend(search.await.into_keys());
5937                        }
5938                    }
5939                    _ => {
5940                        buffer.update(&mut cx, |buffer, cx| {
5941                            log::info!(
5942                                "Guest {}: updating buffer {} ({:?})",
5943                                guest_id,
5944                                buffer.remote_id(),
5945                                buffer.file().unwrap().full_path(cx)
5946                            );
5947                            buffer.randomly_edit(&mut *rng.lock(), 5, cx)
5948                        });
5949                    }
5950                }
5951                cx.background().simulate_random_delay().await;
5952            }
5953
5954            log::info!("Guest {} done", guest_id);
5955
5956            self.project = Some(project);
5957            (self, cx)
5958        }
5959    }
5960
5961    impl Drop for TestClient {
5962        fn drop(&mut self) {
5963            self.client.tear_down();
5964        }
5965    }
5966
5967    impl Executor for Arc<gpui::executor::Background> {
5968        type Timer = gpui::executor::Timer;
5969
5970        fn spawn_detached<F: 'static + Send + Future<Output = ()>>(&self, future: F) {
5971            self.spawn(future).detach();
5972        }
5973
5974        fn timer(&self, duration: Duration) -> Self::Timer {
5975            self.as_ref().timer(duration)
5976        }
5977    }
5978
5979    fn channel_messages(channel: &Channel) -> Vec<(String, String, bool)> {
5980        channel
5981            .messages()
5982            .cursor::<()>()
5983            .map(|m| {
5984                (
5985                    m.sender.github_login.clone(),
5986                    m.body.clone(),
5987                    m.is_pending(),
5988                )
5989            })
5990            .collect()
5991    }
5992
5993    struct EmptyView;
5994
5995    impl gpui::Entity for EmptyView {
5996        type Event = ();
5997    }
5998
5999    impl gpui::View for EmptyView {
6000        fn ui_name() -> &'static str {
6001            "empty view"
6002        }
6003
6004        fn render(&mut self, _: &mut gpui::RenderContext<Self>) -> gpui::ElementBox {
6005            gpui::Element::boxed(gpui::elements::Empty)
6006        }
6007    }
6008}