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