rpc.rs

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