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_std::task;
  10use async_tungstenite::{tungstenite::protocol::Role, WebSocketStream};
  11use collections::{HashMap, HashSet};
  12use futures::{future::BoxFuture, FutureExt, StreamExt};
  13use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard};
  14use postage::{mpsc, prelude::Sink as _};
  15use rpc::{
  16    proto::{self, AnyTypedEnvelope, EnvelopedMessage},
  17    Connection, ConnectionId, Peer, TypedEnvelope,
  18};
  19use sha1::{Digest as _, Sha1};
  20use std::{any::TypeId, future::Future, path::PathBuf, sync::Arc, time::Instant};
  21use store::{Store, Worktree};
  22use surf::StatusCode;
  23use tide::log;
  24use tide::{
  25    http::headers::{HeaderName, CONNECTION, UPGRADE},
  26    Request, Response,
  27};
  28use time::OffsetDateTime;
  29
  30type MessageHandler = Box<
  31    dyn Send
  32        + Sync
  33        + Fn(Arc<Server>, Box<dyn AnyTypedEnvelope>) -> BoxFuture<'static, tide::Result<()>>,
  34>;
  35
  36pub struct Server {
  37    peer: Arc<Peer>,
  38    store: RwLock<Store>,
  39    app_state: Arc<AppState>,
  40    handlers: HashMap<TypeId, MessageHandler>,
  41    notifications: Option<mpsc::Sender<()>>,
  42}
  43
  44const MESSAGE_COUNT_PER_PAGE: usize = 100;
  45const MAX_MESSAGE_LEN: usize = 1024;
  46const NO_SUCH_PROJECT: &'static str = "no such project";
  47
  48impl Server {
  49    pub fn new(
  50        app_state: Arc<AppState>,
  51        peer: Arc<Peer>,
  52        notifications: Option<mpsc::Sender<()>>,
  53    ) -> Arc<Self> {
  54        let mut server = Self {
  55            peer,
  56            app_state,
  57            store: Default::default(),
  58            handlers: Default::default(),
  59            notifications,
  60        };
  61
  62        server
  63            .add_handler(Server::ping)
  64            .add_handler(Server::register_project)
  65            .add_handler(Server::unregister_project)
  66            .add_handler(Server::share_project)
  67            .add_handler(Server::unshare_project)
  68            .add_handler(Server::join_project)
  69            .add_handler(Server::leave_project)
  70            .add_handler(Server::register_worktree)
  71            .add_handler(Server::unregister_worktree)
  72            .add_handler(Server::share_worktree)
  73            .add_handler(Server::update_worktree)
  74            .add_handler(Server::update_diagnostic_summary)
  75            .add_handler(Server::disk_based_diagnostics_updating)
  76            .add_handler(Server::disk_based_diagnostics_updated)
  77            .add_handler(Server::get_definition)
  78            .add_handler(Server::open_buffer)
  79            .add_handler(Server::close_buffer)
  80            .add_handler(Server::update_buffer)
  81            .add_handler(Server::update_buffer_file)
  82            .add_handler(Server::buffer_reloaded)
  83            .add_handler(Server::buffer_saved)
  84            .add_handler(Server::save_buffer)
  85            .add_handler(Server::format_buffer)
  86            .add_handler(Server::get_completions)
  87            .add_handler(Server::apply_additional_edits_for_completion)
  88            .add_handler(Server::get_channels)
  89            .add_handler(Server::get_users)
  90            .add_handler(Server::join_channel)
  91            .add_handler(Server::leave_channel)
  92            .add_handler(Server::send_channel_message)
  93            .add_handler(Server::get_channel_messages);
  94
  95        Arc::new(server)
  96    }
  97
  98    fn add_handler<F, Fut, M>(&mut self, handler: F) -> &mut Self
  99    where
 100        F: 'static + Send + Sync + Fn(Arc<Self>, TypedEnvelope<M>) -> Fut,
 101        Fut: 'static + Send + Future<Output = tide::Result<()>>,
 102        M: EnvelopedMessage,
 103    {
 104        let prev_handler = self.handlers.insert(
 105            TypeId::of::<M>(),
 106            Box::new(move |server, envelope| {
 107                let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
 108                (handler)(server, *envelope).boxed()
 109            }),
 110        );
 111        if prev_handler.is_some() {
 112            panic!("registered a handler for the same message twice");
 113        }
 114        self
 115    }
 116
 117    pub fn handle_connection(
 118        self: &Arc<Self>,
 119        connection: Connection,
 120        addr: String,
 121        user_id: UserId,
 122        mut send_connection_id: Option<postage::mpsc::Sender<ConnectionId>>,
 123    ) -> impl Future<Output = ()> {
 124        let mut this = self.clone();
 125        async move {
 126            let (connection_id, handle_io, mut incoming_rx) =
 127                this.peer.add_connection(connection).await;
 128
 129            if let Some(send_connection_id) = send_connection_id.as_mut() {
 130                let _ = send_connection_id.send(connection_id).await;
 131            }
 132
 133            this.state_mut().add_connection(connection_id, user_id);
 134            if let Err(err) = this.update_contacts_for_users(&[user_id]) {
 135                log::error!("error updating contacts for {:?}: {}", user_id, err);
 136            }
 137
 138            let handle_io = handle_io.fuse();
 139            futures::pin_mut!(handle_io);
 140            loop {
 141                let next_message = incoming_rx.next().fuse();
 142                futures::pin_mut!(next_message);
 143                futures::select_biased! {
 144                    result = handle_io => {
 145                        if let Err(err) = result {
 146                            log::error!("error handling rpc connection {:?} - {:?}", addr, err);
 147                        }
 148                        break;
 149                    }
 150                    message = next_message => {
 151                        if let Some(message) = message {
 152                            let start_time = Instant::now();
 153                            let type_name = message.payload_type_name();
 154                            log::info!("rpc message received. connection:{}, type:{}", connection_id, type_name);
 155                            if let Some(handler) = this.handlers.get(&message.payload_type_id()) {
 156                                if let Err(err) = (handler)(this.clone(), message).await {
 157                                    log::error!("rpc message error. connection:{}, type:{}, error:{:?}", connection_id, type_name, err);
 158                                } else {
 159                                    log::info!("rpc message handled. connection:{}, type:{}, duration:{:?}", connection_id, type_name, start_time.elapsed());
 160                                }
 161
 162                                if let Some(mut notifications) = this.notifications.clone() {
 163                                    let _ = notifications.send(()).await;
 164                                }
 165                            } else {
 166                                log::warn!("unhandled message: {}", type_name);
 167                            }
 168                        } else {
 169                            log::info!("rpc connection closed {:?}", addr);
 170                            break;
 171                        }
 172                    }
 173                }
 174            }
 175
 176            if let Err(err) = this.sign_out(connection_id).await {
 177                log::error!("error signing out connection {:?} - {:?}", addr, err);
 178            }
 179        }
 180    }
 181
 182    async fn sign_out(self: &mut Arc<Self>, connection_id: ConnectionId) -> tide::Result<()> {
 183        self.peer.disconnect(connection_id);
 184        let removed_connection = self.state_mut().remove_connection(connection_id)?;
 185
 186        for (project_id, project) in removed_connection.hosted_projects {
 187            if let Some(share) = project.share {
 188                broadcast(
 189                    connection_id,
 190                    share.guests.keys().copied().collect(),
 191                    |conn_id| {
 192                        self.peer
 193                            .send(conn_id, proto::UnshareProject { project_id })
 194                    },
 195                )?;
 196            }
 197        }
 198
 199        for (project_id, peer_ids) in removed_connection.guest_project_ids {
 200            broadcast(connection_id, peer_ids, |conn_id| {
 201                self.peer.send(
 202                    conn_id,
 203                    proto::RemoveProjectCollaborator {
 204                        project_id,
 205                        peer_id: connection_id.0,
 206                    },
 207                )
 208            })?;
 209        }
 210
 211        self.update_contacts_for_users(removed_connection.contact_ids.iter())?;
 212        Ok(())
 213    }
 214
 215    async fn ping(self: Arc<Server>, request: TypedEnvelope<proto::Ping>) -> tide::Result<()> {
 216        self.peer.respond(request.receipt(), proto::Ack {})?;
 217        Ok(())
 218    }
 219
 220    async fn register_project(
 221        mut self: Arc<Server>,
 222        request: TypedEnvelope<proto::RegisterProject>,
 223    ) -> tide::Result<()> {
 224        let project_id = {
 225            let mut state = self.state_mut();
 226            let user_id = state.user_id_for_connection(request.sender_id)?;
 227            state.register_project(request.sender_id, user_id)
 228        };
 229        self.peer.respond(
 230            request.receipt(),
 231            proto::RegisterProjectResponse { project_id },
 232        )?;
 233        Ok(())
 234    }
 235
 236    async fn unregister_project(
 237        mut self: Arc<Server>,
 238        request: TypedEnvelope<proto::UnregisterProject>,
 239    ) -> tide::Result<()> {
 240        let project = self
 241            .state_mut()
 242            .unregister_project(request.payload.project_id, request.sender_id)
 243            .ok_or_else(|| anyhow!("no such project"))?;
 244        self.update_contacts_for_users(project.authorized_user_ids().iter())?;
 245        Ok(())
 246    }
 247
 248    async fn share_project(
 249        mut self: Arc<Server>,
 250        request: TypedEnvelope<proto::ShareProject>,
 251    ) -> tide::Result<()> {
 252        self.state_mut()
 253            .share_project(request.payload.project_id, request.sender_id);
 254        self.peer.respond(request.receipt(), proto::Ack {})?;
 255        Ok(())
 256    }
 257
 258    async fn unshare_project(
 259        mut self: Arc<Server>,
 260        request: TypedEnvelope<proto::UnshareProject>,
 261    ) -> tide::Result<()> {
 262        let project_id = request.payload.project_id;
 263        let project = self
 264            .state_mut()
 265            .unshare_project(project_id, request.sender_id)?;
 266
 267        broadcast(request.sender_id, project.connection_ids, |conn_id| {
 268            self.peer
 269                .send(conn_id, proto::UnshareProject { project_id })
 270        })?;
 271        self.update_contacts_for_users(&project.authorized_user_ids)?;
 272        Ok(())
 273    }
 274
 275    async fn join_project(
 276        mut self: Arc<Server>,
 277        request: TypedEnvelope<proto::JoinProject>,
 278    ) -> tide::Result<()> {
 279        let project_id = request.payload.project_id;
 280
 281        let user_id = self.state().user_id_for_connection(request.sender_id)?;
 282        let response_data = self
 283            .state_mut()
 284            .join_project(request.sender_id, user_id, project_id)
 285            .and_then(|joined| {
 286                let share = joined.project.share()?;
 287                let peer_count = share.guests.len();
 288                let mut collaborators = Vec::with_capacity(peer_count);
 289                collaborators.push(proto::Collaborator {
 290                    peer_id: joined.project.host_connection_id.0,
 291                    replica_id: 0,
 292                    user_id: joined.project.host_user_id.to_proto(),
 293                });
 294                let worktrees = joined
 295                    .project
 296                    .worktrees
 297                    .iter()
 298                    .filter_map(|(id, worktree)| {
 299                        worktree.share.as_ref().map(|share| proto::Worktree {
 300                            id: *id,
 301                            root_name: worktree.root_name.clone(),
 302                            entries: share.entries.values().cloned().collect(),
 303                            diagnostic_summaries: share
 304                                .diagnostic_summaries
 305                                .values()
 306                                .cloned()
 307                                .collect(),
 308                            weak: worktree.weak,
 309                        })
 310                    })
 311                    .collect();
 312                for (peer_conn_id, (peer_replica_id, peer_user_id)) in &share.guests {
 313                    if *peer_conn_id != request.sender_id {
 314                        collaborators.push(proto::Collaborator {
 315                            peer_id: peer_conn_id.0,
 316                            replica_id: *peer_replica_id as u32,
 317                            user_id: peer_user_id.to_proto(),
 318                        });
 319                    }
 320                }
 321                let response = proto::JoinProjectResponse {
 322                    worktrees,
 323                    replica_id: joined.replica_id as u32,
 324                    collaborators,
 325                };
 326                let connection_ids = joined.project.connection_ids();
 327                let contact_user_ids = joined.project.authorized_user_ids();
 328                Ok((response, connection_ids, contact_user_ids))
 329            });
 330
 331        match response_data {
 332            Ok((response, connection_ids, contact_user_ids)) => {
 333                broadcast(request.sender_id, connection_ids, |conn_id| {
 334                    self.peer.send(
 335                        conn_id,
 336                        proto::AddProjectCollaborator {
 337                            project_id,
 338                            collaborator: Some(proto::Collaborator {
 339                                peer_id: request.sender_id.0,
 340                                replica_id: response.replica_id,
 341                                user_id: user_id.to_proto(),
 342                            }),
 343                        },
 344                    )
 345                })?;
 346                self.peer.respond(request.receipt(), response)?;
 347                self.update_contacts_for_users(&contact_user_ids)?;
 348            }
 349            Err(error) => {
 350                self.peer.respond_with_error(
 351                    request.receipt(),
 352                    proto::Error {
 353                        message: error.to_string(),
 354                    },
 355                )?;
 356            }
 357        }
 358
 359        Ok(())
 360    }
 361
 362    async fn leave_project(
 363        mut self: Arc<Server>,
 364        request: TypedEnvelope<proto::LeaveProject>,
 365    ) -> tide::Result<()> {
 366        let sender_id = request.sender_id;
 367        let project_id = request.payload.project_id;
 368        let worktree = self.state_mut().leave_project(sender_id, project_id);
 369        if let Some(worktree) = worktree {
 370            broadcast(sender_id, worktree.connection_ids, |conn_id| {
 371                self.peer.send(
 372                    conn_id,
 373                    proto::RemoveProjectCollaborator {
 374                        project_id,
 375                        peer_id: sender_id.0,
 376                    },
 377                )
 378            })?;
 379            self.update_contacts_for_users(&worktree.authorized_user_ids)?;
 380        }
 381        Ok(())
 382    }
 383
 384    async fn register_worktree(
 385        mut self: Arc<Server>,
 386        request: TypedEnvelope<proto::RegisterWorktree>,
 387    ) -> tide::Result<()> {
 388        let receipt = request.receipt();
 389        let host_user_id = self.state().user_id_for_connection(request.sender_id)?;
 390
 391        let mut contact_user_ids = HashSet::default();
 392        contact_user_ids.insert(host_user_id);
 393        for github_login in request.payload.authorized_logins {
 394            match self.app_state.db.create_user(&github_login, false).await {
 395                Ok(contact_user_id) => {
 396                    contact_user_ids.insert(contact_user_id);
 397                }
 398                Err(err) => {
 399                    let message = err.to_string();
 400                    self.peer
 401                        .respond_with_error(receipt, proto::Error { message })?;
 402                    return Ok(());
 403                }
 404            }
 405        }
 406
 407        let contact_user_ids = contact_user_ids.into_iter().collect::<Vec<_>>();
 408        let ok = self.state_mut().register_worktree(
 409            request.payload.project_id,
 410            request.payload.worktree_id,
 411            Worktree {
 412                authorized_user_ids: contact_user_ids.clone(),
 413                root_name: request.payload.root_name,
 414                share: None,
 415                weak: false,
 416            },
 417        );
 418
 419        if ok {
 420            self.peer.respond(receipt, proto::Ack {})?;
 421            self.update_contacts_for_users(&contact_user_ids)?;
 422        } else {
 423            self.peer.respond_with_error(
 424                receipt,
 425                proto::Error {
 426                    message: NO_SUCH_PROJECT.to_string(),
 427                },
 428            )?;
 429        }
 430
 431        Ok(())
 432    }
 433
 434    async fn unregister_worktree(
 435        mut self: Arc<Server>,
 436        request: TypedEnvelope<proto::UnregisterWorktree>,
 437    ) -> tide::Result<()> {
 438        let project_id = request.payload.project_id;
 439        let worktree_id = request.payload.worktree_id;
 440        let (worktree, guest_connection_ids) =
 441            self.state_mut()
 442                .unregister_worktree(project_id, worktree_id, request.sender_id)?;
 443        broadcast(request.sender_id, guest_connection_ids, |conn_id| {
 444            self.peer.send(
 445                conn_id,
 446                proto::UnregisterWorktree {
 447                    project_id,
 448                    worktree_id,
 449                },
 450            )
 451        })?;
 452        self.update_contacts_for_users(&worktree.authorized_user_ids)?;
 453        Ok(())
 454    }
 455
 456    async fn share_worktree(
 457        mut self: Arc<Server>,
 458        mut request: TypedEnvelope<proto::ShareWorktree>,
 459    ) -> tide::Result<()> {
 460        let worktree = request
 461            .payload
 462            .worktree
 463            .as_mut()
 464            .ok_or_else(|| anyhow!("missing worktree"))?;
 465        let entries = worktree
 466            .entries
 467            .iter()
 468            .map(|entry| (entry.id, entry.clone()))
 469            .collect();
 470        let diagnostic_summaries = worktree
 471            .diagnostic_summaries
 472            .iter()
 473            .map(|summary| (PathBuf::from(summary.path.clone()), summary.clone()))
 474            .collect();
 475
 476        let shared_worktree = self.state_mut().share_worktree(
 477            request.payload.project_id,
 478            worktree.id,
 479            request.sender_id,
 480            entries,
 481            diagnostic_summaries,
 482        );
 483        if let Some(shared_worktree) = shared_worktree {
 484            broadcast(
 485                request.sender_id,
 486                shared_worktree.connection_ids,
 487                |connection_id| {
 488                    self.peer.forward_send(
 489                        request.sender_id,
 490                        connection_id,
 491                        request.payload.clone(),
 492                    )
 493                },
 494            )?;
 495            self.peer.respond(request.receipt(), proto::Ack {})?;
 496            self.update_contacts_for_users(&shared_worktree.authorized_user_ids)?;
 497        } else {
 498            self.peer.respond_with_error(
 499                request.receipt(),
 500                proto::Error {
 501                    message: "no such worktree".to_string(),
 502                },
 503            )?;
 504        }
 505        Ok(())
 506    }
 507
 508    async fn update_worktree(
 509        mut self: Arc<Server>,
 510        request: TypedEnvelope<proto::UpdateWorktree>,
 511    ) -> tide::Result<()> {
 512        let connection_ids = self
 513            .state_mut()
 514            .update_worktree(
 515                request.sender_id,
 516                request.payload.project_id,
 517                request.payload.worktree_id,
 518                &request.payload.removed_entries,
 519                &request.payload.updated_entries,
 520            )
 521            .ok_or_else(|| anyhow!("no such worktree"))?;
 522
 523        broadcast(request.sender_id, connection_ids, |connection_id| {
 524            self.peer
 525                .forward_send(request.sender_id, connection_id, request.payload.clone())
 526        })?;
 527
 528        Ok(())
 529    }
 530
 531    async fn update_diagnostic_summary(
 532        mut self: Arc<Server>,
 533        request: TypedEnvelope<proto::UpdateDiagnosticSummary>,
 534    ) -> tide::Result<()> {
 535        let receiver_ids = request
 536            .payload
 537            .summary
 538            .clone()
 539            .and_then(|summary| {
 540                self.state_mut().update_diagnostic_summary(
 541                    request.payload.project_id,
 542                    request.payload.worktree_id,
 543                    request.sender_id,
 544                    summary,
 545                )
 546            })
 547            .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
 548
 549        broadcast(request.sender_id, receiver_ids, |connection_id| {
 550            self.peer
 551                .forward_send(request.sender_id, connection_id, request.payload.clone())
 552        })?;
 553        Ok(())
 554    }
 555
 556    async fn disk_based_diagnostics_updating(
 557        self: Arc<Server>,
 558        request: TypedEnvelope<proto::DiskBasedDiagnosticsUpdating>,
 559    ) -> tide::Result<()> {
 560        let receiver_ids = self
 561            .state()
 562            .project_connection_ids(request.payload.project_id, request.sender_id)
 563            .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
 564        broadcast(request.sender_id, receiver_ids, |connection_id| {
 565            self.peer
 566                .forward_send(request.sender_id, connection_id, request.payload.clone())
 567        })?;
 568        Ok(())
 569    }
 570
 571    async fn disk_based_diagnostics_updated(
 572        self: Arc<Server>,
 573        request: TypedEnvelope<proto::DiskBasedDiagnosticsUpdated>,
 574    ) -> tide::Result<()> {
 575        let receiver_ids = self
 576            .state()
 577            .project_connection_ids(request.payload.project_id, request.sender_id)
 578            .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
 579        broadcast(request.sender_id, receiver_ids, |connection_id| {
 580            self.peer
 581                .forward_send(request.sender_id, connection_id, request.payload.clone())
 582        })?;
 583        Ok(())
 584    }
 585
 586    async fn get_definition(
 587        self: Arc<Server>,
 588        request: TypedEnvelope<proto::GetDefinition>,
 589    ) -> tide::Result<()> {
 590        let receipt = request.receipt();
 591        let host_connection_id = self
 592            .state()
 593            .read_project(request.payload.project_id, request.sender_id)
 594            .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?
 595            .host_connection_id;
 596        let response = self
 597            .peer
 598            .forward_request(request.sender_id, host_connection_id, request.payload)
 599            .await?;
 600        self.peer.respond(receipt, response)?;
 601        Ok(())
 602    }
 603
 604    async fn open_buffer(
 605        self: Arc<Server>,
 606        request: TypedEnvelope<proto::OpenBuffer>,
 607    ) -> tide::Result<()> {
 608        let receipt = request.receipt();
 609        let host_connection_id = self
 610            .state()
 611            .read_project(request.payload.project_id, request.sender_id)
 612            .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?
 613            .host_connection_id;
 614        let response = self
 615            .peer
 616            .forward_request(request.sender_id, host_connection_id, request.payload)
 617            .await?;
 618        self.peer.respond(receipt, response)?;
 619        Ok(())
 620    }
 621
 622    async fn close_buffer(
 623        self: Arc<Server>,
 624        request: TypedEnvelope<proto::CloseBuffer>,
 625    ) -> tide::Result<()> {
 626        let host_connection_id = self
 627            .state()
 628            .read_project(request.payload.project_id, request.sender_id)
 629            .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?
 630            .host_connection_id;
 631        self.peer
 632            .forward_send(request.sender_id, host_connection_id, request.payload)?;
 633        Ok(())
 634    }
 635
 636    async fn save_buffer(
 637        self: Arc<Server>,
 638        request: TypedEnvelope<proto::SaveBuffer>,
 639    ) -> tide::Result<()> {
 640        let host;
 641        let guests;
 642        {
 643            let state = self.state();
 644            let project = state
 645                .read_project(request.payload.project_id, request.sender_id)
 646                .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
 647            host = project.host_connection_id;
 648            guests = project.guest_connection_ids()
 649        }
 650
 651        let sender = request.sender_id;
 652        let receipt = request.receipt();
 653        let response = self
 654            .peer
 655            .forward_request(sender, host, request.payload.clone())
 656            .await?;
 657
 658        broadcast(host, guests, |conn_id| {
 659            let response = response.clone();
 660            if conn_id == sender {
 661                self.peer.respond(receipt, response)
 662            } else {
 663                self.peer.forward_send(host, conn_id, response)
 664            }
 665        })?;
 666
 667        Ok(())
 668    }
 669
 670    async fn format_buffer(
 671        self: Arc<Server>,
 672        request: TypedEnvelope<proto::FormatBuffer>,
 673    ) -> tide::Result<()> {
 674        let host;
 675        {
 676            let state = self.state();
 677            let project = state
 678                .read_project(request.payload.project_id, request.sender_id)
 679                .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
 680            host = project.host_connection_id;
 681        }
 682
 683        let sender = request.sender_id;
 684        let receipt = request.receipt();
 685        let response = self
 686            .peer
 687            .forward_request(sender, host, request.payload.clone())
 688            .await?;
 689        self.peer.respond(receipt, response)?;
 690
 691        Ok(())
 692    }
 693
 694    async fn get_completions(
 695        self: Arc<Server>,
 696        request: TypedEnvelope<proto::GetCompletions>,
 697    ) -> tide::Result<()> {
 698        let host;
 699        {
 700            let state = self.state();
 701            let project = state
 702                .read_project(request.payload.project_id, request.sender_id)
 703                .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
 704            host = project.host_connection_id;
 705        }
 706
 707        let sender = request.sender_id;
 708        let receipt = request.receipt();
 709        let response = self
 710            .peer
 711            .forward_request(sender, host, request.payload.clone())
 712            .await?;
 713        self.peer.respond(receipt, response)?;
 714        Ok(())
 715    }
 716
 717    async fn apply_additional_edits_for_completion(
 718        self: Arc<Server>,
 719        request: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
 720    ) -> tide::Result<()> {
 721        let host;
 722        {
 723            let state = self.state();
 724            let project = state
 725                .read_project(request.payload.project_id, request.sender_id)
 726                .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
 727            host = project.host_connection_id;
 728        }
 729
 730        let sender = request.sender_id;
 731        let receipt = request.receipt();
 732        let response = self
 733            .peer
 734            .forward_request(sender, host, request.payload.clone())
 735            .await?;
 736        self.peer.respond(receipt, response)?;
 737        Ok(())
 738    }
 739
 740    async fn update_buffer(
 741        self: Arc<Server>,
 742        request: TypedEnvelope<proto::UpdateBuffer>,
 743    ) -> tide::Result<()> {
 744        let receiver_ids = self
 745            .state()
 746            .project_connection_ids(request.payload.project_id, request.sender_id)
 747            .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
 748        broadcast(request.sender_id, receiver_ids, |connection_id| {
 749            self.peer
 750                .forward_send(request.sender_id, connection_id, request.payload.clone())
 751        })?;
 752        self.peer.respond(request.receipt(), proto::Ack {})?;
 753        Ok(())
 754    }
 755
 756    async fn update_buffer_file(
 757        self: Arc<Server>,
 758        request: TypedEnvelope<proto::UpdateBufferFile>,
 759    ) -> tide::Result<()> {
 760        let receiver_ids = self
 761            .state()
 762            .project_connection_ids(request.payload.project_id, request.sender_id)
 763            .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
 764        broadcast(request.sender_id, receiver_ids, |connection_id| {
 765            self.peer
 766                .forward_send(request.sender_id, connection_id, request.payload.clone())
 767        })?;
 768        Ok(())
 769    }
 770
 771    async fn buffer_reloaded(
 772        self: Arc<Server>,
 773        request: TypedEnvelope<proto::BufferReloaded>,
 774    ) -> tide::Result<()> {
 775        let receiver_ids = self
 776            .state()
 777            .project_connection_ids(request.payload.project_id, request.sender_id)
 778            .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
 779        broadcast(request.sender_id, receiver_ids, |connection_id| {
 780            self.peer
 781                .forward_send(request.sender_id, connection_id, request.payload.clone())
 782        })?;
 783        Ok(())
 784    }
 785
 786    async fn buffer_saved(
 787        self: Arc<Server>,
 788        request: TypedEnvelope<proto::BufferSaved>,
 789    ) -> tide::Result<()> {
 790        let receiver_ids = self
 791            .state()
 792            .project_connection_ids(request.payload.project_id, request.sender_id)
 793            .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
 794        broadcast(request.sender_id, receiver_ids, |connection_id| {
 795            self.peer
 796                .forward_send(request.sender_id, connection_id, request.payload.clone())
 797        })?;
 798        Ok(())
 799    }
 800
 801    async fn get_channels(
 802        self: Arc<Server>,
 803        request: TypedEnvelope<proto::GetChannels>,
 804    ) -> tide::Result<()> {
 805        let user_id = self.state().user_id_for_connection(request.sender_id)?;
 806        let channels = self.app_state.db.get_accessible_channels(user_id).await?;
 807        self.peer.respond(
 808            request.receipt(),
 809            proto::GetChannelsResponse {
 810                channels: channels
 811                    .into_iter()
 812                    .map(|chan| proto::Channel {
 813                        id: chan.id.to_proto(),
 814                        name: chan.name,
 815                    })
 816                    .collect(),
 817            },
 818        )?;
 819        Ok(())
 820    }
 821
 822    async fn get_users(
 823        self: Arc<Server>,
 824        request: TypedEnvelope<proto::GetUsers>,
 825    ) -> tide::Result<()> {
 826        let receipt = request.receipt();
 827        let user_ids = request.payload.user_ids.into_iter().map(UserId::from_proto);
 828        let users = self
 829            .app_state
 830            .db
 831            .get_users_by_ids(user_ids)
 832            .await?
 833            .into_iter()
 834            .map(|user| proto::User {
 835                id: user.id.to_proto(),
 836                avatar_url: format!("https://github.com/{}.png?size=128", user.github_login),
 837                github_login: user.github_login,
 838            })
 839            .collect();
 840        self.peer
 841            .respond(receipt, proto::GetUsersResponse { users })?;
 842        Ok(())
 843    }
 844
 845    fn update_contacts_for_users<'a>(
 846        self: &Arc<Server>,
 847        user_ids: impl IntoIterator<Item = &'a UserId>,
 848    ) -> anyhow::Result<()> {
 849        let mut result = Ok(());
 850        let state = self.state();
 851        for user_id in user_ids {
 852            let contacts = state.contacts_for_user(*user_id);
 853            for connection_id in state.connection_ids_for_user(*user_id) {
 854                if let Err(error) = self.peer.send(
 855                    connection_id,
 856                    proto::UpdateContacts {
 857                        contacts: contacts.clone(),
 858                    },
 859                ) {
 860                    result = Err(error);
 861                }
 862            }
 863        }
 864        result
 865    }
 866
 867    async fn join_channel(
 868        mut self: Arc<Self>,
 869        request: TypedEnvelope<proto::JoinChannel>,
 870    ) -> tide::Result<()> {
 871        let user_id = self.state().user_id_for_connection(request.sender_id)?;
 872        let channel_id = ChannelId::from_proto(request.payload.channel_id);
 873        if !self
 874            .app_state
 875            .db
 876            .can_user_access_channel(user_id, channel_id)
 877            .await?
 878        {
 879            Err(anyhow!("access denied"))?;
 880        }
 881
 882        self.state_mut().join_channel(request.sender_id, channel_id);
 883        let messages = self
 884            .app_state
 885            .db
 886            .get_channel_messages(channel_id, MESSAGE_COUNT_PER_PAGE, None)
 887            .await?
 888            .into_iter()
 889            .map(|msg| proto::ChannelMessage {
 890                id: msg.id.to_proto(),
 891                body: msg.body,
 892                timestamp: msg.sent_at.unix_timestamp() as u64,
 893                sender_id: msg.sender_id.to_proto(),
 894                nonce: Some(msg.nonce.as_u128().into()),
 895            })
 896            .collect::<Vec<_>>();
 897        self.peer.respond(
 898            request.receipt(),
 899            proto::JoinChannelResponse {
 900                done: messages.len() < MESSAGE_COUNT_PER_PAGE,
 901                messages,
 902            },
 903        )?;
 904        Ok(())
 905    }
 906
 907    async fn leave_channel(
 908        mut self: Arc<Self>,
 909        request: TypedEnvelope<proto::LeaveChannel>,
 910    ) -> tide::Result<()> {
 911        let user_id = self.state().user_id_for_connection(request.sender_id)?;
 912        let channel_id = ChannelId::from_proto(request.payload.channel_id);
 913        if !self
 914            .app_state
 915            .db
 916            .can_user_access_channel(user_id, channel_id)
 917            .await?
 918        {
 919            Err(anyhow!("access denied"))?;
 920        }
 921
 922        self.state_mut()
 923            .leave_channel(request.sender_id, channel_id);
 924
 925        Ok(())
 926    }
 927
 928    async fn send_channel_message(
 929        self: Arc<Self>,
 930        request: TypedEnvelope<proto::SendChannelMessage>,
 931    ) -> tide::Result<()> {
 932        let receipt = request.receipt();
 933        let channel_id = ChannelId::from_proto(request.payload.channel_id);
 934        let user_id;
 935        let connection_ids;
 936        {
 937            let state = self.state();
 938            user_id = state.user_id_for_connection(request.sender_id)?;
 939            if let Some(ids) = state.channel_connection_ids(channel_id) {
 940                connection_ids = ids;
 941            } else {
 942                return Ok(());
 943            }
 944        }
 945
 946        // Validate the message body.
 947        let body = request.payload.body.trim().to_string();
 948        if body.len() > MAX_MESSAGE_LEN {
 949            self.peer.respond_with_error(
 950                receipt,
 951                proto::Error {
 952                    message: "message is too long".to_string(),
 953                },
 954            )?;
 955            return Ok(());
 956        }
 957        if body.is_empty() {
 958            self.peer.respond_with_error(
 959                receipt,
 960                proto::Error {
 961                    message: "message can't be blank".to_string(),
 962                },
 963            )?;
 964            return Ok(());
 965        }
 966
 967        let timestamp = OffsetDateTime::now_utc();
 968        let nonce = if let Some(nonce) = request.payload.nonce {
 969            nonce
 970        } else {
 971            self.peer.respond_with_error(
 972                receipt,
 973                proto::Error {
 974                    message: "nonce can't be blank".to_string(),
 975                },
 976            )?;
 977            return Ok(());
 978        };
 979
 980        let message_id = self
 981            .app_state
 982            .db
 983            .create_channel_message(channel_id, user_id, &body, timestamp, nonce.clone().into())
 984            .await?
 985            .to_proto();
 986        let message = proto::ChannelMessage {
 987            sender_id: user_id.to_proto(),
 988            id: message_id,
 989            body,
 990            timestamp: timestamp.unix_timestamp() as u64,
 991            nonce: Some(nonce),
 992        };
 993        broadcast(request.sender_id, connection_ids, |conn_id| {
 994            self.peer.send(
 995                conn_id,
 996                proto::ChannelMessageSent {
 997                    channel_id: channel_id.to_proto(),
 998                    message: Some(message.clone()),
 999                },
1000            )
1001        })?;
1002        self.peer.respond(
1003            receipt,
1004            proto::SendChannelMessageResponse {
1005                message: Some(message),
1006            },
1007        )?;
1008        Ok(())
1009    }
1010
1011    async fn get_channel_messages(
1012        self: Arc<Self>,
1013        request: TypedEnvelope<proto::GetChannelMessages>,
1014    ) -> tide::Result<()> {
1015        let user_id = self.state().user_id_for_connection(request.sender_id)?;
1016        let channel_id = ChannelId::from_proto(request.payload.channel_id);
1017        if !self
1018            .app_state
1019            .db
1020            .can_user_access_channel(user_id, channel_id)
1021            .await?
1022        {
1023            Err(anyhow!("access denied"))?;
1024        }
1025
1026        let messages = self
1027            .app_state
1028            .db
1029            .get_channel_messages(
1030                channel_id,
1031                MESSAGE_COUNT_PER_PAGE,
1032                Some(MessageId::from_proto(request.payload.before_message_id)),
1033            )
1034            .await?
1035            .into_iter()
1036            .map(|msg| proto::ChannelMessage {
1037                id: msg.id.to_proto(),
1038                body: msg.body,
1039                timestamp: msg.sent_at.unix_timestamp() as u64,
1040                sender_id: msg.sender_id.to_proto(),
1041                nonce: Some(msg.nonce.as_u128().into()),
1042            })
1043            .collect::<Vec<_>>();
1044        self.peer.respond(
1045            request.receipt(),
1046            proto::GetChannelMessagesResponse {
1047                done: messages.len() < MESSAGE_COUNT_PER_PAGE,
1048                messages,
1049            },
1050        )?;
1051        Ok(())
1052    }
1053
1054    fn state<'a>(self: &'a Arc<Self>) -> RwLockReadGuard<'a, Store> {
1055        self.store.read()
1056    }
1057
1058    fn state_mut<'a>(self: &'a mut Arc<Self>) -> RwLockWriteGuard<'a, Store> {
1059        self.store.write()
1060    }
1061}
1062
1063fn broadcast<F>(
1064    sender_id: ConnectionId,
1065    receiver_ids: Vec<ConnectionId>,
1066    mut f: F,
1067) -> anyhow::Result<()>
1068where
1069    F: FnMut(ConnectionId) -> anyhow::Result<()>,
1070{
1071    let mut result = Ok(());
1072    for receiver_id in receiver_ids {
1073        if receiver_id != sender_id {
1074            if let Err(error) = f(receiver_id) {
1075                if result.is_ok() {
1076                    result = Err(error);
1077                }
1078            }
1079        }
1080    }
1081    result
1082}
1083
1084pub fn add_routes(app: &mut tide::Server<Arc<AppState>>, rpc: &Arc<Peer>) {
1085    let server = Server::new(app.state().clone(), rpc.clone(), None);
1086    app.at("/rpc").get(move |request: Request<Arc<AppState>>| {
1087        let server = server.clone();
1088        async move {
1089            const WEBSOCKET_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
1090
1091            let connection_upgrade = header_contains_ignore_case(&request, CONNECTION, "upgrade");
1092            let upgrade_to_websocket = header_contains_ignore_case(&request, UPGRADE, "websocket");
1093            let upgrade_requested = connection_upgrade && upgrade_to_websocket;
1094            let client_protocol_version: Option<u32> = request
1095                .header("X-Zed-Protocol-Version")
1096                .and_then(|v| v.as_str().parse().ok());
1097
1098            if !upgrade_requested || client_protocol_version != Some(rpc::PROTOCOL_VERSION) {
1099                return Ok(Response::new(StatusCode::UpgradeRequired));
1100            }
1101
1102            let header = match request.header("Sec-Websocket-Key") {
1103                Some(h) => h.as_str(),
1104                None => return Err(anyhow!("expected sec-websocket-key"))?,
1105            };
1106
1107            let user_id = process_auth_header(&request).await?;
1108
1109            let mut response = Response::new(StatusCode::SwitchingProtocols);
1110            response.insert_header(UPGRADE, "websocket");
1111            response.insert_header(CONNECTION, "Upgrade");
1112            let hash = Sha1::new().chain(header).chain(WEBSOCKET_GUID).finalize();
1113            response.insert_header("Sec-Websocket-Accept", base64::encode(&hash[..]));
1114            response.insert_header("Sec-Websocket-Version", "13");
1115
1116            let http_res: &mut tide::http::Response = response.as_mut();
1117            let upgrade_receiver = http_res.recv_upgrade().await;
1118            let addr = request.remote().unwrap_or("unknown").to_string();
1119            task::spawn(async move {
1120                if let Some(stream) = upgrade_receiver.await {
1121                    server
1122                        .handle_connection(
1123                            Connection::new(
1124                                WebSocketStream::from_raw_socket(stream, Role::Server, None).await,
1125                            ),
1126                            addr,
1127                            user_id,
1128                            None,
1129                        )
1130                        .await;
1131                }
1132            });
1133
1134            Ok(response)
1135        }
1136    });
1137}
1138
1139fn header_contains_ignore_case<T>(
1140    request: &tide::Request<T>,
1141    header_name: HeaderName,
1142    value: &str,
1143) -> bool {
1144    request
1145        .header(header_name)
1146        .map(|h| {
1147            h.as_str()
1148                .split(',')
1149                .any(|s| s.trim().eq_ignore_ascii_case(value.trim()))
1150        })
1151        .unwrap_or(false)
1152}
1153
1154#[cfg(test)]
1155mod tests {
1156    use super::*;
1157    use crate::{
1158        auth,
1159        db::{tests::TestDb, UserId},
1160        github, AppState, Config,
1161    };
1162    use ::rpc::Peer;
1163    use async_std::task;
1164    use gpui::{executor, ModelHandle, TestAppContext};
1165    use parking_lot::Mutex;
1166    use postage::{mpsc, watch};
1167    use rand::prelude::*;
1168    use rpc::PeerId;
1169    use serde_json::json;
1170    use sqlx::types::time::OffsetDateTime;
1171    use std::{
1172        ops::Deref,
1173        path::Path,
1174        rc::Rc,
1175        sync::{
1176            atomic::{AtomicBool, Ordering::SeqCst},
1177            Arc,
1178        },
1179        time::Duration,
1180    };
1181    use zed::{
1182        client::{
1183            self, test::FakeHttpClient, Channel, ChannelDetails, ChannelList, Client, Credentials,
1184            EstablishConnectionError, UserStore,
1185        },
1186        editor::{Editor, EditorSettings, Input, MultiBuffer},
1187        fs::{FakeFs, Fs as _},
1188        language::{
1189            tree_sitter_rust, AnchorRangeExt, Diagnostic, DiagnosticEntry, Language,
1190            LanguageConfig, LanguageRegistry, LanguageServerConfig, Point,
1191        },
1192        lsp,
1193        project::{DiagnosticSummary, Project, ProjectPath},
1194    };
1195
1196    #[cfg(test)]
1197    #[ctor::ctor]
1198    fn init_logger() {
1199        if std::env::var("RUST_LOG").is_ok() {
1200            env_logger::init();
1201        }
1202    }
1203
1204    #[gpui::test(iterations = 10)]
1205    async fn test_share_project(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1206        let (window_b, _) = cx_b.add_window(|_| EmptyView);
1207        let lang_registry = Arc::new(LanguageRegistry::new());
1208        let fs = Arc::new(FakeFs::new(cx_a.background()));
1209        cx_a.foreground().forbid_parking();
1210
1211        // Connect to a server as 2 clients.
1212        let mut server = TestServer::start(cx_a.foreground()).await;
1213        let client_a = server.create_client(&mut cx_a, "user_a").await;
1214        let client_b = server.create_client(&mut cx_b, "user_b").await;
1215
1216        // Share a project as client A
1217        fs.insert_tree(
1218            "/a",
1219            json!({
1220                ".zed.toml": r#"collaborators = ["user_b"]"#,
1221                "a.txt": "a-contents",
1222                "b.txt": "b-contents",
1223            }),
1224        )
1225        .await;
1226        let project_a = cx_a.update(|cx| {
1227            Project::local(
1228                client_a.clone(),
1229                client_a.user_store.clone(),
1230                lang_registry.clone(),
1231                fs.clone(),
1232                cx,
1233            )
1234        });
1235        let (worktree_a, _) = project_a
1236            .update(&mut cx_a, |p, cx| {
1237                p.find_or_create_local_worktree("/a", false, cx)
1238            })
1239            .await
1240            .unwrap();
1241        let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1242        worktree_a
1243            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1244            .await;
1245        let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1246        project_a
1247            .update(&mut cx_a, |p, cx| p.share(cx))
1248            .await
1249            .unwrap();
1250
1251        // Join that project as client B
1252        let project_b = Project::remote(
1253            project_id,
1254            client_b.clone(),
1255            client_b.user_store.clone(),
1256            lang_registry.clone(),
1257            fs.clone(),
1258            &mut cx_b.to_async(),
1259        )
1260        .await
1261        .unwrap();
1262
1263        let replica_id_b = project_b.read_with(&cx_b, |project, _| {
1264            assert_eq!(
1265                project
1266                    .collaborators()
1267                    .get(&client_a.peer_id)
1268                    .unwrap()
1269                    .user
1270                    .github_login,
1271                "user_a"
1272            );
1273            project.replica_id()
1274        });
1275        project_a
1276            .condition(&cx_a, |tree, _| {
1277                tree.collaborators()
1278                    .get(&client_b.peer_id)
1279                    .map_or(false, |collaborator| {
1280                        collaborator.replica_id == replica_id_b
1281                            && collaborator.user.github_login == "user_b"
1282                    })
1283            })
1284            .await;
1285
1286        // Open the same file as client B and client A.
1287        let buffer_b = project_b
1288            .update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "b.txt"), cx))
1289            .await
1290            .unwrap();
1291        let buffer_b = cx_b.add_model(|cx| MultiBuffer::singleton(buffer_b, cx));
1292        buffer_b.read_with(&cx_b, |buf, cx| {
1293            assert_eq!(buf.read(cx).text(), "b-contents")
1294        });
1295        project_a.read_with(&cx_a, |project, cx| {
1296            assert!(project.has_open_buffer((worktree_id, "b.txt"), cx))
1297        });
1298        let buffer_a = project_a
1299            .update(&mut cx_a, |p, cx| p.open_buffer((worktree_id, "b.txt"), cx))
1300            .await
1301            .unwrap();
1302
1303        let editor_b = cx_b.add_view(window_b, |cx| {
1304            Editor::for_buffer(buffer_b, Arc::new(|cx| EditorSettings::test(cx)), cx)
1305        });
1306
1307        // TODO
1308        // // Create a selection set as client B and see that selection set as client A.
1309        // buffer_a
1310        //     .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 1)
1311        //     .await;
1312
1313        // Edit the buffer as client B and see that edit as client A.
1314        editor_b.update(&mut cx_b, |editor, cx| {
1315            editor.handle_input(&Input("ok, ".into()), cx)
1316        });
1317        buffer_a
1318            .condition(&cx_a, |buffer, _| buffer.text() == "ok, b-contents")
1319            .await;
1320
1321        // TODO
1322        // // Remove the selection set as client B, see those selections disappear as client A.
1323        cx_b.update(move |_| drop(editor_b));
1324        // buffer_a
1325        //     .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 0)
1326        //     .await;
1327
1328        // Close the buffer as client A, see that the buffer is closed.
1329        cx_a.update(move |_| drop(buffer_a));
1330        project_a
1331            .condition(&cx_a, |project, cx| {
1332                !project.has_open_buffer((worktree_id, "b.txt"), cx)
1333            })
1334            .await;
1335
1336        // Dropping the client B's project removes client B from client A's collaborators.
1337        cx_b.update(move |_| drop(project_b));
1338        project_a
1339            .condition(&cx_a, |project, _| project.collaborators().is_empty())
1340            .await;
1341    }
1342
1343    #[gpui::test(iterations = 10)]
1344    async fn test_unshare_project(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1345        let lang_registry = Arc::new(LanguageRegistry::new());
1346        let fs = Arc::new(FakeFs::new(cx_a.background()));
1347        cx_a.foreground().forbid_parking();
1348
1349        // Connect to a server as 2 clients.
1350        let mut server = TestServer::start(cx_a.foreground()).await;
1351        let client_a = server.create_client(&mut cx_a, "user_a").await;
1352        let client_b = server.create_client(&mut cx_b, "user_b").await;
1353
1354        // Share a project as client A
1355        fs.insert_tree(
1356            "/a",
1357            json!({
1358                ".zed.toml": r#"collaborators = ["user_b"]"#,
1359                "a.txt": "a-contents",
1360                "b.txt": "b-contents",
1361            }),
1362        )
1363        .await;
1364        let project_a = cx_a.update(|cx| {
1365            Project::local(
1366                client_a.clone(),
1367                client_a.user_store.clone(),
1368                lang_registry.clone(),
1369                fs.clone(),
1370                cx,
1371            )
1372        });
1373        let (worktree_a, _) = project_a
1374            .update(&mut cx_a, |p, cx| {
1375                p.find_or_create_local_worktree("/a", false, cx)
1376            })
1377            .await
1378            .unwrap();
1379        worktree_a
1380            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1381            .await;
1382        let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1383        let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1384        project_a
1385            .update(&mut cx_a, |p, cx| p.share(cx))
1386            .await
1387            .unwrap();
1388        assert!(worktree_a.read_with(&cx_a, |tree, _| tree.as_local().unwrap().is_shared()));
1389
1390        // Join that project as client B
1391        let project_b = Project::remote(
1392            project_id,
1393            client_b.clone(),
1394            client_b.user_store.clone(),
1395            lang_registry.clone(),
1396            fs.clone(),
1397            &mut cx_b.to_async(),
1398        )
1399        .await
1400        .unwrap();
1401        project_b
1402            .update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1403            .await
1404            .unwrap();
1405
1406        // Unshare the project as client A
1407        project_a
1408            .update(&mut cx_a, |project, cx| project.unshare(cx))
1409            .await
1410            .unwrap();
1411        project_b
1412            .condition(&mut cx_b, |project, _| project.is_read_only())
1413            .await;
1414        assert!(worktree_a.read_with(&cx_a, |tree, _| !tree.as_local().unwrap().is_shared()));
1415        drop(project_b);
1416
1417        // Share the project again and ensure guests can still join.
1418        project_a
1419            .update(&mut cx_a, |project, cx| project.share(cx))
1420            .await
1421            .unwrap();
1422        assert!(worktree_a.read_with(&cx_a, |tree, _| tree.as_local().unwrap().is_shared()));
1423
1424        let project_c = Project::remote(
1425            project_id,
1426            client_b.clone(),
1427            client_b.user_store.clone(),
1428            lang_registry.clone(),
1429            fs.clone(),
1430            &mut cx_b.to_async(),
1431        )
1432        .await
1433        .unwrap();
1434        project_c
1435            .update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1436            .await
1437            .unwrap();
1438    }
1439
1440    #[gpui::test(iterations = 10)]
1441    async fn test_propagate_saves_and_fs_changes(
1442        mut cx_a: TestAppContext,
1443        mut cx_b: TestAppContext,
1444        mut cx_c: TestAppContext,
1445    ) {
1446        let lang_registry = Arc::new(LanguageRegistry::new());
1447        let fs = Arc::new(FakeFs::new(cx_a.background()));
1448        cx_a.foreground().forbid_parking();
1449
1450        // Connect to a server as 3 clients.
1451        let mut server = TestServer::start(cx_a.foreground()).await;
1452        let client_a = server.create_client(&mut cx_a, "user_a").await;
1453        let client_b = server.create_client(&mut cx_b, "user_b").await;
1454        let client_c = server.create_client(&mut cx_c, "user_c").await;
1455
1456        // Share a worktree as client A.
1457        fs.insert_tree(
1458            "/a",
1459            json!({
1460                ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
1461                "file1": "",
1462                "file2": ""
1463            }),
1464        )
1465        .await;
1466        let project_a = cx_a.update(|cx| {
1467            Project::local(
1468                client_a.clone(),
1469                client_a.user_store.clone(),
1470                lang_registry.clone(),
1471                fs.clone(),
1472                cx,
1473            )
1474        });
1475        let (worktree_a, _) = project_a
1476            .update(&mut cx_a, |p, cx| {
1477                p.find_or_create_local_worktree("/a", false, cx)
1478            })
1479            .await
1480            .unwrap();
1481        worktree_a
1482            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1483            .await;
1484        let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1485        let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1486        project_a
1487            .update(&mut cx_a, |p, cx| p.share(cx))
1488            .await
1489            .unwrap();
1490
1491        // Join that worktree as clients B and C.
1492        let project_b = Project::remote(
1493            project_id,
1494            client_b.clone(),
1495            client_b.user_store.clone(),
1496            lang_registry.clone(),
1497            fs.clone(),
1498            &mut cx_b.to_async(),
1499        )
1500        .await
1501        .unwrap();
1502        let project_c = Project::remote(
1503            project_id,
1504            client_c.clone(),
1505            client_c.user_store.clone(),
1506            lang_registry.clone(),
1507            fs.clone(),
1508            &mut cx_c.to_async(),
1509        )
1510        .await
1511        .unwrap();
1512        let worktree_b = project_b.read_with(&cx_b, |p, cx| p.worktrees(cx).next().unwrap());
1513        let worktree_c = project_c.read_with(&cx_c, |p, cx| p.worktrees(cx).next().unwrap());
1514
1515        // Open and edit a buffer as both guests B and C.
1516        let buffer_b = project_b
1517            .update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
1518            .await
1519            .unwrap();
1520        let buffer_c = project_c
1521            .update(&mut cx_c, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
1522            .await
1523            .unwrap();
1524        buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "i-am-b, ", cx));
1525        buffer_c.update(&mut cx_c, |buf, cx| buf.edit([0..0], "i-am-c, ", cx));
1526
1527        // Open and edit that buffer as the host.
1528        let buffer_a = project_a
1529            .update(&mut cx_a, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
1530            .await
1531            .unwrap();
1532
1533        buffer_a
1534            .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, ")
1535            .await;
1536        buffer_a.update(&mut cx_a, |buf, cx| {
1537            buf.edit([buf.len()..buf.len()], "i-am-a", cx)
1538        });
1539
1540        // Wait for edits to propagate
1541        buffer_a
1542            .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1543            .await;
1544        buffer_b
1545            .condition(&mut cx_b, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1546            .await;
1547        buffer_c
1548            .condition(&mut cx_c, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1549            .await;
1550
1551        // Edit the buffer as the host and concurrently save as guest B.
1552        let save_b = buffer_b.update(&mut cx_b, |buf, cx| buf.save(cx));
1553        buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "hi-a, ", cx));
1554        save_b.await.unwrap();
1555        assert_eq!(
1556            fs.load("/a/file1".as_ref()).await.unwrap(),
1557            "hi-a, i-am-c, i-am-b, i-am-a"
1558        );
1559        buffer_a.read_with(&cx_a, |buf, _| assert!(!buf.is_dirty()));
1560        buffer_b.read_with(&cx_b, |buf, _| assert!(!buf.is_dirty()));
1561        buffer_c.condition(&cx_c, |buf, _| !buf.is_dirty()).await;
1562
1563        // Make changes on host's file system, see those changes on guest worktrees.
1564        fs.rename("/a/file1".as_ref(), "/a/file1-renamed".as_ref())
1565            .await
1566            .unwrap();
1567        fs.rename("/a/file2".as_ref(), "/a/file3".as_ref())
1568            .await
1569            .unwrap();
1570        fs.insert_file(Path::new("/a/file4"), "4".into())
1571            .await
1572            .unwrap();
1573
1574        worktree_a
1575            .condition(&cx_a, |tree, _| tree.file_count() == 4)
1576            .await;
1577        worktree_b
1578            .condition(&cx_b, |tree, _| tree.file_count() == 4)
1579            .await;
1580        worktree_c
1581            .condition(&cx_c, |tree, _| tree.file_count() == 4)
1582            .await;
1583        worktree_a.read_with(&cx_a, |tree, _| {
1584            assert_eq!(
1585                tree.paths()
1586                    .map(|p| p.to_string_lossy())
1587                    .collect::<Vec<_>>(),
1588                &[".zed.toml", "file1-renamed", "file3", "file4"]
1589            )
1590        });
1591        worktree_b.read_with(&cx_b, |tree, _| {
1592            assert_eq!(
1593                tree.paths()
1594                    .map(|p| p.to_string_lossy())
1595                    .collect::<Vec<_>>(),
1596                &[".zed.toml", "file1-renamed", "file3", "file4"]
1597            )
1598        });
1599        worktree_c.read_with(&cx_c, |tree, _| {
1600            assert_eq!(
1601                tree.paths()
1602                    .map(|p| p.to_string_lossy())
1603                    .collect::<Vec<_>>(),
1604                &[".zed.toml", "file1-renamed", "file3", "file4"]
1605            )
1606        });
1607
1608        // Ensure buffer files are updated as well.
1609        buffer_a
1610            .condition(&cx_a, |buf, _| {
1611                buf.file().unwrap().path().to_str() == Some("file1-renamed")
1612            })
1613            .await;
1614        buffer_b
1615            .condition(&cx_b, |buf, _| {
1616                buf.file().unwrap().path().to_str() == Some("file1-renamed")
1617            })
1618            .await;
1619        buffer_c
1620            .condition(&cx_c, |buf, _| {
1621                buf.file().unwrap().path().to_str() == Some("file1-renamed")
1622            })
1623            .await;
1624    }
1625
1626    #[gpui::test(iterations = 10)]
1627    async fn test_buffer_conflict_after_save(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1628        cx_a.foreground().forbid_parking();
1629        let lang_registry = Arc::new(LanguageRegistry::new());
1630        let fs = Arc::new(FakeFs::new(cx_a.background()));
1631
1632        // Connect to a server as 2 clients.
1633        let mut server = TestServer::start(cx_a.foreground()).await;
1634        let client_a = server.create_client(&mut cx_a, "user_a").await;
1635        let client_b = server.create_client(&mut cx_b, "user_b").await;
1636
1637        // Share a project as client A
1638        fs.insert_tree(
1639            "/dir",
1640            json!({
1641                ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
1642                "a.txt": "a-contents",
1643            }),
1644        )
1645        .await;
1646
1647        let project_a = cx_a.update(|cx| {
1648            Project::local(
1649                client_a.clone(),
1650                client_a.user_store.clone(),
1651                lang_registry.clone(),
1652                fs.clone(),
1653                cx,
1654            )
1655        });
1656        let (worktree_a, _) = project_a
1657            .update(&mut cx_a, |p, cx| {
1658                p.find_or_create_local_worktree("/dir", false, cx)
1659            })
1660            .await
1661            .unwrap();
1662        worktree_a
1663            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1664            .await;
1665        let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1666        let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1667        project_a
1668            .update(&mut cx_a, |p, cx| p.share(cx))
1669            .await
1670            .unwrap();
1671
1672        // Join that project as client B
1673        let project_b = Project::remote(
1674            project_id,
1675            client_b.clone(),
1676            client_b.user_store.clone(),
1677            lang_registry.clone(),
1678            fs.clone(),
1679            &mut cx_b.to_async(),
1680        )
1681        .await
1682        .unwrap();
1683        let worktree_b = project_b.update(&mut cx_b, |p, cx| p.worktrees(cx).next().unwrap());
1684
1685        // Open a buffer as client B
1686        let buffer_b = project_b
1687            .update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1688            .await
1689            .unwrap();
1690        let mtime = buffer_b.read_with(&cx_b, |buf, _| buf.file().unwrap().mtime());
1691
1692        buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "world ", cx));
1693        buffer_b.read_with(&cx_b, |buf, _| {
1694            assert!(buf.is_dirty());
1695            assert!(!buf.has_conflict());
1696        });
1697
1698        buffer_b
1699            .update(&mut cx_b, |buf, cx| buf.save(cx))
1700            .await
1701            .unwrap();
1702        worktree_b
1703            .condition(&cx_b, |_, cx| {
1704                buffer_b.read(cx).file().unwrap().mtime() != mtime
1705            })
1706            .await;
1707        buffer_b.read_with(&cx_b, |buf, _| {
1708            assert!(!buf.is_dirty());
1709            assert!(!buf.has_conflict());
1710        });
1711
1712        buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "hello ", cx));
1713        buffer_b.read_with(&cx_b, |buf, _| {
1714            assert!(buf.is_dirty());
1715            assert!(!buf.has_conflict());
1716        });
1717    }
1718
1719    #[gpui::test(iterations = 10)]
1720    async fn test_buffer_reloading(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1721        cx_a.foreground().forbid_parking();
1722        let lang_registry = Arc::new(LanguageRegistry::new());
1723        let fs = Arc::new(FakeFs::new(cx_a.background()));
1724
1725        // Connect to a server as 2 clients.
1726        let mut server = TestServer::start(cx_a.foreground()).await;
1727        let client_a = server.create_client(&mut cx_a, "user_a").await;
1728        let client_b = server.create_client(&mut cx_b, "user_b").await;
1729
1730        // Share a project as client A
1731        fs.insert_tree(
1732            "/dir",
1733            json!({
1734                ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
1735                "a.txt": "a-contents",
1736            }),
1737        )
1738        .await;
1739
1740        let project_a = cx_a.update(|cx| {
1741            Project::local(
1742                client_a.clone(),
1743                client_a.user_store.clone(),
1744                lang_registry.clone(),
1745                fs.clone(),
1746                cx,
1747            )
1748        });
1749        let (worktree_a, _) = project_a
1750            .update(&mut cx_a, |p, cx| {
1751                p.find_or_create_local_worktree("/dir", false, cx)
1752            })
1753            .await
1754            .unwrap();
1755        worktree_a
1756            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1757            .await;
1758        let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1759        let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1760        project_a
1761            .update(&mut cx_a, |p, cx| p.share(cx))
1762            .await
1763            .unwrap();
1764
1765        // Join that project as client B
1766        let project_b = Project::remote(
1767            project_id,
1768            client_b.clone(),
1769            client_b.user_store.clone(),
1770            lang_registry.clone(),
1771            fs.clone(),
1772            &mut cx_b.to_async(),
1773        )
1774        .await
1775        .unwrap();
1776        let _worktree_b = project_b.update(&mut cx_b, |p, cx| p.worktrees(cx).next().unwrap());
1777
1778        // Open a buffer as client B
1779        let buffer_b = project_b
1780            .update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1781            .await
1782            .unwrap();
1783        buffer_b.read_with(&cx_b, |buf, _| {
1784            assert!(!buf.is_dirty());
1785            assert!(!buf.has_conflict());
1786        });
1787
1788        fs.save(Path::new("/dir/a.txt"), &"new contents".into())
1789            .await
1790            .unwrap();
1791        buffer_b
1792            .condition(&cx_b, |buf, _| {
1793                buf.text() == "new contents" && !buf.is_dirty()
1794            })
1795            .await;
1796        buffer_b.read_with(&cx_b, |buf, _| {
1797            assert!(!buf.has_conflict());
1798        });
1799    }
1800
1801    #[gpui::test(iterations = 100)]
1802    async fn test_editing_while_guest_opens_buffer(
1803        mut cx_a: TestAppContext,
1804        mut cx_b: TestAppContext,
1805    ) {
1806        cx_a.foreground().forbid_parking();
1807        let lang_registry = Arc::new(LanguageRegistry::new());
1808        let fs = Arc::new(FakeFs::new(cx_a.background()));
1809
1810        // Connect to a server as 2 clients.
1811        let mut server = TestServer::start(cx_a.foreground()).await;
1812        let client_a = server.create_client(&mut cx_a, "user_a").await;
1813        let client_b = server.create_client(&mut cx_b, "user_b").await;
1814
1815        // Share a project as client A
1816        fs.insert_tree(
1817            "/dir",
1818            json!({
1819                ".zed.toml": r#"collaborators = ["user_b"]"#,
1820                "a.txt": "a-contents",
1821            }),
1822        )
1823        .await;
1824        let project_a = cx_a.update(|cx| {
1825            Project::local(
1826                client_a.clone(),
1827                client_a.user_store.clone(),
1828                lang_registry.clone(),
1829                fs.clone(),
1830                cx,
1831            )
1832        });
1833        let (worktree_a, _) = project_a
1834            .update(&mut cx_a, |p, cx| {
1835                p.find_or_create_local_worktree("/dir", false, cx)
1836            })
1837            .await
1838            .unwrap();
1839        worktree_a
1840            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1841            .await;
1842        let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1843        let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1844        project_a
1845            .update(&mut cx_a, |p, cx| p.share(cx))
1846            .await
1847            .unwrap();
1848
1849        // Join that project as client B
1850        let project_b = Project::remote(
1851            project_id,
1852            client_b.clone(),
1853            client_b.user_store.clone(),
1854            lang_registry.clone(),
1855            fs.clone(),
1856            &mut cx_b.to_async(),
1857        )
1858        .await
1859        .unwrap();
1860
1861        // Open a buffer as client A
1862        let buffer_a = project_a
1863            .update(&mut cx_a, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1864            .await
1865            .unwrap();
1866
1867        // Start opening the same buffer as client B
1868        let buffer_b = cx_b
1869            .background()
1870            .spawn(project_b.update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx)));
1871        task::yield_now().await;
1872
1873        // Edit the buffer as client A while client B is still opening it.
1874        buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "z", cx));
1875
1876        let text = buffer_a.read_with(&cx_a, |buf, _| buf.text());
1877        let buffer_b = buffer_b.await.unwrap();
1878        buffer_b.condition(&cx_b, |buf, _| buf.text() == text).await;
1879    }
1880
1881    #[gpui::test(iterations = 10)]
1882    async fn test_leaving_worktree_while_opening_buffer(
1883        mut cx_a: TestAppContext,
1884        mut cx_b: TestAppContext,
1885    ) {
1886        cx_a.foreground().forbid_parking();
1887        let lang_registry = Arc::new(LanguageRegistry::new());
1888        let fs = Arc::new(FakeFs::new(cx_a.background()));
1889
1890        // Connect to a server as 2 clients.
1891        let mut server = TestServer::start(cx_a.foreground()).await;
1892        let client_a = server.create_client(&mut cx_a, "user_a").await;
1893        let client_b = server.create_client(&mut cx_b, "user_b").await;
1894
1895        // Share a project as client A
1896        fs.insert_tree(
1897            "/dir",
1898            json!({
1899                ".zed.toml": r#"collaborators = ["user_b"]"#,
1900                "a.txt": "a-contents",
1901            }),
1902        )
1903        .await;
1904        let project_a = cx_a.update(|cx| {
1905            Project::local(
1906                client_a.clone(),
1907                client_a.user_store.clone(),
1908                lang_registry.clone(),
1909                fs.clone(),
1910                cx,
1911            )
1912        });
1913        let (worktree_a, _) = project_a
1914            .update(&mut cx_a, |p, cx| {
1915                p.find_or_create_local_worktree("/dir", false, cx)
1916            })
1917            .await
1918            .unwrap();
1919        worktree_a
1920            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1921            .await;
1922        let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1923        let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1924        project_a
1925            .update(&mut cx_a, |p, cx| p.share(cx))
1926            .await
1927            .unwrap();
1928
1929        // Join that project as client B
1930        let project_b = Project::remote(
1931            project_id,
1932            client_b.clone(),
1933            client_b.user_store.clone(),
1934            lang_registry.clone(),
1935            fs.clone(),
1936            &mut cx_b.to_async(),
1937        )
1938        .await
1939        .unwrap();
1940
1941        // See that a guest has joined as client A.
1942        project_a
1943            .condition(&cx_a, |p, _| p.collaborators().len() == 1)
1944            .await;
1945
1946        // Begin opening a buffer as client B, but leave the project before the open completes.
1947        let buffer_b = cx_b
1948            .background()
1949            .spawn(project_b.update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx)));
1950        cx_b.update(|_| drop(project_b));
1951        drop(buffer_b);
1952
1953        // See that the guest has left.
1954        project_a
1955            .condition(&cx_a, |p, _| p.collaborators().len() == 0)
1956            .await;
1957    }
1958
1959    #[gpui::test(iterations = 10)]
1960    async fn test_peer_disconnection(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1961        cx_a.foreground().forbid_parking();
1962        let lang_registry = Arc::new(LanguageRegistry::new());
1963        let fs = Arc::new(FakeFs::new(cx_a.background()));
1964
1965        // Connect to a server as 2 clients.
1966        let mut server = TestServer::start(cx_a.foreground()).await;
1967        let client_a = server.create_client(&mut cx_a, "user_a").await;
1968        let client_b = server.create_client(&mut cx_b, "user_b").await;
1969
1970        // Share a project as client A
1971        fs.insert_tree(
1972            "/a",
1973            json!({
1974                ".zed.toml": r#"collaborators = ["user_b"]"#,
1975                "a.txt": "a-contents",
1976                "b.txt": "b-contents",
1977            }),
1978        )
1979        .await;
1980        let project_a = cx_a.update(|cx| {
1981            Project::local(
1982                client_a.clone(),
1983                client_a.user_store.clone(),
1984                lang_registry.clone(),
1985                fs.clone(),
1986                cx,
1987            )
1988        });
1989        let (worktree_a, _) = project_a
1990            .update(&mut cx_a, |p, cx| {
1991                p.find_or_create_local_worktree("/a", false, cx)
1992            })
1993            .await
1994            .unwrap();
1995        worktree_a
1996            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1997            .await;
1998        let project_id = project_a
1999            .update(&mut cx_a, |project, _| project.next_remote_id())
2000            .await;
2001        project_a
2002            .update(&mut cx_a, |project, cx| project.share(cx))
2003            .await
2004            .unwrap();
2005
2006        // Join that project as client B
2007        let _project_b = Project::remote(
2008            project_id,
2009            client_b.clone(),
2010            client_b.user_store.clone(),
2011            lang_registry.clone(),
2012            fs.clone(),
2013            &mut cx_b.to_async(),
2014        )
2015        .await
2016        .unwrap();
2017
2018        // See that a guest has joined as client A.
2019        project_a
2020            .condition(&cx_a, |p, _| p.collaborators().len() == 1)
2021            .await;
2022
2023        // Drop client B's connection and ensure client A observes client B leaving the worktree.
2024        client_b.disconnect(&cx_b.to_async()).unwrap();
2025        project_a
2026            .condition(&cx_a, |p, _| p.collaborators().len() == 0)
2027            .await;
2028    }
2029
2030    #[gpui::test(iterations = 10)]
2031    async fn test_collaborating_with_diagnostics(
2032        mut cx_a: TestAppContext,
2033        mut cx_b: TestAppContext,
2034    ) {
2035        cx_a.foreground().forbid_parking();
2036        let mut lang_registry = Arc::new(LanguageRegistry::new());
2037        let fs = Arc::new(FakeFs::new(cx_a.background()));
2038
2039        // Set up a fake language server.
2040        let (language_server_config, mut fake_language_server) =
2041            LanguageServerConfig::fake(cx_a.background()).await;
2042        Arc::get_mut(&mut lang_registry)
2043            .unwrap()
2044            .add(Arc::new(Language::new(
2045                LanguageConfig {
2046                    name: "Rust".to_string(),
2047                    path_suffixes: vec!["rs".to_string()],
2048                    language_server: Some(language_server_config),
2049                    ..Default::default()
2050                },
2051                Some(tree_sitter_rust::language()),
2052            )));
2053
2054        // Connect to a server as 2 clients.
2055        let mut server = TestServer::start(cx_a.foreground()).await;
2056        let client_a = server.create_client(&mut cx_a, "user_a").await;
2057        let client_b = server.create_client(&mut cx_b, "user_b").await;
2058
2059        // Share a project as client A
2060        fs.insert_tree(
2061            "/a",
2062            json!({
2063                ".zed.toml": r#"collaborators = ["user_b"]"#,
2064                "a.rs": "let one = two",
2065                "other.rs": "",
2066            }),
2067        )
2068        .await;
2069        let project_a = cx_a.update(|cx| {
2070            Project::local(
2071                client_a.clone(),
2072                client_a.user_store.clone(),
2073                lang_registry.clone(),
2074                fs.clone(),
2075                cx,
2076            )
2077        });
2078        let (worktree_a, _) = project_a
2079            .update(&mut cx_a, |p, cx| {
2080                p.find_or_create_local_worktree("/a", false, cx)
2081            })
2082            .await
2083            .unwrap();
2084        worktree_a
2085            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2086            .await;
2087        let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
2088        let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
2089        project_a
2090            .update(&mut cx_a, |p, cx| p.share(cx))
2091            .await
2092            .unwrap();
2093
2094        // Cause the language server to start.
2095        let _ = cx_a
2096            .background()
2097            .spawn(project_a.update(&mut 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        fake_language_server
2111            .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
2112                uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
2113                version: None,
2114                diagnostics: vec![lsp::Diagnostic {
2115                    severity: Some(lsp::DiagnosticSeverity::ERROR),
2116                    range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
2117                    message: "message 1".to_string(),
2118                    ..Default::default()
2119                }],
2120            })
2121            .await;
2122
2123        // Wait for server to see the diagnostics update.
2124        server
2125            .condition(|store| {
2126                let worktree = store
2127                    .project(project_id)
2128                    .unwrap()
2129                    .worktrees
2130                    .get(&worktree_id.to_proto())
2131                    .unwrap();
2132
2133                !worktree
2134                    .share
2135                    .as_ref()
2136                    .unwrap()
2137                    .diagnostic_summaries
2138                    .is_empty()
2139            })
2140            .await;
2141
2142        // Join the worktree as client B.
2143        let project_b = Project::remote(
2144            project_id,
2145            client_b.clone(),
2146            client_b.user_store.clone(),
2147            lang_registry.clone(),
2148            fs.clone(),
2149            &mut cx_b.to_async(),
2150        )
2151        .await
2152        .unwrap();
2153
2154        project_b.read_with(&cx_b, |project, cx| {
2155            assert_eq!(
2156                project.diagnostic_summaries(cx).collect::<Vec<_>>(),
2157                &[(
2158                    ProjectPath {
2159                        worktree_id,
2160                        path: Arc::from(Path::new("a.rs")),
2161                    },
2162                    DiagnosticSummary {
2163                        error_count: 1,
2164                        warning_count: 0,
2165                        ..Default::default()
2166                    },
2167                )]
2168            )
2169        });
2170
2171        // Simulate a language server reporting more errors for a file.
2172        fake_language_server
2173            .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
2174                uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
2175                version: None,
2176                diagnostics: vec![
2177                    lsp::Diagnostic {
2178                        severity: Some(lsp::DiagnosticSeverity::ERROR),
2179                        range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
2180                        message: "message 1".to_string(),
2181                        ..Default::default()
2182                    },
2183                    lsp::Diagnostic {
2184                        severity: Some(lsp::DiagnosticSeverity::WARNING),
2185                        range: lsp::Range::new(
2186                            lsp::Position::new(0, 10),
2187                            lsp::Position::new(0, 13),
2188                        ),
2189                        message: "message 2".to_string(),
2190                        ..Default::default()
2191                    },
2192                ],
2193            })
2194            .await;
2195
2196        // Client b gets the updated summaries
2197        project_b
2198            .condition(&cx_b, |project, cx| {
2199                project.diagnostic_summaries(cx).collect::<Vec<_>>()
2200                    == &[(
2201                        ProjectPath {
2202                            worktree_id,
2203                            path: Arc::from(Path::new("a.rs")),
2204                        },
2205                        DiagnosticSummary {
2206                            error_count: 1,
2207                            warning_count: 1,
2208                            ..Default::default()
2209                        },
2210                    )]
2211            })
2212            .await;
2213
2214        // Open the file with the errors on client B. They should be present.
2215        let buffer_b = cx_b
2216            .background()
2217            .spawn(project_b.update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
2218            .await
2219            .unwrap();
2220
2221        buffer_b.read_with(&cx_b, |buffer, _| {
2222            assert_eq!(
2223                buffer
2224                    .snapshot()
2225                    .diagnostics_in_range::<_, Point>(0..buffer.len())
2226                    .map(|entry| entry)
2227                    .collect::<Vec<_>>(),
2228                &[
2229                    DiagnosticEntry {
2230                        range: Point::new(0, 4)..Point::new(0, 7),
2231                        diagnostic: Diagnostic {
2232                            group_id: 0,
2233                            message: "message 1".to_string(),
2234                            severity: lsp::DiagnosticSeverity::ERROR,
2235                            is_primary: true,
2236                            ..Default::default()
2237                        }
2238                    },
2239                    DiagnosticEntry {
2240                        range: Point::new(0, 10)..Point::new(0, 13),
2241                        diagnostic: Diagnostic {
2242                            group_id: 1,
2243                            severity: lsp::DiagnosticSeverity::WARNING,
2244                            message: "message 2".to_string(),
2245                            is_primary: true,
2246                            ..Default::default()
2247                        }
2248                    }
2249                ]
2250            );
2251        });
2252    }
2253
2254    #[gpui::test(iterations = 10)]
2255    async fn test_collaborating_with_completion(
2256        mut cx_a: TestAppContext,
2257        mut cx_b: TestAppContext,
2258    ) {
2259        cx_a.foreground().forbid_parking();
2260        let mut lang_registry = Arc::new(LanguageRegistry::new());
2261        let fs = Arc::new(FakeFs::new(cx_a.background()));
2262
2263        // Set up a fake language server.
2264        let (language_server_config, mut fake_language_server) =
2265            LanguageServerConfig::fake_with_capabilities(
2266                lsp::ServerCapabilities {
2267                    completion_provider: Some(lsp::CompletionOptions {
2268                        trigger_characters: Some(vec![".".to_string()]),
2269                        ..Default::default()
2270                    }),
2271                    ..Default::default()
2272                },
2273                cx_a.background(),
2274            )
2275            .await;
2276        Arc::get_mut(&mut lang_registry)
2277            .unwrap()
2278            .add(Arc::new(Language::new(
2279                LanguageConfig {
2280                    name: "Rust".to_string(),
2281                    path_suffixes: vec!["rs".to_string()],
2282                    language_server: Some(language_server_config),
2283                    ..Default::default()
2284                },
2285                Some(tree_sitter_rust::language()),
2286            )));
2287
2288        // Connect to a server as 2 clients.
2289        let mut server = TestServer::start(cx_a.foreground()).await;
2290        let client_a = server.create_client(&mut cx_a, "user_a").await;
2291        let client_b = server.create_client(&mut cx_b, "user_b").await;
2292
2293        // Share a project as client A
2294        fs.insert_tree(
2295            "/a",
2296            json!({
2297                ".zed.toml": r#"collaborators = ["user_b"]"#,
2298                "main.rs": "fn main() { a }",
2299                "other.rs": "",
2300            }),
2301        )
2302        .await;
2303        let project_a = cx_a.update(|cx| {
2304            Project::local(
2305                client_a.clone(),
2306                client_a.user_store.clone(),
2307                lang_registry.clone(),
2308                fs.clone(),
2309                cx,
2310            )
2311        });
2312        let (worktree_a, _) = project_a
2313            .update(&mut cx_a, |p, cx| {
2314                p.find_or_create_local_worktree("/a", false, cx)
2315            })
2316            .await
2317            .unwrap();
2318        worktree_a
2319            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2320            .await;
2321        let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
2322        let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
2323        project_a
2324            .update(&mut cx_a, |p, cx| p.share(cx))
2325            .await
2326            .unwrap();
2327
2328        // Join the worktree as client B.
2329        let project_b = Project::remote(
2330            project_id,
2331            client_b.clone(),
2332            client_b.user_store.clone(),
2333            lang_registry.clone(),
2334            fs.clone(),
2335            &mut cx_b.to_async(),
2336        )
2337        .await
2338        .unwrap();
2339
2340        // Open a file in an editor as the guest.
2341        let buffer_b = project_b
2342            .update(&mut cx_b, |p, cx| {
2343                p.open_buffer((worktree_id, "main.rs"), cx)
2344            })
2345            .await
2346            .unwrap();
2347        let (window_b, _) = cx_b.add_window(|_| EmptyView);
2348        let editor_b = cx_b.add_view(window_b, |cx| {
2349            Editor::for_buffer(
2350                cx.add_model(|cx| MultiBuffer::singleton(buffer_b.clone(), cx)),
2351                Arc::new(|cx| EditorSettings::test(cx)),
2352                cx,
2353            )
2354        });
2355
2356        // Type a completion trigger character as the guest.
2357        editor_b.update(&mut cx_b, |editor, cx| {
2358            editor.select_ranges([13..13], None, cx);
2359            editor.handle_input(&Input(".".into()), cx);
2360            cx.focus(&editor_b);
2361        });
2362
2363        // Receive a completion request as the host's language server.
2364        let (request_id, params) = fake_language_server
2365            .receive_request::<lsp::request::Completion>()
2366            .await;
2367        assert_eq!(
2368            params.text_document_position.text_document.uri,
2369            lsp::Url::from_file_path("/a/main.rs").unwrap(),
2370        );
2371        assert_eq!(
2372            params.text_document_position.position,
2373            lsp::Position::new(0, 14),
2374        );
2375
2376        // Return some completions from the host's language server.
2377        fake_language_server
2378            .respond(
2379                request_id,
2380                Some(lsp::CompletionResponse::Array(vec![
2381                    lsp::CompletionItem {
2382                        label: "first_method(…)".into(),
2383                        detail: Some("fn(&mut self, B) -> C".into()),
2384                        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
2385                            new_text: "first_method($1)".to_string(),
2386                            range: lsp::Range::new(
2387                                lsp::Position::new(0, 14),
2388                                lsp::Position::new(0, 14),
2389                            ),
2390                        })),
2391                        insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
2392                        ..Default::default()
2393                    },
2394                    lsp::CompletionItem {
2395                        label: "second_method(…)".into(),
2396                        detail: Some("fn(&mut self, C) -> D<E>".into()),
2397                        text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
2398                            new_text: "second_method()".to_string(),
2399                            range: lsp::Range::new(
2400                                lsp::Position::new(0, 14),
2401                                lsp::Position::new(0, 14),
2402                            ),
2403                        })),
2404                        insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
2405                        ..Default::default()
2406                    },
2407                ])),
2408            )
2409            .await;
2410
2411        // Open the buffer on the host.
2412        let buffer_a = project_a
2413            .update(&mut cx_a, |p, cx| {
2414                p.open_buffer((worktree_id, "main.rs"), cx)
2415            })
2416            .await
2417            .unwrap();
2418        buffer_a
2419            .condition(&cx_a, |buffer, _| buffer.text() == "fn main() { a. }")
2420            .await;
2421
2422        // Confirm a completion on the guest.
2423        editor_b.next_notification(&cx_b).await;
2424        editor_b.update(&mut cx_b, |editor, cx| {
2425            assert!(editor.has_completions());
2426            editor.confirm_completion(Some(0), cx);
2427            assert_eq!(editor.text(cx), "fn main() { a.first_method() }");
2428        });
2429
2430        buffer_a
2431            .condition(&cx_a, |buffer, _| {
2432                buffer.text() == "fn main() { a.first_method() }"
2433            })
2434            .await;
2435
2436        // Receive a request resolve the selected completion on the host's language server.
2437        let (request_id, params) = fake_language_server
2438            .receive_request::<lsp::request::ResolveCompletionItem>()
2439            .await;
2440        assert_eq!(params.label, "first_method(…)");
2441
2442        // Return a resolved completion from the host's language server.
2443        // The resolved completion has an additional text edit.
2444        fake_language_server
2445            .respond(
2446                request_id,
2447                lsp::CompletionItem {
2448                    label: "first_method(…)".into(),
2449                    detail: Some("fn(&mut self, B) -> C".into()),
2450                    text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
2451                        new_text: "first_method($1)".to_string(),
2452                        range: lsp::Range::new(
2453                            lsp::Position::new(0, 14),
2454                            lsp::Position::new(0, 14),
2455                        ),
2456                    })),
2457                    additional_text_edits: Some(vec![lsp::TextEdit {
2458                        new_text: "use d::SomeTrait;\n".to_string(),
2459                        range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
2460                    }]),
2461                    insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
2462                    ..Default::default()
2463                },
2464            )
2465            .await;
2466
2467        // The additional edit is applied.
2468        buffer_b
2469            .condition(&cx_b, |buffer, _| {
2470                buffer.text() == "use d::SomeTrait;\nfn main() { a.first_method() }"
2471            })
2472            .await;
2473        assert_eq!(
2474            buffer_a.read_with(&cx_a, |buffer, _| buffer.text()),
2475            buffer_b.read_with(&cx_b, |buffer, _| buffer.text()),
2476        );
2477    }
2478
2479    #[gpui::test(iterations = 10)]
2480    async fn test_formatting_buffer(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
2481        cx_a.foreground().forbid_parking();
2482        let mut lang_registry = Arc::new(LanguageRegistry::new());
2483        let fs = Arc::new(FakeFs::new(cx_a.background()));
2484
2485        // Set up a fake language server.
2486        let (language_server_config, mut fake_language_server) =
2487            LanguageServerConfig::fake(cx_a.background()).await;
2488        Arc::get_mut(&mut lang_registry)
2489            .unwrap()
2490            .add(Arc::new(Language::new(
2491                LanguageConfig {
2492                    name: "Rust".to_string(),
2493                    path_suffixes: vec!["rs".to_string()],
2494                    language_server: Some(language_server_config),
2495                    ..Default::default()
2496                },
2497                Some(tree_sitter_rust::language()),
2498            )));
2499
2500        // Connect to a server as 2 clients.
2501        let mut server = TestServer::start(cx_a.foreground()).await;
2502        let client_a = server.create_client(&mut cx_a, "user_a").await;
2503        let client_b = server.create_client(&mut cx_b, "user_b").await;
2504
2505        // Share a project as client A
2506        fs.insert_tree(
2507            "/a",
2508            json!({
2509                ".zed.toml": r#"collaborators = ["user_b"]"#,
2510                "a.rs": "let one = two",
2511            }),
2512        )
2513        .await;
2514        let project_a = cx_a.update(|cx| {
2515            Project::local(
2516                client_a.clone(),
2517                client_a.user_store.clone(),
2518                lang_registry.clone(),
2519                fs.clone(),
2520                cx,
2521            )
2522        });
2523        let (worktree_a, _) = project_a
2524            .update(&mut cx_a, |p, cx| {
2525                p.find_or_create_local_worktree("/a", false, cx)
2526            })
2527            .await
2528            .unwrap();
2529        worktree_a
2530            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2531            .await;
2532        let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
2533        let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
2534        project_a
2535            .update(&mut cx_a, |p, cx| p.share(cx))
2536            .await
2537            .unwrap();
2538
2539        // Join the worktree as client B.
2540        let project_b = Project::remote(
2541            project_id,
2542            client_b.clone(),
2543            client_b.user_store.clone(),
2544            lang_registry.clone(),
2545            fs.clone(),
2546            &mut cx_b.to_async(),
2547        )
2548        .await
2549        .unwrap();
2550
2551        let buffer_b = cx_b
2552            .background()
2553            .spawn(project_b.update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
2554            .await
2555            .unwrap();
2556
2557        let format = buffer_b.update(&mut cx_b, |buffer, cx| buffer.format(cx));
2558        let (request_id, _) = fake_language_server
2559            .receive_request::<lsp::request::Formatting>()
2560            .await;
2561        fake_language_server
2562            .respond(
2563                request_id,
2564                Some(vec![
2565                    lsp::TextEdit {
2566                        range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 4)),
2567                        new_text: "h".to_string(),
2568                    },
2569                    lsp::TextEdit {
2570                        range: lsp::Range::new(lsp::Position::new(0, 7), lsp::Position::new(0, 7)),
2571                        new_text: "y".to_string(),
2572                    },
2573                ]),
2574            )
2575            .await;
2576        format.await.unwrap();
2577        assert_eq!(
2578            buffer_b.read_with(&cx_b, |buffer, _| buffer.text()),
2579            "let honey = two"
2580        );
2581    }
2582
2583    #[gpui::test(iterations = 10)]
2584    async fn test_definition(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
2585        cx_a.foreground().forbid_parking();
2586        let mut lang_registry = Arc::new(LanguageRegistry::new());
2587        let fs = Arc::new(FakeFs::new(cx_a.background()));
2588        fs.insert_tree(
2589            "/root-1",
2590            json!({
2591                ".zed.toml": r#"collaborators = ["user_b"]"#,
2592                "a.rs": "const ONE: usize = b::TWO + b::THREE;",
2593            }),
2594        )
2595        .await;
2596        fs.insert_tree(
2597            "/root-2",
2598            json!({
2599                "b.rs": "const TWO: usize = 2;\nconst THREE: usize = 3;",
2600            }),
2601        )
2602        .await;
2603
2604        // Set up a fake language server.
2605        let (language_server_config, mut fake_language_server) =
2606            LanguageServerConfig::fake(cx_a.background()).await;
2607        Arc::get_mut(&mut lang_registry)
2608            .unwrap()
2609            .add(Arc::new(Language::new(
2610                LanguageConfig {
2611                    name: "Rust".to_string(),
2612                    path_suffixes: vec!["rs".to_string()],
2613                    language_server: Some(language_server_config),
2614                    ..Default::default()
2615                },
2616                Some(tree_sitter_rust::language()),
2617            )));
2618
2619        // Connect to a server as 2 clients.
2620        let mut server = TestServer::start(cx_a.foreground()).await;
2621        let client_a = server.create_client(&mut cx_a, "user_a").await;
2622        let client_b = server.create_client(&mut cx_b, "user_b").await;
2623
2624        // Share a project as client A
2625        let project_a = cx_a.update(|cx| {
2626            Project::local(
2627                client_a.clone(),
2628                client_a.user_store.clone(),
2629                lang_registry.clone(),
2630                fs.clone(),
2631                cx,
2632            )
2633        });
2634        let (worktree_a, _) = project_a
2635            .update(&mut cx_a, |p, cx| {
2636                p.find_or_create_local_worktree("/root-1", false, cx)
2637            })
2638            .await
2639            .unwrap();
2640        worktree_a
2641            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2642            .await;
2643        let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
2644        let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
2645        project_a
2646            .update(&mut cx_a, |p, cx| p.share(cx))
2647            .await
2648            .unwrap();
2649
2650        // Join the worktree as client B.
2651        let project_b = Project::remote(
2652            project_id,
2653            client_b.clone(),
2654            client_b.user_store.clone(),
2655            lang_registry.clone(),
2656            fs.clone(),
2657            &mut cx_b.to_async(),
2658        )
2659        .await
2660        .unwrap();
2661
2662        // Open the file to be formatted on client B.
2663        let buffer_b = cx_b
2664            .background()
2665            .spawn(project_b.update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
2666            .await
2667            .unwrap();
2668
2669        let definitions_1 = project_b.update(&mut cx_b, |p, cx| p.definition(&buffer_b, 23, cx));
2670        let (request_id, _) = fake_language_server
2671            .receive_request::<lsp::request::GotoDefinition>()
2672            .await;
2673        fake_language_server
2674            .respond(
2675                request_id,
2676                Some(lsp::GotoDefinitionResponse::Scalar(lsp::Location::new(
2677                    lsp::Url::from_file_path("/root-2/b.rs").unwrap(),
2678                    lsp::Range::new(lsp::Position::new(0, 6), lsp::Position::new(0, 9)),
2679                ))),
2680            )
2681            .await;
2682        let definitions_1 = definitions_1.await.unwrap();
2683        cx_b.read(|cx| {
2684            assert_eq!(definitions_1.len(), 1);
2685            assert_eq!(project_b.read(cx).worktrees(cx).count(), 2);
2686            let target_buffer = definitions_1[0].target_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_1[0].target_range.to_point(target_buffer),
2693                Point::new(0, 6)..Point::new(0, 9)
2694            );
2695        });
2696
2697        // Try getting more definitions for the same buffer, ensuring the buffer gets reused from
2698        // the previous call to `definition`.
2699        let definitions_2 = project_b.update(&mut cx_b, |p, cx| p.definition(&buffer_b, 33, cx));
2700        let (request_id, _) = fake_language_server
2701            .receive_request::<lsp::request::GotoDefinition>()
2702            .await;
2703        fake_language_server
2704            .respond(
2705                request_id,
2706                Some(lsp::GotoDefinitionResponse::Scalar(lsp::Location::new(
2707                    lsp::Url::from_file_path("/root-2/b.rs").unwrap(),
2708                    lsp::Range::new(lsp::Position::new(1, 6), lsp::Position::new(1, 11)),
2709                ))),
2710            )
2711            .await;
2712        let definitions_2 = definitions_2.await.unwrap();
2713        cx_b.read(|cx| {
2714            assert_eq!(definitions_2.len(), 1);
2715            assert_eq!(project_b.read(cx).worktrees(cx).count(), 2);
2716            let target_buffer = definitions_2[0].target_buffer.read(cx);
2717            assert_eq!(
2718                target_buffer.text(),
2719                "const TWO: usize = 2;\nconst THREE: usize = 3;"
2720            );
2721            assert_eq!(
2722                definitions_2[0].target_range.to_point(target_buffer),
2723                Point::new(1, 6)..Point::new(1, 11)
2724            );
2725        });
2726        assert_eq!(
2727            definitions_1[0].target_buffer,
2728            definitions_2[0].target_buffer
2729        );
2730
2731        cx_b.update(|_| {
2732            drop(definitions_1);
2733            drop(definitions_2);
2734        });
2735        project_b
2736            .condition(&cx_b, |proj, cx| proj.worktrees(cx).count() == 1)
2737            .await;
2738    }
2739
2740    #[gpui::test(iterations = 10)]
2741    async fn test_open_buffer_while_getting_definition_pointing_to_it(
2742        mut cx_a: TestAppContext,
2743        mut cx_b: TestAppContext,
2744        mut rng: StdRng,
2745    ) {
2746        cx_a.foreground().forbid_parking();
2747        let mut lang_registry = Arc::new(LanguageRegistry::new());
2748        let fs = Arc::new(FakeFs::new(cx_a.background()));
2749        fs.insert_tree(
2750            "/root",
2751            json!({
2752                ".zed.toml": r#"collaborators = ["user_b"]"#,
2753                "a.rs": "const ONE: usize = b::TWO;",
2754                "b.rs": "const TWO: usize = 2",
2755            }),
2756        )
2757        .await;
2758
2759        // Set up a fake language server.
2760        let (language_server_config, mut fake_language_server) =
2761            LanguageServerConfig::fake(cx_a.background()).await;
2762        Arc::get_mut(&mut lang_registry)
2763            .unwrap()
2764            .add(Arc::new(Language::new(
2765                LanguageConfig {
2766                    name: "Rust".to_string(),
2767                    path_suffixes: vec!["rs".to_string()],
2768                    language_server: Some(language_server_config),
2769                    ..Default::default()
2770                },
2771                Some(tree_sitter_rust::language()),
2772            )));
2773
2774        // Connect to a server as 2 clients.
2775        let mut server = TestServer::start(cx_a.foreground()).await;
2776        let client_a = server.create_client(&mut cx_a, "user_a").await;
2777        let client_b = server.create_client(&mut cx_b, "user_b").await;
2778
2779        // Share a project as client A
2780        let project_a = cx_a.update(|cx| {
2781            Project::local(
2782                client_a.clone(),
2783                client_a.user_store.clone(),
2784                lang_registry.clone(),
2785                fs.clone(),
2786                cx,
2787            )
2788        });
2789        let (worktree_a, _) = project_a
2790            .update(&mut cx_a, |p, cx| {
2791                p.find_or_create_local_worktree("/root", false, cx)
2792            })
2793            .await
2794            .unwrap();
2795        worktree_a
2796            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2797            .await;
2798        let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
2799        let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
2800        project_a
2801            .update(&mut cx_a, |p, cx| p.share(cx))
2802            .await
2803            .unwrap();
2804
2805        // Join the worktree as client B.
2806        let project_b = Project::remote(
2807            project_id,
2808            client_b.clone(),
2809            client_b.user_store.clone(),
2810            lang_registry.clone(),
2811            fs.clone(),
2812            &mut cx_b.to_async(),
2813        )
2814        .await
2815        .unwrap();
2816
2817        let buffer_b1 = cx_b
2818            .background()
2819            .spawn(project_b.update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
2820            .await
2821            .unwrap();
2822
2823        let definitions;
2824        let buffer_b2;
2825        if rng.gen() {
2826            definitions = project_b.update(&mut cx_b, |p, cx| p.definition(&buffer_b1, 23, cx));
2827            buffer_b2 =
2828                project_b.update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "b.rs"), cx));
2829        } else {
2830            buffer_b2 =
2831                project_b.update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "b.rs"), cx));
2832            definitions = project_b.update(&mut cx_b, |p, cx| p.definition(&buffer_b1, 23, cx));
2833        }
2834
2835        let (request_id, _) = fake_language_server
2836            .receive_request::<lsp::request::GotoDefinition>()
2837            .await;
2838        fake_language_server
2839            .respond(
2840                request_id,
2841                Some(lsp::GotoDefinitionResponse::Scalar(lsp::Location::new(
2842                    lsp::Url::from_file_path("/root/b.rs").unwrap(),
2843                    lsp::Range::new(lsp::Position::new(0, 6), lsp::Position::new(0, 9)),
2844                ))),
2845            )
2846            .await;
2847
2848        let buffer_b2 = buffer_b2.await.unwrap();
2849        let definitions = definitions.await.unwrap();
2850        assert_eq!(definitions.len(), 1);
2851        assert_eq!(definitions[0].target_buffer, buffer_b2);
2852    }
2853
2854    #[gpui::test(iterations = 10)]
2855    async fn test_basic_chat(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
2856        cx_a.foreground().forbid_parking();
2857
2858        // Connect to a server as 2 clients.
2859        let mut server = TestServer::start(cx_a.foreground()).await;
2860        let client_a = server.create_client(&mut cx_a, "user_a").await;
2861        let client_b = server.create_client(&mut cx_b, "user_b").await;
2862
2863        // Create an org that includes these 2 users.
2864        let db = &server.app_state.db;
2865        let org_id = db.create_org("Test Org", "test-org").await.unwrap();
2866        db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
2867            .await
2868            .unwrap();
2869        db.add_org_member(org_id, client_b.current_user_id(&cx_b), false)
2870            .await
2871            .unwrap();
2872
2873        // Create a channel that includes all the users.
2874        let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
2875        db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
2876            .await
2877            .unwrap();
2878        db.add_channel_member(channel_id, client_b.current_user_id(&cx_b), false)
2879            .await
2880            .unwrap();
2881        db.create_channel_message(
2882            channel_id,
2883            client_b.current_user_id(&cx_b),
2884            "hello A, it's B.",
2885            OffsetDateTime::now_utc(),
2886            1,
2887        )
2888        .await
2889        .unwrap();
2890
2891        let channels_a = cx_a
2892            .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
2893        channels_a
2894            .condition(&mut cx_a, |list, _| list.available_channels().is_some())
2895            .await;
2896        channels_a.read_with(&cx_a, |list, _| {
2897            assert_eq!(
2898                list.available_channels().unwrap(),
2899                &[ChannelDetails {
2900                    id: channel_id.to_proto(),
2901                    name: "test-channel".to_string()
2902                }]
2903            )
2904        });
2905        let channel_a = channels_a.update(&mut cx_a, |this, cx| {
2906            this.get_channel(channel_id.to_proto(), cx).unwrap()
2907        });
2908        channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
2909        channel_a
2910            .condition(&cx_a, |channel, _| {
2911                channel_messages(channel)
2912                    == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2913            })
2914            .await;
2915
2916        let channels_b = cx_b
2917            .add_model(|cx| ChannelList::new(client_b.user_store.clone(), client_b.clone(), cx));
2918        channels_b
2919            .condition(&mut cx_b, |list, _| list.available_channels().is_some())
2920            .await;
2921        channels_b.read_with(&cx_b, |list, _| {
2922            assert_eq!(
2923                list.available_channels().unwrap(),
2924                &[ChannelDetails {
2925                    id: channel_id.to_proto(),
2926                    name: "test-channel".to_string()
2927                }]
2928            )
2929        });
2930
2931        let channel_b = channels_b.update(&mut cx_b, |this, cx| {
2932            this.get_channel(channel_id.to_proto(), cx).unwrap()
2933        });
2934        channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
2935        channel_b
2936            .condition(&cx_b, |channel, _| {
2937                channel_messages(channel)
2938                    == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2939            })
2940            .await;
2941
2942        channel_a
2943            .update(&mut cx_a, |channel, cx| {
2944                channel
2945                    .send_message("oh, hi B.".to_string(), cx)
2946                    .unwrap()
2947                    .detach();
2948                let task = channel.send_message("sup".to_string(), cx).unwrap();
2949                assert_eq!(
2950                    channel_messages(channel),
2951                    &[
2952                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2953                        ("user_a".to_string(), "oh, hi B.".to_string(), true),
2954                        ("user_a".to_string(), "sup".to_string(), true)
2955                    ]
2956                );
2957                task
2958            })
2959            .await
2960            .unwrap();
2961
2962        channel_b
2963            .condition(&cx_b, |channel, _| {
2964                channel_messages(channel)
2965                    == [
2966                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2967                        ("user_a".to_string(), "oh, hi B.".to_string(), false),
2968                        ("user_a".to_string(), "sup".to_string(), false),
2969                    ]
2970            })
2971            .await;
2972
2973        assert_eq!(
2974            server
2975                .state()
2976                .await
2977                .channel(channel_id)
2978                .unwrap()
2979                .connection_ids
2980                .len(),
2981            2
2982        );
2983        cx_b.update(|_| drop(channel_b));
2984        server
2985            .condition(|state| state.channel(channel_id).unwrap().connection_ids.len() == 1)
2986            .await;
2987
2988        cx_a.update(|_| drop(channel_a));
2989        server
2990            .condition(|state| state.channel(channel_id).is_none())
2991            .await;
2992    }
2993
2994    #[gpui::test(iterations = 10)]
2995    async fn test_chat_message_validation(mut cx_a: TestAppContext) {
2996        cx_a.foreground().forbid_parking();
2997
2998        let mut server = TestServer::start(cx_a.foreground()).await;
2999        let client_a = server.create_client(&mut cx_a, "user_a").await;
3000
3001        let db = &server.app_state.db;
3002        let org_id = db.create_org("Test Org", "test-org").await.unwrap();
3003        let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
3004        db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
3005            .await
3006            .unwrap();
3007        db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
3008            .await
3009            .unwrap();
3010
3011        let channels_a = cx_a
3012            .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
3013        channels_a
3014            .condition(&mut cx_a, |list, _| list.available_channels().is_some())
3015            .await;
3016        let channel_a = channels_a.update(&mut cx_a, |this, cx| {
3017            this.get_channel(channel_id.to_proto(), cx).unwrap()
3018        });
3019
3020        // Messages aren't allowed to be too long.
3021        channel_a
3022            .update(&mut cx_a, |channel, cx| {
3023                let long_body = "this is long.\n".repeat(1024);
3024                channel.send_message(long_body, cx).unwrap()
3025            })
3026            .await
3027            .unwrap_err();
3028
3029        // Messages aren't allowed to be blank.
3030        channel_a.update(&mut cx_a, |channel, cx| {
3031            channel.send_message(String::new(), cx).unwrap_err()
3032        });
3033
3034        // Leading and trailing whitespace are trimmed.
3035        channel_a
3036            .update(&mut cx_a, |channel, cx| {
3037                channel
3038                    .send_message("\n surrounded by whitespace  \n".to_string(), cx)
3039                    .unwrap()
3040            })
3041            .await
3042            .unwrap();
3043        assert_eq!(
3044            db.get_channel_messages(channel_id, 10, None)
3045                .await
3046                .unwrap()
3047                .iter()
3048                .map(|m| &m.body)
3049                .collect::<Vec<_>>(),
3050            &["surrounded by whitespace"]
3051        );
3052    }
3053
3054    #[gpui::test(iterations = 10)]
3055    async fn test_chat_reconnection(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
3056        cx_a.foreground().forbid_parking();
3057
3058        // Connect to a server as 2 clients.
3059        let mut server = TestServer::start(cx_a.foreground()).await;
3060        let client_a = server.create_client(&mut cx_a, "user_a").await;
3061        let client_b = server.create_client(&mut cx_b, "user_b").await;
3062        let mut status_b = client_b.status();
3063
3064        // Create an org that includes these 2 users.
3065        let db = &server.app_state.db;
3066        let org_id = db.create_org("Test Org", "test-org").await.unwrap();
3067        db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
3068            .await
3069            .unwrap();
3070        db.add_org_member(org_id, client_b.current_user_id(&cx_b), false)
3071            .await
3072            .unwrap();
3073
3074        // Create a channel that includes all the users.
3075        let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
3076        db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
3077            .await
3078            .unwrap();
3079        db.add_channel_member(channel_id, client_b.current_user_id(&cx_b), false)
3080            .await
3081            .unwrap();
3082        db.create_channel_message(
3083            channel_id,
3084            client_b.current_user_id(&cx_b),
3085            "hello A, it's B.",
3086            OffsetDateTime::now_utc(),
3087            2,
3088        )
3089        .await
3090        .unwrap();
3091
3092        let channels_a = cx_a
3093            .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
3094        channels_a
3095            .condition(&mut cx_a, |list, _| list.available_channels().is_some())
3096            .await;
3097
3098        channels_a.read_with(&cx_a, |list, _| {
3099            assert_eq!(
3100                list.available_channels().unwrap(),
3101                &[ChannelDetails {
3102                    id: channel_id.to_proto(),
3103                    name: "test-channel".to_string()
3104                }]
3105            )
3106        });
3107        let channel_a = channels_a.update(&mut cx_a, |this, cx| {
3108            this.get_channel(channel_id.to_proto(), cx).unwrap()
3109        });
3110        channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
3111        channel_a
3112            .condition(&cx_a, |channel, _| {
3113                channel_messages(channel)
3114                    == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
3115            })
3116            .await;
3117
3118        let channels_b = cx_b
3119            .add_model(|cx| ChannelList::new(client_b.user_store.clone(), client_b.clone(), cx));
3120        channels_b
3121            .condition(&mut cx_b, |list, _| list.available_channels().is_some())
3122            .await;
3123        channels_b.read_with(&cx_b, |list, _| {
3124            assert_eq!(
3125                list.available_channels().unwrap(),
3126                &[ChannelDetails {
3127                    id: channel_id.to_proto(),
3128                    name: "test-channel".to_string()
3129                }]
3130            )
3131        });
3132
3133        let channel_b = channels_b.update(&mut cx_b, |this, cx| {
3134            this.get_channel(channel_id.to_proto(), cx).unwrap()
3135        });
3136        channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
3137        channel_b
3138            .condition(&cx_b, |channel, _| {
3139                channel_messages(channel)
3140                    == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
3141            })
3142            .await;
3143
3144        // Disconnect client B, ensuring we can still access its cached channel data.
3145        server.forbid_connections();
3146        server.disconnect_client(client_b.current_user_id(&cx_b));
3147        while !matches!(
3148            status_b.next().await,
3149            Some(client::Status::ReconnectionError { .. })
3150        ) {}
3151
3152        channels_b.read_with(&cx_b, |channels, _| {
3153            assert_eq!(
3154                channels.available_channels().unwrap(),
3155                [ChannelDetails {
3156                    id: channel_id.to_proto(),
3157                    name: "test-channel".to_string()
3158                }]
3159            )
3160        });
3161        channel_b.read_with(&cx_b, |channel, _| {
3162            assert_eq!(
3163                channel_messages(channel),
3164                [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
3165            )
3166        });
3167
3168        // Send a message from client B while it is disconnected.
3169        channel_b
3170            .update(&mut cx_b, |channel, cx| {
3171                let task = channel
3172                    .send_message("can you see this?".to_string(), cx)
3173                    .unwrap();
3174                assert_eq!(
3175                    channel_messages(channel),
3176                    &[
3177                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3178                        ("user_b".to_string(), "can you see this?".to_string(), true)
3179                    ]
3180                );
3181                task
3182            })
3183            .await
3184            .unwrap_err();
3185
3186        // Send a message from client A while B is disconnected.
3187        channel_a
3188            .update(&mut cx_a, |channel, cx| {
3189                channel
3190                    .send_message("oh, hi B.".to_string(), cx)
3191                    .unwrap()
3192                    .detach();
3193                let task = channel.send_message("sup".to_string(), cx).unwrap();
3194                assert_eq!(
3195                    channel_messages(channel),
3196                    &[
3197                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3198                        ("user_a".to_string(), "oh, hi B.".to_string(), true),
3199                        ("user_a".to_string(), "sup".to_string(), true)
3200                    ]
3201                );
3202                task
3203            })
3204            .await
3205            .unwrap();
3206
3207        // Give client B a chance to reconnect.
3208        server.allow_connections();
3209        cx_b.foreground().advance_clock(Duration::from_secs(10));
3210
3211        // Verify that B sees the new messages upon reconnection, as well as the message client B
3212        // sent while offline.
3213        channel_b
3214            .condition(&cx_b, |channel, _| {
3215                channel_messages(channel)
3216                    == [
3217                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3218                        ("user_a".to_string(), "oh, hi B.".to_string(), false),
3219                        ("user_a".to_string(), "sup".to_string(), false),
3220                        ("user_b".to_string(), "can you see this?".to_string(), false),
3221                    ]
3222            })
3223            .await;
3224
3225        // Ensure client A and B can communicate normally after reconnection.
3226        channel_a
3227            .update(&mut cx_a, |channel, cx| {
3228                channel.send_message("you online?".to_string(), cx).unwrap()
3229            })
3230            .await
3231            .unwrap();
3232        channel_b
3233            .condition(&cx_b, |channel, _| {
3234                channel_messages(channel)
3235                    == [
3236                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3237                        ("user_a".to_string(), "oh, hi B.".to_string(), false),
3238                        ("user_a".to_string(), "sup".to_string(), false),
3239                        ("user_b".to_string(), "can you see this?".to_string(), false),
3240                        ("user_a".to_string(), "you online?".to_string(), false),
3241                    ]
3242            })
3243            .await;
3244
3245        channel_b
3246            .update(&mut cx_b, |channel, cx| {
3247                channel.send_message("yep".to_string(), cx).unwrap()
3248            })
3249            .await
3250            .unwrap();
3251        channel_a
3252            .condition(&cx_a, |channel, _| {
3253                channel_messages(channel)
3254                    == [
3255                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3256                        ("user_a".to_string(), "oh, hi B.".to_string(), false),
3257                        ("user_a".to_string(), "sup".to_string(), false),
3258                        ("user_b".to_string(), "can you see this?".to_string(), false),
3259                        ("user_a".to_string(), "you online?".to_string(), false),
3260                        ("user_b".to_string(), "yep".to_string(), false),
3261                    ]
3262            })
3263            .await;
3264    }
3265
3266    #[gpui::test(iterations = 10)]
3267    async fn test_contacts(
3268        mut cx_a: TestAppContext,
3269        mut cx_b: TestAppContext,
3270        mut cx_c: TestAppContext,
3271    ) {
3272        cx_a.foreground().forbid_parking();
3273        let lang_registry = Arc::new(LanguageRegistry::new());
3274        let fs = Arc::new(FakeFs::new(cx_a.background()));
3275
3276        // Connect to a server as 3 clients.
3277        let mut server = TestServer::start(cx_a.foreground()).await;
3278        let client_a = server.create_client(&mut cx_a, "user_a").await;
3279        let client_b = server.create_client(&mut cx_b, "user_b").await;
3280        let client_c = server.create_client(&mut cx_c, "user_c").await;
3281
3282        // Share a worktree as client A.
3283        fs.insert_tree(
3284            "/a",
3285            json!({
3286                ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
3287            }),
3288        )
3289        .await;
3290
3291        let project_a = cx_a.update(|cx| {
3292            Project::local(
3293                client_a.clone(),
3294                client_a.user_store.clone(),
3295                lang_registry.clone(),
3296                fs.clone(),
3297                cx,
3298            )
3299        });
3300        let (worktree_a, _) = project_a
3301            .update(&mut cx_a, |p, cx| {
3302                p.find_or_create_local_worktree("/a", false, cx)
3303            })
3304            .await
3305            .unwrap();
3306        worktree_a
3307            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
3308            .await;
3309
3310        client_a
3311            .user_store
3312            .condition(&cx_a, |user_store, _| {
3313                contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
3314            })
3315            .await;
3316        client_b
3317            .user_store
3318            .condition(&cx_b, |user_store, _| {
3319                contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
3320            })
3321            .await;
3322        client_c
3323            .user_store
3324            .condition(&cx_c, |user_store, _| {
3325                contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
3326            })
3327            .await;
3328
3329        let project_id = project_a
3330            .update(&mut cx_a, |project, _| project.next_remote_id())
3331            .await;
3332        project_a
3333            .update(&mut cx_a, |project, cx| project.share(cx))
3334            .await
3335            .unwrap();
3336
3337        let _project_b = Project::remote(
3338            project_id,
3339            client_b.clone(),
3340            client_b.user_store.clone(),
3341            lang_registry.clone(),
3342            fs.clone(),
3343            &mut cx_b.to_async(),
3344        )
3345        .await
3346        .unwrap();
3347
3348        client_a
3349            .user_store
3350            .condition(&cx_a, |user_store, _| {
3351                contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
3352            })
3353            .await;
3354        client_b
3355            .user_store
3356            .condition(&cx_b, |user_store, _| {
3357                contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
3358            })
3359            .await;
3360        client_c
3361            .user_store
3362            .condition(&cx_c, |user_store, _| {
3363                contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
3364            })
3365            .await;
3366
3367        project_a
3368            .condition(&cx_a, |project, _| {
3369                project.collaborators().contains_key(&client_b.peer_id)
3370            })
3371            .await;
3372
3373        cx_a.update(move |_| drop(project_a));
3374        client_a
3375            .user_store
3376            .condition(&cx_a, |user_store, _| contacts(user_store) == vec![])
3377            .await;
3378        client_b
3379            .user_store
3380            .condition(&cx_b, |user_store, _| contacts(user_store) == vec![])
3381            .await;
3382        client_c
3383            .user_store
3384            .condition(&cx_c, |user_store, _| contacts(user_store) == vec![])
3385            .await;
3386
3387        fn contacts(user_store: &UserStore) -> Vec<(&str, Vec<(&str, Vec<&str>)>)> {
3388            user_store
3389                .contacts()
3390                .iter()
3391                .map(|contact| {
3392                    let worktrees = contact
3393                        .projects
3394                        .iter()
3395                        .map(|p| {
3396                            (
3397                                p.worktree_root_names[0].as_str(),
3398                                p.guests.iter().map(|p| p.github_login.as_str()).collect(),
3399                            )
3400                        })
3401                        .collect();
3402                    (contact.user.github_login.as_str(), worktrees)
3403                })
3404                .collect()
3405        }
3406    }
3407
3408    struct TestServer {
3409        peer: Arc<Peer>,
3410        app_state: Arc<AppState>,
3411        server: Arc<Server>,
3412        foreground: Rc<executor::Foreground>,
3413        notifications: mpsc::Receiver<()>,
3414        connection_killers: Arc<Mutex<HashMap<UserId, watch::Sender<Option<()>>>>>,
3415        forbid_connections: Arc<AtomicBool>,
3416        _test_db: TestDb,
3417    }
3418
3419    impl TestServer {
3420        async fn start(foreground: Rc<executor::Foreground>) -> Self {
3421            let test_db = TestDb::new();
3422            let app_state = Self::build_app_state(&test_db).await;
3423            let peer = Peer::new();
3424            let notifications = mpsc::channel(128);
3425            let server = Server::new(app_state.clone(), peer.clone(), Some(notifications.0));
3426            Self {
3427                peer,
3428                app_state,
3429                server,
3430                foreground,
3431                notifications: notifications.1,
3432                connection_killers: Default::default(),
3433                forbid_connections: Default::default(),
3434                _test_db: test_db,
3435            }
3436        }
3437
3438        async fn create_client(&mut self, cx: &mut TestAppContext, name: &str) -> TestClient {
3439            let http = FakeHttpClient::with_404_response();
3440            let user_id = self.app_state.db.create_user(name, false).await.unwrap();
3441            let client_name = name.to_string();
3442            let mut client = Client::new(http.clone());
3443            let server = self.server.clone();
3444            let connection_killers = self.connection_killers.clone();
3445            let forbid_connections = self.forbid_connections.clone();
3446            let (connection_id_tx, mut connection_id_rx) = postage::mpsc::channel(16);
3447
3448            Arc::get_mut(&mut client)
3449                .unwrap()
3450                .override_authenticate(move |cx| {
3451                    cx.spawn(|_| async move {
3452                        let access_token = "the-token".to_string();
3453                        Ok(Credentials {
3454                            user_id: user_id.0 as u64,
3455                            access_token,
3456                        })
3457                    })
3458                })
3459                .override_establish_connection(move |credentials, cx| {
3460                    assert_eq!(credentials.user_id, user_id.0 as u64);
3461                    assert_eq!(credentials.access_token, "the-token");
3462
3463                    let server = server.clone();
3464                    let connection_killers = connection_killers.clone();
3465                    let forbid_connections = forbid_connections.clone();
3466                    let client_name = client_name.clone();
3467                    let connection_id_tx = connection_id_tx.clone();
3468                    cx.spawn(move |cx| async move {
3469                        if forbid_connections.load(SeqCst) {
3470                            Err(EstablishConnectionError::other(anyhow!(
3471                                "server is forbidding connections"
3472                            )))
3473                        } else {
3474                            let (client_conn, server_conn, kill_conn) =
3475                                Connection::in_memory(cx.background());
3476                            connection_killers.lock().insert(user_id, kill_conn);
3477                            cx.background()
3478                                .spawn(server.handle_connection(
3479                                    server_conn,
3480                                    client_name,
3481                                    user_id,
3482                                    Some(connection_id_tx),
3483                                ))
3484                                .detach();
3485                            Ok(client_conn)
3486                        }
3487                    })
3488                });
3489
3490            client
3491                .authenticate_and_connect(&cx.to_async())
3492                .await
3493                .unwrap();
3494
3495            let peer_id = PeerId(connection_id_rx.next().await.unwrap().0);
3496            let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http, cx));
3497            let mut authed_user =
3498                user_store.read_with(cx, |user_store, _| user_store.watch_current_user());
3499            while authed_user.next().await.unwrap().is_none() {}
3500
3501            TestClient {
3502                client,
3503                peer_id,
3504                user_store,
3505            }
3506        }
3507
3508        fn disconnect_client(&self, user_id: UserId) {
3509            if let Some(mut kill_conn) = self.connection_killers.lock().remove(&user_id) {
3510                let _ = kill_conn.try_send(Some(()));
3511            }
3512        }
3513
3514        fn forbid_connections(&self) {
3515            self.forbid_connections.store(true, SeqCst);
3516        }
3517
3518        fn allow_connections(&self) {
3519            self.forbid_connections.store(false, SeqCst);
3520        }
3521
3522        async fn build_app_state(test_db: &TestDb) -> Arc<AppState> {
3523            let mut config = Config::default();
3524            config.session_secret = "a".repeat(32);
3525            config.database_url = test_db.url.clone();
3526            let github_client = github::AppClient::test();
3527            Arc::new(AppState {
3528                db: test_db.db().clone(),
3529                handlebars: Default::default(),
3530                auth_client: auth::build_client("", ""),
3531                repo_client: github::RepoClient::test(&github_client),
3532                github_client,
3533                config,
3534            })
3535        }
3536
3537        async fn state<'a>(&'a self) -> RwLockReadGuard<'a, Store> {
3538            self.server.store.read()
3539        }
3540
3541        async fn condition<F>(&mut self, mut predicate: F)
3542        where
3543            F: FnMut(&Store) -> bool,
3544        {
3545            async_std::future::timeout(Duration::from_millis(500), async {
3546                while !(predicate)(&*self.server.store.read()) {
3547                    self.foreground.start_waiting();
3548                    self.notifications.next().await;
3549                    self.foreground.finish_waiting();
3550                }
3551            })
3552            .await
3553            .expect("condition timed out");
3554        }
3555    }
3556
3557    impl Drop for TestServer {
3558        fn drop(&mut self) {
3559            self.peer.reset();
3560        }
3561    }
3562
3563    struct TestClient {
3564        client: Arc<Client>,
3565        pub peer_id: PeerId,
3566        pub user_store: ModelHandle<UserStore>,
3567    }
3568
3569    impl Deref for TestClient {
3570        type Target = Arc<Client>;
3571
3572        fn deref(&self) -> &Self::Target {
3573            &self.client
3574        }
3575    }
3576
3577    impl TestClient {
3578        pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
3579            UserId::from_proto(
3580                self.user_store
3581                    .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
3582            )
3583        }
3584    }
3585
3586    fn channel_messages(channel: &Channel) -> Vec<(String, String, bool)> {
3587        channel
3588            .messages()
3589            .cursor::<()>()
3590            .map(|m| {
3591                (
3592                    m.sender.github_login.clone(),
3593                    m.body.clone(),
3594                    m.is_pending(),
3595                )
3596            })
3597            .collect()
3598    }
3599
3600    struct EmptyView;
3601
3602    impl gpui::Entity for EmptyView {
3603        type Event = ();
3604    }
3605
3606    impl gpui::View for EmptyView {
3607        fn ui_name() -> &'static str {
3608            "empty view"
3609        }
3610
3611        fn render(&mut self, _: &mut gpui::RenderContext<Self>) -> gpui::ElementBox {
3612            gpui::Element::boxed(gpui::elements::Empty)
3613        }
3614    }
3615}