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