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