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_message_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<()> {
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.removed_entries,
506 &request.payload.updated_entries,
507 )?;
508
509 broadcast(request.sender_id, connection_ids, |connection_id| {
510 self.peer
511 .forward_send(request.sender_id, connection_id, request.payload.clone())
512 })?;
513
514 Ok(())
515 }
516
517 async fn update_diagnostic_summary(
518 mut self: Arc<Server>,
519 request: TypedEnvelope<proto::UpdateDiagnosticSummary>,
520 ) -> tide::Result<()> {
521 let summary = request
522 .payload
523 .summary
524 .clone()
525 .ok_or_else(|| anyhow!("invalid summary"))?;
526 let receiver_ids = self.state_mut().update_diagnostic_summary(
527 request.payload.project_id,
528 request.payload.worktree_id,
529 request.sender_id,
530 summary,
531 )?;
532
533 broadcast(request.sender_id, receiver_ids, |connection_id| {
534 self.peer
535 .forward_send(request.sender_id, connection_id, request.payload.clone())
536 })?;
537 Ok(())
538 }
539
540 async fn disk_based_diagnostics_updating(
541 self: Arc<Server>,
542 request: TypedEnvelope<proto::DiskBasedDiagnosticsUpdating>,
543 ) -> tide::Result<()> {
544 let receiver_ids = self
545 .state()
546 .project_connection_ids(request.payload.project_id, request.sender_id)?;
547 broadcast(request.sender_id, receiver_ids, |connection_id| {
548 self.peer
549 .forward_send(request.sender_id, connection_id, request.payload.clone())
550 })?;
551 Ok(())
552 }
553
554 async fn disk_based_diagnostics_updated(
555 self: Arc<Server>,
556 request: TypedEnvelope<proto::DiskBasedDiagnosticsUpdated>,
557 ) -> tide::Result<()> {
558 let receiver_ids = self
559 .state()
560 .project_connection_ids(request.payload.project_id, request.sender_id)?;
561 broadcast(request.sender_id, receiver_ids, |connection_id| {
562 self.peer
563 .forward_send(request.sender_id, connection_id, request.payload.clone())
564 })?;
565 Ok(())
566 }
567
568 async fn get_definition(
569 self: Arc<Server>,
570 request: TypedEnvelope<proto::GetDefinition>,
571 ) -> tide::Result<proto::GetDefinitionResponse> {
572 let host_connection_id = self
573 .state()
574 .read_project(request.payload.project_id, request.sender_id)?
575 .host_connection_id;
576 Ok(self
577 .peer
578 .forward_request(request.sender_id, host_connection_id, request.payload)
579 .await?)
580 }
581
582 async fn open_buffer(
583 self: Arc<Server>,
584 request: TypedEnvelope<proto::OpenBuffer>,
585 ) -> tide::Result<proto::OpenBufferResponse> {
586 let host_connection_id = self
587 .state()
588 .read_project(request.payload.project_id, request.sender_id)?
589 .host_connection_id;
590 Ok(self
591 .peer
592 .forward_request(request.sender_id, host_connection_id, request.payload)
593 .await?)
594 }
595
596 async fn close_buffer(
597 self: Arc<Server>,
598 request: TypedEnvelope<proto::CloseBuffer>,
599 ) -> tide::Result<()> {
600 let host_connection_id = self
601 .state()
602 .read_project(request.payload.project_id, request.sender_id)?
603 .host_connection_id;
604 self.peer
605 .forward_send(request.sender_id, host_connection_id, request.payload)?;
606 Ok(())
607 }
608
609 async fn save_buffer(
610 self: Arc<Server>,
611 request: TypedEnvelope<proto::SaveBuffer>,
612 ) -> tide::Result<proto::BufferSaved> {
613 let host;
614 let mut guests;
615 {
616 let state = self.state();
617 let project = state.read_project(request.payload.project_id, request.sender_id)?;
618 host = project.host_connection_id;
619 guests = project.guest_connection_ids()
620 }
621
622 let response = self
623 .peer
624 .forward_request(request.sender_id, host, request.payload.clone())
625 .await?;
626
627 guests.retain(|guest_connection_id| *guest_connection_id != request.sender_id);
628 broadcast(host, guests, |conn_id| {
629 self.peer.forward_send(host, conn_id, response.clone())
630 })?;
631
632 Ok(response)
633 }
634
635 async fn format_buffers(
636 self: Arc<Server>,
637 request: TypedEnvelope<proto::FormatBuffers>,
638 ) -> tide::Result<proto::FormatBuffersResponse> {
639 let host = self
640 .state()
641 .read_project(request.payload.project_id, request.sender_id)?
642 .host_connection_id;
643 Ok(self
644 .peer
645 .forward_request(request.sender_id, host, request.payload.clone())
646 .await?)
647 }
648
649 async fn get_completions(
650 self: Arc<Server>,
651 request: TypedEnvelope<proto::GetCompletions>,
652 ) -> tide::Result<proto::GetCompletionsResponse> {
653 let host = self
654 .state()
655 .read_project(request.payload.project_id, request.sender_id)?
656 .host_connection_id;
657 Ok(self
658 .peer
659 .forward_request(request.sender_id, host, request.payload.clone())
660 .await?)
661 }
662
663 async fn apply_additional_edits_for_completion(
664 self: Arc<Server>,
665 request: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
666 ) -> tide::Result<proto::ApplyCompletionAdditionalEditsResponse> {
667 let host = self
668 .state()
669 .read_project(request.payload.project_id, request.sender_id)?
670 .host_connection_id;
671 Ok(self
672 .peer
673 .forward_request(request.sender_id, host, request.payload.clone())
674 .await?)
675 }
676
677 async fn get_code_actions(
678 self: Arc<Server>,
679 request: TypedEnvelope<proto::GetCodeActions>,
680 ) -> tide::Result<proto::GetCodeActionsResponse> {
681 let host = self
682 .state()
683 .read_project(request.payload.project_id, request.sender_id)?
684 .host_connection_id;
685 Ok(self
686 .peer
687 .forward_request(request.sender_id, host, request.payload.clone())
688 .await?)
689 }
690
691 async fn apply_code_action(
692 self: Arc<Server>,
693 request: TypedEnvelope<proto::ApplyCodeAction>,
694 ) -> tide::Result<proto::ApplyCodeActionResponse> {
695 let host = self
696 .state()
697 .read_project(request.payload.project_id, request.sender_id)?
698 .host_connection_id;
699 Ok(self
700 .peer
701 .forward_request(request.sender_id, host, request.payload.clone())
702 .await?)
703 }
704
705 async fn update_buffer(
706 self: Arc<Server>,
707 request: TypedEnvelope<proto::UpdateBuffer>,
708 ) -> tide::Result<proto::Ack> {
709 let receiver_ids = self
710 .state()
711 .project_connection_ids(request.payload.project_id, request.sender_id)?;
712 broadcast(request.sender_id, receiver_ids, |connection_id| {
713 self.peer
714 .forward_send(request.sender_id, connection_id, request.payload.clone())
715 })?;
716 Ok(proto::Ack {})
717 }
718
719 async fn update_buffer_file(
720 self: Arc<Server>,
721 request: TypedEnvelope<proto::UpdateBufferFile>,
722 ) -> tide::Result<()> {
723 let receiver_ids = self
724 .state()
725 .project_connection_ids(request.payload.project_id, request.sender_id)?;
726 broadcast(request.sender_id, receiver_ids, |connection_id| {
727 self.peer
728 .forward_send(request.sender_id, connection_id, request.payload.clone())
729 })?;
730 Ok(())
731 }
732
733 async fn buffer_reloaded(
734 self: Arc<Server>,
735 request: TypedEnvelope<proto::BufferReloaded>,
736 ) -> tide::Result<()> {
737 let receiver_ids = self
738 .state()
739 .project_connection_ids(request.payload.project_id, request.sender_id)?;
740 broadcast(request.sender_id, receiver_ids, |connection_id| {
741 self.peer
742 .forward_send(request.sender_id, connection_id, request.payload.clone())
743 })?;
744 Ok(())
745 }
746
747 async fn buffer_saved(
748 self: Arc<Server>,
749 request: TypedEnvelope<proto::BufferSaved>,
750 ) -> tide::Result<()> {
751 let receiver_ids = self
752 .state()
753 .project_connection_ids(request.payload.project_id, request.sender_id)?;
754 broadcast(request.sender_id, receiver_ids, |connection_id| {
755 self.peer
756 .forward_send(request.sender_id, connection_id, request.payload.clone())
757 })?;
758 Ok(())
759 }
760
761 async fn get_channels(
762 self: Arc<Server>,
763 request: TypedEnvelope<proto::GetChannels>,
764 ) -> tide::Result<proto::GetChannelsResponse> {
765 let user_id = self.state().user_id_for_connection(request.sender_id)?;
766 let channels = self.app_state.db.get_accessible_channels(user_id).await?;
767 Ok(proto::GetChannelsResponse {
768 channels: channels
769 .into_iter()
770 .map(|chan| proto::Channel {
771 id: chan.id.to_proto(),
772 name: chan.name,
773 })
774 .collect(),
775 })
776 }
777
778 async fn get_users(
779 self: Arc<Server>,
780 request: TypedEnvelope<proto::GetUsers>,
781 ) -> tide::Result<proto::GetUsersResponse> {
782 let user_ids = request.payload.user_ids.into_iter().map(UserId::from_proto);
783 let users = self
784 .app_state
785 .db
786 .get_users_by_ids(user_ids)
787 .await?
788 .into_iter()
789 .map(|user| proto::User {
790 id: user.id.to_proto(),
791 avatar_url: format!("https://github.com/{}.png?size=128", user.github_login),
792 github_login: user.github_login,
793 })
794 .collect();
795 Ok(proto::GetUsersResponse { users })
796 }
797
798 fn update_contacts_for_users<'a>(
799 self: &Arc<Server>,
800 user_ids: impl IntoIterator<Item = &'a UserId>,
801 ) -> anyhow::Result<()> {
802 let mut result = Ok(());
803 let state = self.state();
804 for user_id in user_ids {
805 let contacts = state.contacts_for_user(*user_id);
806 for connection_id in state.connection_ids_for_user(*user_id) {
807 if let Err(error) = self.peer.send(
808 connection_id,
809 proto::UpdateContacts {
810 contacts: contacts.clone(),
811 },
812 ) {
813 result = Err(error);
814 }
815 }
816 }
817 result
818 }
819
820 async fn join_channel(
821 mut self: Arc<Self>,
822 request: TypedEnvelope<proto::JoinChannel>,
823 ) -> tide::Result<proto::JoinChannelResponse> {
824 let user_id = self.state().user_id_for_connection(request.sender_id)?;
825 let channel_id = ChannelId::from_proto(request.payload.channel_id);
826 if !self
827 .app_state
828 .db
829 .can_user_access_channel(user_id, channel_id)
830 .await?
831 {
832 Err(anyhow!("access denied"))?;
833 }
834
835 self.state_mut().join_channel(request.sender_id, channel_id);
836 let messages = self
837 .app_state
838 .db
839 .get_channel_messages(channel_id, MESSAGE_COUNT_PER_PAGE, None)
840 .await?
841 .into_iter()
842 .map(|msg| proto::ChannelMessage {
843 id: msg.id.to_proto(),
844 body: msg.body,
845 timestamp: msg.sent_at.unix_timestamp() as u64,
846 sender_id: msg.sender_id.to_proto(),
847 nonce: Some(msg.nonce.as_u128().into()),
848 })
849 .collect::<Vec<_>>();
850 Ok(proto::JoinChannelResponse {
851 done: messages.len() < MESSAGE_COUNT_PER_PAGE,
852 messages,
853 })
854 }
855
856 async fn leave_channel(
857 mut self: Arc<Self>,
858 request: TypedEnvelope<proto::LeaveChannel>,
859 ) -> tide::Result<()> {
860 let user_id = self.state().user_id_for_connection(request.sender_id)?;
861 let channel_id = ChannelId::from_proto(request.payload.channel_id);
862 if !self
863 .app_state
864 .db
865 .can_user_access_channel(user_id, channel_id)
866 .await?
867 {
868 Err(anyhow!("access denied"))?;
869 }
870
871 self.state_mut()
872 .leave_channel(request.sender_id, channel_id);
873
874 Ok(())
875 }
876
877 async fn send_channel_message(
878 self: Arc<Self>,
879 request: TypedEnvelope<proto::SendChannelMessage>,
880 ) -> tide::Result<proto::SendChannelMessageResponse> {
881 let channel_id = ChannelId::from_proto(request.payload.channel_id);
882 let user_id;
883 let connection_ids;
884 {
885 let state = self.state();
886 user_id = state.user_id_for_connection(request.sender_id)?;
887 connection_ids = state.channel_connection_ids(channel_id)?;
888 }
889
890 // Validate the message body.
891 let body = request.payload.body.trim().to_string();
892 if body.len() > MAX_MESSAGE_LEN {
893 return Err(anyhow!("message is too long"))?;
894 }
895 if body.is_empty() {
896 return Err(anyhow!("message can't be blank"))?;
897 }
898
899 let timestamp = OffsetDateTime::now_utc();
900 let nonce = request
901 .payload
902 .nonce
903 .ok_or_else(|| anyhow!("nonce can't be blank"))?;
904
905 let message_id = self
906 .app_state
907 .db
908 .create_channel_message(channel_id, user_id, &body, timestamp, nonce.clone().into())
909 .await?
910 .to_proto();
911 let message = proto::ChannelMessage {
912 sender_id: user_id.to_proto(),
913 id: message_id,
914 body,
915 timestamp: timestamp.unix_timestamp() as u64,
916 nonce: Some(nonce),
917 };
918 broadcast(request.sender_id, connection_ids, |conn_id| {
919 self.peer.send(
920 conn_id,
921 proto::ChannelMessageSent {
922 channel_id: channel_id.to_proto(),
923 message: Some(message.clone()),
924 },
925 )
926 })?;
927 Ok(proto::SendChannelMessageResponse {
928 message: Some(message),
929 })
930 }
931
932 async fn get_channel_messages(
933 self: Arc<Self>,
934 request: TypedEnvelope<proto::GetChannelMessages>,
935 ) -> tide::Result<proto::GetChannelMessagesResponse> {
936 let user_id = self.state().user_id_for_connection(request.sender_id)?;
937 let channel_id = ChannelId::from_proto(request.payload.channel_id);
938 if !self
939 .app_state
940 .db
941 .can_user_access_channel(user_id, channel_id)
942 .await?
943 {
944 Err(anyhow!("access denied"))?;
945 }
946
947 let messages = self
948 .app_state
949 .db
950 .get_channel_messages(
951 channel_id,
952 MESSAGE_COUNT_PER_PAGE,
953 Some(MessageId::from_proto(request.payload.before_message_id)),
954 )
955 .await?
956 .into_iter()
957 .map(|msg| proto::ChannelMessage {
958 id: msg.id.to_proto(),
959 body: msg.body,
960 timestamp: msg.sent_at.unix_timestamp() as u64,
961 sender_id: msg.sender_id.to_proto(),
962 nonce: Some(msg.nonce.as_u128().into()),
963 })
964 .collect::<Vec<_>>();
965
966 Ok(proto::GetChannelMessagesResponse {
967 done: messages.len() < MESSAGE_COUNT_PER_PAGE,
968 messages,
969 })
970 }
971
972 fn state<'a>(self: &'a Arc<Self>) -> RwLockReadGuard<'a, Store> {
973 self.store.read()
974 }
975
976 fn state_mut<'a>(self: &'a mut Arc<Self>) -> RwLockWriteGuard<'a, Store> {
977 self.store.write()
978 }
979}
980
981impl Executor for RealExecutor {
982 fn spawn_detached<F: 'static + Send + Future<Output = ()>>(&self, future: F) {
983 task::spawn(future);
984 }
985}
986
987fn broadcast<F>(
988 sender_id: ConnectionId,
989 receiver_ids: Vec<ConnectionId>,
990 mut f: F,
991) -> anyhow::Result<()>
992where
993 F: FnMut(ConnectionId) -> anyhow::Result<()>,
994{
995 let mut result = Ok(());
996 for receiver_id in receiver_ids {
997 if receiver_id != sender_id {
998 if let Err(error) = f(receiver_id) {
999 if result.is_ok() {
1000 result = Err(error);
1001 }
1002 }
1003 }
1004 }
1005 result
1006}
1007
1008pub fn add_routes(app: &mut tide::Server<Arc<AppState>>, rpc: &Arc<Peer>) {
1009 let server = Server::new(app.state().clone(), rpc.clone(), None);
1010 app.at("/rpc").get(move |request: Request<Arc<AppState>>| {
1011 let server = server.clone();
1012 async move {
1013 const WEBSOCKET_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
1014
1015 let connection_upgrade = header_contains_ignore_case(&request, CONNECTION, "upgrade");
1016 let upgrade_to_websocket = header_contains_ignore_case(&request, UPGRADE, "websocket");
1017 let upgrade_requested = connection_upgrade && upgrade_to_websocket;
1018 let client_protocol_version: Option<u32> = request
1019 .header("X-Zed-Protocol-Version")
1020 .and_then(|v| v.as_str().parse().ok());
1021
1022 if !upgrade_requested || client_protocol_version != Some(rpc::PROTOCOL_VERSION) {
1023 return Ok(Response::new(StatusCode::UpgradeRequired));
1024 }
1025
1026 let header = match request.header("Sec-Websocket-Key") {
1027 Some(h) => h.as_str(),
1028 None => return Err(anyhow!("expected sec-websocket-key"))?,
1029 };
1030
1031 let user_id = process_auth_header(&request).await?;
1032
1033 let mut response = Response::new(StatusCode::SwitchingProtocols);
1034 response.insert_header(UPGRADE, "websocket");
1035 response.insert_header(CONNECTION, "Upgrade");
1036 let hash = Sha1::new().chain(header).chain(WEBSOCKET_GUID).finalize();
1037 response.insert_header("Sec-Websocket-Accept", base64::encode(&hash[..]));
1038 response.insert_header("Sec-Websocket-Version", "13");
1039
1040 let http_res: &mut tide::http::Response = response.as_mut();
1041 let upgrade_receiver = http_res.recv_upgrade().await;
1042 let addr = request.remote().unwrap_or("unknown").to_string();
1043 task::spawn(async move {
1044 if let Some(stream) = upgrade_receiver.await {
1045 server
1046 .handle_connection(
1047 Connection::new(
1048 WebSocketStream::from_raw_socket(stream, Role::Server, None).await,
1049 ),
1050 addr,
1051 user_id,
1052 None,
1053 RealExecutor,
1054 )
1055 .await;
1056 }
1057 });
1058
1059 Ok(response)
1060 }
1061 });
1062}
1063
1064fn header_contains_ignore_case<T>(
1065 request: &tide::Request<T>,
1066 header_name: HeaderName,
1067 value: &str,
1068) -> bool {
1069 request
1070 .header(header_name)
1071 .map(|h| {
1072 h.as_str()
1073 .split(',')
1074 .any(|s| s.trim().eq_ignore_ascii_case(value.trim()))
1075 })
1076 .unwrap_or(false)
1077}
1078
1079#[cfg(test)]
1080mod tests {
1081 use super::*;
1082 use crate::{
1083 auth,
1084 db::{tests::TestDb, UserId},
1085 github, AppState, Config,
1086 };
1087 use ::rpc::Peer;
1088 use gpui::{executor, ModelHandle, TestAppContext};
1089 use parking_lot::Mutex;
1090 use postage::{mpsc, watch};
1091 use rand::prelude::*;
1092 use rpc::PeerId;
1093 use serde_json::json;
1094 use sqlx::types::time::OffsetDateTime;
1095 use std::{
1096 ops::Deref,
1097 path::Path,
1098 rc::Rc,
1099 sync::{
1100 atomic::{AtomicBool, Ordering::SeqCst},
1101 Arc,
1102 },
1103 time::Duration,
1104 };
1105 use zed::{
1106 client::{
1107 self, test::FakeHttpClient, Channel, ChannelDetails, ChannelList, Client, Credentials,
1108 EstablishConnectionError, UserStore,
1109 },
1110 editor::{
1111 self, ConfirmCodeAction, ConfirmCompletion, Editor, EditorSettings, Input, MultiBuffer,
1112 Redo, ToggleCodeActions, Undo,
1113 },
1114 fs::{FakeFs, Fs as _},
1115 language::{
1116 tree_sitter_rust, AnchorRangeExt, Diagnostic, DiagnosticEntry, Language,
1117 LanguageConfig, LanguageRegistry, LanguageServerConfig, Point,
1118 },
1119 lsp,
1120 project::{DiagnosticSummary, Project, ProjectPath},
1121 workspace::{Workspace, WorkspaceParams},
1122 };
1123
1124 #[cfg(test)]
1125 #[ctor::ctor]
1126 fn init_logger() {
1127 if std::env::var("RUST_LOG").is_ok() {
1128 env_logger::init();
1129 }
1130 }
1131
1132 #[gpui::test(iterations = 10)]
1133 async fn test_share_project(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1134 let (window_b, _) = cx_b.add_window(|_| EmptyView);
1135 let lang_registry = Arc::new(LanguageRegistry::new());
1136 let fs = Arc::new(FakeFs::new(cx_a.background()));
1137 cx_a.foreground().forbid_parking();
1138
1139 // Connect to a server as 2 clients.
1140 let mut server = TestServer::start(cx_a.foreground()).await;
1141 let client_a = server.create_client(&mut cx_a, "user_a").await;
1142 let client_b = server.create_client(&mut cx_b, "user_b").await;
1143
1144 // Share a project as client A
1145 fs.insert_tree(
1146 "/a",
1147 json!({
1148 ".zed.toml": r#"collaborators = ["user_b"]"#,
1149 "a.txt": "a-contents",
1150 "b.txt": "b-contents",
1151 }),
1152 )
1153 .await;
1154 let project_a = cx_a.update(|cx| {
1155 Project::local(
1156 client_a.clone(),
1157 client_a.user_store.clone(),
1158 lang_registry.clone(),
1159 fs.clone(),
1160 cx,
1161 )
1162 });
1163 let (worktree_a, _) = project_a
1164 .update(&mut cx_a, |p, cx| {
1165 p.find_or_create_local_worktree("/a", false, cx)
1166 })
1167 .await
1168 .unwrap();
1169 let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1170 worktree_a
1171 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1172 .await;
1173 let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1174 project_a
1175 .update(&mut cx_a, |p, cx| p.share(cx))
1176 .await
1177 .unwrap();
1178
1179 // Join that project as client B
1180 let project_b = Project::remote(
1181 project_id,
1182 client_b.clone(),
1183 client_b.user_store.clone(),
1184 lang_registry.clone(),
1185 fs.clone(),
1186 &mut cx_b.to_async(),
1187 )
1188 .await
1189 .unwrap();
1190
1191 let replica_id_b = project_b.read_with(&cx_b, |project, _| {
1192 assert_eq!(
1193 project
1194 .collaborators()
1195 .get(&client_a.peer_id)
1196 .unwrap()
1197 .user
1198 .github_login,
1199 "user_a"
1200 );
1201 project.replica_id()
1202 });
1203 project_a
1204 .condition(&cx_a, |tree, _| {
1205 tree.collaborators()
1206 .get(&client_b.peer_id)
1207 .map_or(false, |collaborator| {
1208 collaborator.replica_id == replica_id_b
1209 && collaborator.user.github_login == "user_b"
1210 })
1211 })
1212 .await;
1213
1214 // Open the same file as client B and client A.
1215 let buffer_b = project_b
1216 .update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "b.txt"), cx))
1217 .await
1218 .unwrap();
1219 let buffer_b = cx_b.add_model(|cx| MultiBuffer::singleton(buffer_b, cx));
1220 buffer_b.read_with(&cx_b, |buf, cx| {
1221 assert_eq!(buf.read(cx).text(), "b-contents")
1222 });
1223 project_a.read_with(&cx_a, |project, cx| {
1224 assert!(project.has_open_buffer((worktree_id, "b.txt"), cx))
1225 });
1226 let buffer_a = project_a
1227 .update(&mut cx_a, |p, cx| p.open_buffer((worktree_id, "b.txt"), cx))
1228 .await
1229 .unwrap();
1230
1231 let editor_b = cx_b.add_view(window_b, |cx| {
1232 Editor::for_buffer(buffer_b, Arc::new(|cx| EditorSettings::test(cx)), None, cx)
1233 });
1234
1235 // TODO
1236 // // Create a selection set as client B and see that selection set as client A.
1237 // buffer_a
1238 // .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 1)
1239 // .await;
1240
1241 // Edit the buffer as client B and see that edit as client A.
1242 editor_b.update(&mut cx_b, |editor, cx| {
1243 editor.handle_input(&Input("ok, ".into()), cx)
1244 });
1245 buffer_a
1246 .condition(&cx_a, |buffer, _| buffer.text() == "ok, b-contents")
1247 .await;
1248
1249 // TODO
1250 // // Remove the selection set as client B, see those selections disappear as client A.
1251 cx_b.update(move |_| drop(editor_b));
1252 // buffer_a
1253 // .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 0)
1254 // .await;
1255
1256 // Close the buffer as client A, see that the buffer is closed.
1257 cx_a.update(move |_| drop(buffer_a));
1258 project_a
1259 .condition(&cx_a, |project, cx| {
1260 !project.has_open_buffer((worktree_id, "b.txt"), cx)
1261 })
1262 .await;
1263
1264 // Dropping the client B's project removes client B from client A's collaborators.
1265 cx_b.update(move |_| drop(project_b));
1266 project_a
1267 .condition(&cx_a, |project, _| project.collaborators().is_empty())
1268 .await;
1269 }
1270
1271 #[gpui::test(iterations = 10)]
1272 async fn test_unshare_project(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1273 let lang_registry = Arc::new(LanguageRegistry::new());
1274 let fs = Arc::new(FakeFs::new(cx_a.background()));
1275 cx_a.foreground().forbid_parking();
1276
1277 // Connect to a server as 2 clients.
1278 let mut server = TestServer::start(cx_a.foreground()).await;
1279 let client_a = server.create_client(&mut cx_a, "user_a").await;
1280 let client_b = server.create_client(&mut cx_b, "user_b").await;
1281
1282 // Share a project as client A
1283 fs.insert_tree(
1284 "/a",
1285 json!({
1286 ".zed.toml": r#"collaborators = ["user_b"]"#,
1287 "a.txt": "a-contents",
1288 "b.txt": "b-contents",
1289 }),
1290 )
1291 .await;
1292 let project_a = cx_a.update(|cx| {
1293 Project::local(
1294 client_a.clone(),
1295 client_a.user_store.clone(),
1296 lang_registry.clone(),
1297 fs.clone(),
1298 cx,
1299 )
1300 });
1301 let (worktree_a, _) = project_a
1302 .update(&mut cx_a, |p, cx| {
1303 p.find_or_create_local_worktree("/a", false, cx)
1304 })
1305 .await
1306 .unwrap();
1307 worktree_a
1308 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1309 .await;
1310 let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1311 let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1312 project_a
1313 .update(&mut cx_a, |p, cx| p.share(cx))
1314 .await
1315 .unwrap();
1316 assert!(worktree_a.read_with(&cx_a, |tree, _| tree.as_local().unwrap().is_shared()));
1317
1318 // Join that project as client B
1319 let project_b = Project::remote(
1320 project_id,
1321 client_b.clone(),
1322 client_b.user_store.clone(),
1323 lang_registry.clone(),
1324 fs.clone(),
1325 &mut cx_b.to_async(),
1326 )
1327 .await
1328 .unwrap();
1329 project_b
1330 .update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1331 .await
1332 .unwrap();
1333
1334 // Unshare the project as client A
1335 project_a
1336 .update(&mut cx_a, |project, cx| project.unshare(cx))
1337 .await
1338 .unwrap();
1339 project_b
1340 .condition(&mut cx_b, |project, _| project.is_read_only())
1341 .await;
1342 assert!(worktree_a.read_with(&cx_a, |tree, _| !tree.as_local().unwrap().is_shared()));
1343 drop(project_b);
1344
1345 // Share the project again and ensure guests can still join.
1346 project_a
1347 .update(&mut cx_a, |project, cx| project.share(cx))
1348 .await
1349 .unwrap();
1350 assert!(worktree_a.read_with(&cx_a, |tree, _| tree.as_local().unwrap().is_shared()));
1351
1352 let project_c = Project::remote(
1353 project_id,
1354 client_b.clone(),
1355 client_b.user_store.clone(),
1356 lang_registry.clone(),
1357 fs.clone(),
1358 &mut cx_b.to_async(),
1359 )
1360 .await
1361 .unwrap();
1362 project_c
1363 .update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1364 .await
1365 .unwrap();
1366 }
1367
1368 #[gpui::test(iterations = 10)]
1369 async fn test_propagate_saves_and_fs_changes(
1370 mut cx_a: TestAppContext,
1371 mut cx_b: TestAppContext,
1372 mut cx_c: TestAppContext,
1373 ) {
1374 let lang_registry = Arc::new(LanguageRegistry::new());
1375 let fs = Arc::new(FakeFs::new(cx_a.background()));
1376 cx_a.foreground().forbid_parking();
1377
1378 // Connect to a server as 3 clients.
1379 let mut server = TestServer::start(cx_a.foreground()).await;
1380 let client_a = server.create_client(&mut cx_a, "user_a").await;
1381 let client_b = server.create_client(&mut cx_b, "user_b").await;
1382 let client_c = server.create_client(&mut cx_c, "user_c").await;
1383
1384 // Share a worktree as client A.
1385 fs.insert_tree(
1386 "/a",
1387 json!({
1388 ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
1389 "file1": "",
1390 "file2": ""
1391 }),
1392 )
1393 .await;
1394 let project_a = cx_a.update(|cx| {
1395 Project::local(
1396 client_a.clone(),
1397 client_a.user_store.clone(),
1398 lang_registry.clone(),
1399 fs.clone(),
1400 cx,
1401 )
1402 });
1403 let (worktree_a, _) = project_a
1404 .update(&mut cx_a, |p, cx| {
1405 p.find_or_create_local_worktree("/a", false, cx)
1406 })
1407 .await
1408 .unwrap();
1409 worktree_a
1410 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1411 .await;
1412 let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1413 let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1414 project_a
1415 .update(&mut cx_a, |p, cx| p.share(cx))
1416 .await
1417 .unwrap();
1418
1419 // Join that worktree as clients B and C.
1420 let project_b = Project::remote(
1421 project_id,
1422 client_b.clone(),
1423 client_b.user_store.clone(),
1424 lang_registry.clone(),
1425 fs.clone(),
1426 &mut cx_b.to_async(),
1427 )
1428 .await
1429 .unwrap();
1430 let project_c = Project::remote(
1431 project_id,
1432 client_c.clone(),
1433 client_c.user_store.clone(),
1434 lang_registry.clone(),
1435 fs.clone(),
1436 &mut cx_c.to_async(),
1437 )
1438 .await
1439 .unwrap();
1440 let worktree_b = project_b.read_with(&cx_b, |p, cx| p.worktrees(cx).next().unwrap());
1441 let worktree_c = project_c.read_with(&cx_c, |p, cx| p.worktrees(cx).next().unwrap());
1442
1443 // Open and edit a buffer as both guests B and C.
1444 let buffer_b = project_b
1445 .update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
1446 .await
1447 .unwrap();
1448 let buffer_c = project_c
1449 .update(&mut cx_c, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
1450 .await
1451 .unwrap();
1452 buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "i-am-b, ", cx));
1453 buffer_c.update(&mut cx_c, |buf, cx| buf.edit([0..0], "i-am-c, ", cx));
1454
1455 // Open and edit that buffer as the host.
1456 let buffer_a = project_a
1457 .update(&mut cx_a, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
1458 .await
1459 .unwrap();
1460
1461 buffer_a
1462 .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, ")
1463 .await;
1464 buffer_a.update(&mut cx_a, |buf, cx| {
1465 buf.edit([buf.len()..buf.len()], "i-am-a", cx)
1466 });
1467
1468 // Wait for edits to propagate
1469 buffer_a
1470 .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1471 .await;
1472 buffer_b
1473 .condition(&mut cx_b, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1474 .await;
1475 buffer_c
1476 .condition(&mut cx_c, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1477 .await;
1478
1479 // Edit the buffer as the host and concurrently save as guest B.
1480 let save_b = buffer_b.update(&mut cx_b, |buf, cx| buf.save(cx));
1481 buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "hi-a, ", cx));
1482 save_b.await.unwrap();
1483 assert_eq!(
1484 fs.load("/a/file1".as_ref()).await.unwrap(),
1485 "hi-a, i-am-c, i-am-b, i-am-a"
1486 );
1487 buffer_a.read_with(&cx_a, |buf, _| assert!(!buf.is_dirty()));
1488 buffer_b.read_with(&cx_b, |buf, _| assert!(!buf.is_dirty()));
1489 buffer_c.condition(&cx_c, |buf, _| !buf.is_dirty()).await;
1490
1491 // Make changes on host's file system, see those changes on guest worktrees.
1492 fs.rename(
1493 "/a/file1".as_ref(),
1494 "/a/file1-renamed".as_ref(),
1495 Default::default(),
1496 )
1497 .await
1498 .unwrap();
1499
1500 fs.rename("/a/file2".as_ref(), "/a/file3".as_ref(), Default::default())
1501 .await
1502 .unwrap();
1503 fs.insert_file(Path::new("/a/file4"), "4".into())
1504 .await
1505 .unwrap();
1506
1507 worktree_a
1508 .condition(&cx_a, |tree, _| {
1509 tree.paths()
1510 .map(|p| p.to_string_lossy())
1511 .collect::<Vec<_>>()
1512 == [".zed.toml", "file1-renamed", "file3", "file4"]
1513 })
1514 .await;
1515 worktree_b
1516 .condition(&cx_b, |tree, _| {
1517 tree.paths()
1518 .map(|p| p.to_string_lossy())
1519 .collect::<Vec<_>>()
1520 == [".zed.toml", "file1-renamed", "file3", "file4"]
1521 })
1522 .await;
1523 worktree_c
1524 .condition(&cx_c, |tree, _| {
1525 tree.paths()
1526 .map(|p| p.to_string_lossy())
1527 .collect::<Vec<_>>()
1528 == [".zed.toml", "file1-renamed", "file3", "file4"]
1529 })
1530 .await;
1531
1532 // Ensure buffer files are updated as well.
1533 buffer_a
1534 .condition(&cx_a, |buf, _| {
1535 buf.file().unwrap().path().to_str() == Some("file1-renamed")
1536 })
1537 .await;
1538 buffer_b
1539 .condition(&cx_b, |buf, _| {
1540 buf.file().unwrap().path().to_str() == Some("file1-renamed")
1541 })
1542 .await;
1543 buffer_c
1544 .condition(&cx_c, |buf, _| {
1545 buf.file().unwrap().path().to_str() == Some("file1-renamed")
1546 })
1547 .await;
1548 }
1549
1550 #[gpui::test(iterations = 10)]
1551 async fn test_buffer_conflict_after_save(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1552 cx_a.foreground().forbid_parking();
1553 let lang_registry = Arc::new(LanguageRegistry::new());
1554 let fs = Arc::new(FakeFs::new(cx_a.background()));
1555
1556 // Connect to a server as 2 clients.
1557 let mut server = TestServer::start(cx_a.foreground()).await;
1558 let client_a = server.create_client(&mut cx_a, "user_a").await;
1559 let client_b = server.create_client(&mut cx_b, "user_b").await;
1560
1561 // Share a project as client A
1562 fs.insert_tree(
1563 "/dir",
1564 json!({
1565 ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
1566 "a.txt": "a-contents",
1567 }),
1568 )
1569 .await;
1570
1571 let project_a = cx_a.update(|cx| {
1572 Project::local(
1573 client_a.clone(),
1574 client_a.user_store.clone(),
1575 lang_registry.clone(),
1576 fs.clone(),
1577 cx,
1578 )
1579 });
1580 let (worktree_a, _) = project_a
1581 .update(&mut cx_a, |p, cx| {
1582 p.find_or_create_local_worktree("/dir", false, cx)
1583 })
1584 .await
1585 .unwrap();
1586 worktree_a
1587 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1588 .await;
1589 let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1590 let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1591 project_a
1592 .update(&mut cx_a, |p, cx| p.share(cx))
1593 .await
1594 .unwrap();
1595
1596 // Join that project as client B
1597 let project_b = Project::remote(
1598 project_id,
1599 client_b.clone(),
1600 client_b.user_store.clone(),
1601 lang_registry.clone(),
1602 fs.clone(),
1603 &mut cx_b.to_async(),
1604 )
1605 .await
1606 .unwrap();
1607
1608 // Open a buffer as client B
1609 let buffer_b = project_b
1610 .update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1611 .await
1612 .unwrap();
1613
1614 buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "world ", cx));
1615 buffer_b.read_with(&cx_b, |buf, _| {
1616 assert!(buf.is_dirty());
1617 assert!(!buf.has_conflict());
1618 });
1619
1620 buffer_b
1621 .update(&mut cx_b, |buf, cx| buf.save(cx))
1622 .await
1623 .unwrap();
1624 buffer_b
1625 .condition(&cx_b, |buffer_b, _| !buffer_b.is_dirty())
1626 .await;
1627 buffer_b.read_with(&cx_b, |buf, _| {
1628 assert!(!buf.has_conflict());
1629 });
1630
1631 buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "hello ", cx));
1632 buffer_b.read_with(&cx_b, |buf, _| {
1633 assert!(buf.is_dirty());
1634 assert!(!buf.has_conflict());
1635 });
1636 }
1637
1638 #[gpui::test(iterations = 10)]
1639 async fn test_buffer_reloading(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1640 cx_a.foreground().forbid_parking();
1641 let lang_registry = Arc::new(LanguageRegistry::new());
1642 let fs = Arc::new(FakeFs::new(cx_a.background()));
1643
1644 // Connect to a server as 2 clients.
1645 let mut server = TestServer::start(cx_a.foreground()).await;
1646 let client_a = server.create_client(&mut cx_a, "user_a").await;
1647 let client_b = server.create_client(&mut cx_b, "user_b").await;
1648
1649 // Share a project as client A
1650 fs.insert_tree(
1651 "/dir",
1652 json!({
1653 ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
1654 "a.txt": "a-contents",
1655 }),
1656 )
1657 .await;
1658
1659 let project_a = cx_a.update(|cx| {
1660 Project::local(
1661 client_a.clone(),
1662 client_a.user_store.clone(),
1663 lang_registry.clone(),
1664 fs.clone(),
1665 cx,
1666 )
1667 });
1668 let (worktree_a, _) = project_a
1669 .update(&mut cx_a, |p, cx| {
1670 p.find_or_create_local_worktree("/dir", false, cx)
1671 })
1672 .await
1673 .unwrap();
1674 worktree_a
1675 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1676 .await;
1677 let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1678 let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1679 project_a
1680 .update(&mut cx_a, |p, cx| p.share(cx))
1681 .await
1682 .unwrap();
1683
1684 // Join that project as client B
1685 let project_b = Project::remote(
1686 project_id,
1687 client_b.clone(),
1688 client_b.user_store.clone(),
1689 lang_registry.clone(),
1690 fs.clone(),
1691 &mut cx_b.to_async(),
1692 )
1693 .await
1694 .unwrap();
1695 let _worktree_b = project_b.update(&mut cx_b, |p, cx| p.worktrees(cx).next().unwrap());
1696
1697 // Open a buffer as client B
1698 let buffer_b = project_b
1699 .update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1700 .await
1701 .unwrap();
1702 buffer_b.read_with(&cx_b, |buf, _| {
1703 assert!(!buf.is_dirty());
1704 assert!(!buf.has_conflict());
1705 });
1706
1707 fs.save(Path::new("/dir/a.txt"), &"new contents".into())
1708 .await
1709 .unwrap();
1710 buffer_b
1711 .condition(&cx_b, |buf, _| {
1712 buf.text() == "new contents" && !buf.is_dirty()
1713 })
1714 .await;
1715 buffer_b.read_with(&cx_b, |buf, _| {
1716 assert!(!buf.has_conflict());
1717 });
1718 }
1719
1720 #[gpui::test(iterations = 10)]
1721 async fn test_editing_while_guest_opens_buffer(
1722 mut cx_a: TestAppContext,
1723 mut cx_b: TestAppContext,
1724 ) {
1725 cx_a.foreground().forbid_parking();
1726 let lang_registry = Arc::new(LanguageRegistry::new());
1727 let fs = Arc::new(FakeFs::new(cx_a.background()));
1728
1729 // Connect to a server as 2 clients.
1730 let mut server = TestServer::start(cx_a.foreground()).await;
1731 let client_a = server.create_client(&mut cx_a, "user_a").await;
1732 let client_b = server.create_client(&mut cx_b, "user_b").await;
1733
1734 // Share a project as client A
1735 fs.insert_tree(
1736 "/dir",
1737 json!({
1738 ".zed.toml": r#"collaborators = ["user_b"]"#,
1739 "a.txt": "a-contents",
1740 }),
1741 )
1742 .await;
1743 let project_a = cx_a.update(|cx| {
1744 Project::local(
1745 client_a.clone(),
1746 client_a.user_store.clone(),
1747 lang_registry.clone(),
1748 fs.clone(),
1749 cx,
1750 )
1751 });
1752 let (worktree_a, _) = project_a
1753 .update(&mut cx_a, |p, cx| {
1754 p.find_or_create_local_worktree("/dir", false, cx)
1755 })
1756 .await
1757 .unwrap();
1758 worktree_a
1759 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1760 .await;
1761 let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1762 let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1763 project_a
1764 .update(&mut cx_a, |p, cx| p.share(cx))
1765 .await
1766 .unwrap();
1767
1768 // Join that project as client B
1769 let project_b = Project::remote(
1770 project_id,
1771 client_b.clone(),
1772 client_b.user_store.clone(),
1773 lang_registry.clone(),
1774 fs.clone(),
1775 &mut cx_b.to_async(),
1776 )
1777 .await
1778 .unwrap();
1779
1780 // Open a buffer as client A
1781 let buffer_a = project_a
1782 .update(&mut cx_a, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1783 .await
1784 .unwrap();
1785
1786 // Start opening the same buffer as client B
1787 let buffer_b = cx_b
1788 .background()
1789 .spawn(project_b.update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx)));
1790
1791 // Edit the buffer as client A while client B is still opening it.
1792 cx_b.background().simulate_random_delay().await;
1793 buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "X", cx));
1794 cx_b.background().simulate_random_delay().await;
1795 buffer_a.update(&mut cx_a, |buf, cx| buf.edit([1..1], "Y", cx));
1796
1797 let text = buffer_a.read_with(&cx_a, |buf, _| buf.text());
1798 let buffer_b = buffer_b.await.unwrap();
1799 buffer_b.condition(&cx_b, |buf, _| buf.text() == text).await;
1800 }
1801
1802 #[gpui::test(iterations = 10)]
1803 async fn test_leaving_worktree_while_opening_buffer(
1804 mut cx_a: TestAppContext,
1805 mut cx_b: TestAppContext,
1806 ) {
1807 cx_a.foreground().forbid_parking();
1808 let lang_registry = Arc::new(LanguageRegistry::new());
1809 let fs = Arc::new(FakeFs::new(cx_a.background()));
1810
1811 // Connect to a server as 2 clients.
1812 let mut server = TestServer::start(cx_a.foreground()).await;
1813 let client_a = server.create_client(&mut cx_a, "user_a").await;
1814 let client_b = server.create_client(&mut cx_b, "user_b").await;
1815
1816 // Share a project as client A
1817 fs.insert_tree(
1818 "/dir",
1819 json!({
1820 ".zed.toml": r#"collaborators = ["user_b"]"#,
1821 "a.txt": "a-contents",
1822 }),
1823 )
1824 .await;
1825 let project_a = cx_a.update(|cx| {
1826 Project::local(
1827 client_a.clone(),
1828 client_a.user_store.clone(),
1829 lang_registry.clone(),
1830 fs.clone(),
1831 cx,
1832 )
1833 });
1834 let (worktree_a, _) = project_a
1835 .update(&mut cx_a, |p, cx| {
1836 p.find_or_create_local_worktree("/dir", false, cx)
1837 })
1838 .await
1839 .unwrap();
1840 worktree_a
1841 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1842 .await;
1843 let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1844 let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1845 project_a
1846 .update(&mut cx_a, |p, cx| p.share(cx))
1847 .await
1848 .unwrap();
1849
1850 // Join that project as client B
1851 let project_b = Project::remote(
1852 project_id,
1853 client_b.clone(),
1854 client_b.user_store.clone(),
1855 lang_registry.clone(),
1856 fs.clone(),
1857 &mut cx_b.to_async(),
1858 )
1859 .await
1860 .unwrap();
1861
1862 // See that a guest has joined as client A.
1863 project_a
1864 .condition(&cx_a, |p, _| p.collaborators().len() == 1)
1865 .await;
1866
1867 // Begin opening a buffer as client B, but leave the project before the open completes.
1868 let buffer_b = cx_b
1869 .background()
1870 .spawn(project_b.update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx)));
1871 cx_b.update(|_| drop(project_b));
1872 drop(buffer_b);
1873
1874 // See that the guest has left.
1875 project_a
1876 .condition(&cx_a, |p, _| p.collaborators().len() == 0)
1877 .await;
1878 }
1879
1880 #[gpui::test(iterations = 10)]
1881 async fn test_peer_disconnection(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1882 cx_a.foreground().forbid_parking();
1883 let lang_registry = Arc::new(LanguageRegistry::new());
1884 let fs = Arc::new(FakeFs::new(cx_a.background()));
1885
1886 // Connect to a server as 2 clients.
1887 let mut server = TestServer::start(cx_a.foreground()).await;
1888 let client_a = server.create_client(&mut cx_a, "user_a").await;
1889 let client_b = server.create_client(&mut cx_b, "user_b").await;
1890
1891 // Share a project as client A
1892 fs.insert_tree(
1893 "/a",
1894 json!({
1895 ".zed.toml": r#"collaborators = ["user_b"]"#,
1896 "a.txt": "a-contents",
1897 "b.txt": "b-contents",
1898 }),
1899 )
1900 .await;
1901 let project_a = cx_a.update(|cx| {
1902 Project::local(
1903 client_a.clone(),
1904 client_a.user_store.clone(),
1905 lang_registry.clone(),
1906 fs.clone(),
1907 cx,
1908 )
1909 });
1910 let (worktree_a, _) = project_a
1911 .update(&mut cx_a, |p, cx| {
1912 p.find_or_create_local_worktree("/a", false, cx)
1913 })
1914 .await
1915 .unwrap();
1916 worktree_a
1917 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1918 .await;
1919 let project_id = project_a
1920 .update(&mut cx_a, |project, _| project.next_remote_id())
1921 .await;
1922 project_a
1923 .update(&mut cx_a, |project, cx| project.share(cx))
1924 .await
1925 .unwrap();
1926
1927 // Join that project as client B
1928 let _project_b = Project::remote(
1929 project_id,
1930 client_b.clone(),
1931 client_b.user_store.clone(),
1932 lang_registry.clone(),
1933 fs.clone(),
1934 &mut cx_b.to_async(),
1935 )
1936 .await
1937 .unwrap();
1938
1939 // See that a guest has joined as client A.
1940 project_a
1941 .condition(&cx_a, |p, _| p.collaborators().len() == 1)
1942 .await;
1943
1944 // Drop client B's connection and ensure client A observes client B leaving the worktree.
1945 client_b.disconnect(&cx_b.to_async()).unwrap();
1946 project_a
1947 .condition(&cx_a, |p, _| p.collaborators().len() == 0)
1948 .await;
1949 }
1950
1951 #[gpui::test(iterations = 10)]
1952 async fn test_collaborating_with_diagnostics(
1953 mut cx_a: TestAppContext,
1954 mut cx_b: TestAppContext,
1955 ) {
1956 cx_a.foreground().forbid_parking();
1957 let mut lang_registry = Arc::new(LanguageRegistry::new());
1958 let fs = Arc::new(FakeFs::new(cx_a.background()));
1959
1960 // Set up a fake language server.
1961 let (language_server_config, mut fake_language_server) =
1962 LanguageServerConfig::fake(&cx_a).await;
1963 Arc::get_mut(&mut lang_registry)
1964 .unwrap()
1965 .add(Arc::new(Language::new(
1966 LanguageConfig {
1967 name: "Rust".to_string(),
1968 path_suffixes: vec!["rs".to_string()],
1969 language_server: Some(language_server_config),
1970 ..Default::default()
1971 },
1972 Some(tree_sitter_rust::language()),
1973 )));
1974
1975 // Connect to a server as 2 clients.
1976 let mut server = TestServer::start(cx_a.foreground()).await;
1977 let client_a = server.create_client(&mut cx_a, "user_a").await;
1978 let client_b = server.create_client(&mut cx_b, "user_b").await;
1979
1980 // Share a project as client A
1981 fs.insert_tree(
1982 "/a",
1983 json!({
1984 ".zed.toml": r#"collaborators = ["user_b"]"#,
1985 "a.rs": "let one = two",
1986 "other.rs": "",
1987 }),
1988 )
1989 .await;
1990 let project_a = cx_a.update(|cx| {
1991 Project::local(
1992 client_a.clone(),
1993 client_a.user_store.clone(),
1994 lang_registry.clone(),
1995 fs.clone(),
1996 cx,
1997 )
1998 });
1999 let (worktree_a, _) = project_a
2000 .update(&mut cx_a, |p, cx| {
2001 p.find_or_create_local_worktree("/a", false, cx)
2002 })
2003 .await
2004 .unwrap();
2005 worktree_a
2006 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2007 .await;
2008 let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
2009 let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
2010 project_a
2011 .update(&mut cx_a, |p, cx| p.share(cx))
2012 .await
2013 .unwrap();
2014
2015 // Cause the language server to start.
2016 let _ = cx_a
2017 .background()
2018 .spawn(project_a.update(&mut cx_a, |project, cx| {
2019 project.open_buffer(
2020 ProjectPath {
2021 worktree_id,
2022 path: Path::new("other.rs").into(),
2023 },
2024 cx,
2025 )
2026 }))
2027 .await
2028 .unwrap();
2029
2030 // Simulate a language server reporting errors for a file.
2031 fake_language_server
2032 .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
2033 uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
2034 version: None,
2035 diagnostics: vec![lsp::Diagnostic {
2036 severity: Some(lsp::DiagnosticSeverity::ERROR),
2037 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
2038 message: "message 1".to_string(),
2039 ..Default::default()
2040 }],
2041 })
2042 .await;
2043
2044 // Wait for server to see the diagnostics update.
2045 server
2046 .condition(|store| {
2047 let worktree = store
2048 .project(project_id)
2049 .unwrap()
2050 .worktrees
2051 .get(&worktree_id.to_proto())
2052 .unwrap();
2053
2054 !worktree
2055 .share
2056 .as_ref()
2057 .unwrap()
2058 .diagnostic_summaries
2059 .is_empty()
2060 })
2061 .await;
2062
2063 // Join the worktree as client B.
2064 let project_b = Project::remote(
2065 project_id,
2066 client_b.clone(),
2067 client_b.user_store.clone(),
2068 lang_registry.clone(),
2069 fs.clone(),
2070 &mut cx_b.to_async(),
2071 )
2072 .await
2073 .unwrap();
2074
2075 project_b.read_with(&cx_b, |project, cx| {
2076 assert_eq!(
2077 project.diagnostic_summaries(cx).collect::<Vec<_>>(),
2078 &[(
2079 ProjectPath {
2080 worktree_id,
2081 path: Arc::from(Path::new("a.rs")),
2082 },
2083 DiagnosticSummary {
2084 error_count: 1,
2085 warning_count: 0,
2086 ..Default::default()
2087 },
2088 )]
2089 )
2090 });
2091
2092 // Simulate a language server reporting more errors for a file.
2093 fake_language_server
2094 .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
2095 uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
2096 version: None,
2097 diagnostics: vec![
2098 lsp::Diagnostic {
2099 severity: Some(lsp::DiagnosticSeverity::ERROR),
2100 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
2101 message: "message 1".to_string(),
2102 ..Default::default()
2103 },
2104 lsp::Diagnostic {
2105 severity: Some(lsp::DiagnosticSeverity::WARNING),
2106 range: lsp::Range::new(
2107 lsp::Position::new(0, 10),
2108 lsp::Position::new(0, 13),
2109 ),
2110 message: "message 2".to_string(),
2111 ..Default::default()
2112 },
2113 ],
2114 })
2115 .await;
2116
2117 // Client b gets the updated summaries
2118 project_b
2119 .condition(&cx_b, |project, cx| {
2120 project.diagnostic_summaries(cx).collect::<Vec<_>>()
2121 == &[(
2122 ProjectPath {
2123 worktree_id,
2124 path: Arc::from(Path::new("a.rs")),
2125 },
2126 DiagnosticSummary {
2127 error_count: 1,
2128 warning_count: 1,
2129 ..Default::default()
2130 },
2131 )]
2132 })
2133 .await;
2134
2135 // Open the file with the errors on client B. They should be present.
2136 let buffer_b = cx_b
2137 .background()
2138 .spawn(project_b.update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
2139 .await
2140 .unwrap();
2141
2142 buffer_b.read_with(&cx_b, |buffer, _| {
2143 assert_eq!(
2144 buffer
2145 .snapshot()
2146 .diagnostics_in_range::<_, Point>(0..buffer.len())
2147 .map(|entry| entry)
2148 .collect::<Vec<_>>(),
2149 &[
2150 DiagnosticEntry {
2151 range: Point::new(0, 4)..Point::new(0, 7),
2152 diagnostic: Diagnostic {
2153 group_id: 0,
2154 message: "message 1".to_string(),
2155 severity: lsp::DiagnosticSeverity::ERROR,
2156 is_primary: true,
2157 ..Default::default()
2158 }
2159 },
2160 DiagnosticEntry {
2161 range: Point::new(0, 10)..Point::new(0, 13),
2162 diagnostic: Diagnostic {
2163 group_id: 1,
2164 severity: lsp::DiagnosticSeverity::WARNING,
2165 message: "message 2".to_string(),
2166 is_primary: true,
2167 ..Default::default()
2168 }
2169 }
2170 ]
2171 );
2172 });
2173 }
2174
2175 #[gpui::test(iterations = 10)]
2176 async fn test_collaborating_with_completion(
2177 mut cx_a: TestAppContext,
2178 mut cx_b: TestAppContext,
2179 ) {
2180 cx_a.foreground().forbid_parking();
2181 let mut lang_registry = Arc::new(LanguageRegistry::new());
2182 let fs = Arc::new(FakeFs::new(cx_a.background()));
2183
2184 // Set up a fake language server.
2185 let (language_server_config, mut fake_language_server) =
2186 LanguageServerConfig::fake_with_capabilities(
2187 lsp::ServerCapabilities {
2188 completion_provider: Some(lsp::CompletionOptions {
2189 trigger_characters: Some(vec![".".to_string()]),
2190 ..Default::default()
2191 }),
2192 ..Default::default()
2193 },
2194 &cx_a,
2195 )
2196 .await;
2197 Arc::get_mut(&mut lang_registry)
2198 .unwrap()
2199 .add(Arc::new(Language::new(
2200 LanguageConfig {
2201 name: "Rust".to_string(),
2202 path_suffixes: vec!["rs".to_string()],
2203 language_server: Some(language_server_config),
2204 ..Default::default()
2205 },
2206 Some(tree_sitter_rust::language()),
2207 )));
2208
2209 // Connect to a server as 2 clients.
2210 let mut server = TestServer::start(cx_a.foreground()).await;
2211 let client_a = server.create_client(&mut cx_a, "user_a").await;
2212 let client_b = server.create_client(&mut cx_b, "user_b").await;
2213
2214 // Share a project as client A
2215 fs.insert_tree(
2216 "/a",
2217 json!({
2218 ".zed.toml": r#"collaborators = ["user_b"]"#,
2219 "main.rs": "fn main() { a }",
2220 "other.rs": "",
2221 }),
2222 )
2223 .await;
2224 let project_a = cx_a.update(|cx| {
2225 Project::local(
2226 client_a.clone(),
2227 client_a.user_store.clone(),
2228 lang_registry.clone(),
2229 fs.clone(),
2230 cx,
2231 )
2232 });
2233 let (worktree_a, _) = project_a
2234 .update(&mut cx_a, |p, cx| {
2235 p.find_or_create_local_worktree("/a", false, cx)
2236 })
2237 .await
2238 .unwrap();
2239 worktree_a
2240 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2241 .await;
2242 let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
2243 let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
2244 project_a
2245 .update(&mut cx_a, |p, cx| p.share(cx))
2246 .await
2247 .unwrap();
2248
2249 // Join the worktree as client B.
2250 let project_b = Project::remote(
2251 project_id,
2252 client_b.clone(),
2253 client_b.user_store.clone(),
2254 lang_registry.clone(),
2255 fs.clone(),
2256 &mut cx_b.to_async(),
2257 )
2258 .await
2259 .unwrap();
2260
2261 // Open a file in an editor as the guest.
2262 let buffer_b = project_b
2263 .update(&mut cx_b, |p, cx| {
2264 p.open_buffer((worktree_id, "main.rs"), cx)
2265 })
2266 .await
2267 .unwrap();
2268 let (window_b, _) = cx_b.add_window(|_| EmptyView);
2269 let editor_b = cx_b.add_view(window_b, |cx| {
2270 Editor::for_buffer(
2271 cx.add_model(|cx| MultiBuffer::singleton(buffer_b.clone(), cx)),
2272 Arc::new(|cx| EditorSettings::test(cx)),
2273 Some(project_b.clone()),
2274 cx,
2275 )
2276 });
2277
2278 // Type a completion trigger character as the guest.
2279 editor_b.update(&mut cx_b, |editor, cx| {
2280 editor.select_ranges([13..13], None, cx);
2281 editor.handle_input(&Input(".".into()), cx);
2282 cx.focus(&editor_b);
2283 });
2284
2285 // Receive a completion request as the host's language server.
2286 // Return some completions from the host's language server.
2287 fake_language_server.handle_request::<lsp::request::Completion, _>(|params| {
2288 assert_eq!(
2289 params.text_document_position.text_document.uri,
2290 lsp::Url::from_file_path("/a/main.rs").unwrap(),
2291 );
2292 assert_eq!(
2293 params.text_document_position.position,
2294 lsp::Position::new(0, 14),
2295 );
2296
2297 Some(lsp::CompletionResponse::Array(vec![
2298 lsp::CompletionItem {
2299 label: "first_method(…)".into(),
2300 detail: Some("fn(&mut self, B) -> C".into()),
2301 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
2302 new_text: "first_method($1)".to_string(),
2303 range: lsp::Range::new(
2304 lsp::Position::new(0, 14),
2305 lsp::Position::new(0, 14),
2306 ),
2307 })),
2308 insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
2309 ..Default::default()
2310 },
2311 lsp::CompletionItem {
2312 label: "second_method(…)".into(),
2313 detail: Some("fn(&mut self, C) -> D<E>".into()),
2314 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
2315 new_text: "second_method()".to_string(),
2316 range: lsp::Range::new(
2317 lsp::Position::new(0, 14),
2318 lsp::Position::new(0, 14),
2319 ),
2320 })),
2321 insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
2322 ..Default::default()
2323 },
2324 ]))
2325 });
2326
2327 // Open the buffer on the host.
2328 let buffer_a = project_a
2329 .update(&mut cx_a, |p, cx| {
2330 p.open_buffer((worktree_id, "main.rs"), cx)
2331 })
2332 .await
2333 .unwrap();
2334 buffer_a
2335 .condition(&cx_a, |buffer, _| buffer.text() == "fn main() { a. }")
2336 .await;
2337
2338 // Confirm a completion on the guest.
2339 editor_b.next_notification(&cx_b).await;
2340 editor_b.update(&mut cx_b, |editor, cx| {
2341 assert!(editor.context_menu_visible());
2342 editor.confirm_completion(&ConfirmCompletion(Some(0)), cx);
2343 assert_eq!(editor.text(cx), "fn main() { a.first_method() }");
2344 });
2345
2346 // Return a resolved completion from the host's language server.
2347 // The resolved completion has an additional text edit.
2348 fake_language_server.handle_request::<lsp::request::ResolveCompletionItem, _>(|params| {
2349 assert_eq!(params.label, "first_method(…)");
2350 lsp::CompletionItem {
2351 label: "first_method(…)".into(),
2352 detail: Some("fn(&mut self, B) -> C".into()),
2353 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
2354 new_text: "first_method($1)".to_string(),
2355 range: lsp::Range::new(lsp::Position::new(0, 14), lsp::Position::new(0, 14)),
2356 })),
2357 additional_text_edits: Some(vec![lsp::TextEdit {
2358 new_text: "use d::SomeTrait;\n".to_string(),
2359 range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
2360 }]),
2361 insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
2362 ..Default::default()
2363 }
2364 });
2365
2366 buffer_a
2367 .condition(&cx_a, |buffer, _| {
2368 buffer.text() == "fn main() { a.first_method() }"
2369 })
2370 .await;
2371
2372 // The additional edit is applied.
2373 buffer_b
2374 .condition(&cx_b, |buffer, _| {
2375 buffer.text() == "use d::SomeTrait;\nfn main() { a.first_method() }"
2376 })
2377 .await;
2378 assert_eq!(
2379 buffer_a.read_with(&cx_a, |buffer, _| buffer.text()),
2380 buffer_b.read_with(&cx_b, |buffer, _| buffer.text()),
2381 );
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 struct TestServer {
3540 peer: Arc<Peer>,
3541 app_state: Arc<AppState>,
3542 server: Arc<Server>,
3543 foreground: Rc<executor::Foreground>,
3544 notifications: mpsc::Receiver<()>,
3545 connection_killers: Arc<Mutex<HashMap<UserId, watch::Sender<Option<()>>>>>,
3546 forbid_connections: Arc<AtomicBool>,
3547 _test_db: TestDb,
3548 }
3549
3550 impl TestServer {
3551 async fn start(foreground: Rc<executor::Foreground>) -> Self {
3552 let test_db = TestDb::new();
3553 let app_state = Self::build_app_state(&test_db).await;
3554 let peer = Peer::new();
3555 let notifications = mpsc::channel(128);
3556 let server = Server::new(app_state.clone(), peer.clone(), Some(notifications.0));
3557 Self {
3558 peer,
3559 app_state,
3560 server,
3561 foreground,
3562 notifications: notifications.1,
3563 connection_killers: Default::default(),
3564 forbid_connections: Default::default(),
3565 _test_db: test_db,
3566 }
3567 }
3568
3569 async fn create_client(&mut self, cx: &mut TestAppContext, name: &str) -> TestClient {
3570 let http = FakeHttpClient::with_404_response();
3571 let user_id = self.app_state.db.create_user(name, false).await.unwrap();
3572 let client_name = name.to_string();
3573 let mut client = Client::new(http.clone());
3574 let server = self.server.clone();
3575 let connection_killers = self.connection_killers.clone();
3576 let forbid_connections = self.forbid_connections.clone();
3577 let (connection_id_tx, mut connection_id_rx) = postage::mpsc::channel(16);
3578
3579 Arc::get_mut(&mut client)
3580 .unwrap()
3581 .override_authenticate(move |cx| {
3582 cx.spawn(|_| async move {
3583 let access_token = "the-token".to_string();
3584 Ok(Credentials {
3585 user_id: user_id.0 as u64,
3586 access_token,
3587 })
3588 })
3589 })
3590 .override_establish_connection(move |credentials, cx| {
3591 assert_eq!(credentials.user_id, user_id.0 as u64);
3592 assert_eq!(credentials.access_token, "the-token");
3593
3594 let server = server.clone();
3595 let connection_killers = connection_killers.clone();
3596 let forbid_connections = forbid_connections.clone();
3597 let client_name = client_name.clone();
3598 let connection_id_tx = connection_id_tx.clone();
3599 cx.spawn(move |cx| async move {
3600 if forbid_connections.load(SeqCst) {
3601 Err(EstablishConnectionError::other(anyhow!(
3602 "server is forbidding connections"
3603 )))
3604 } else {
3605 let (client_conn, server_conn, kill_conn) =
3606 Connection::in_memory(cx.background());
3607 connection_killers.lock().insert(user_id, kill_conn);
3608 cx.background()
3609 .spawn(server.handle_connection(
3610 server_conn,
3611 client_name,
3612 user_id,
3613 Some(connection_id_tx),
3614 cx.background(),
3615 ))
3616 .detach();
3617 Ok(client_conn)
3618 }
3619 })
3620 });
3621
3622 client
3623 .authenticate_and_connect(&cx.to_async())
3624 .await
3625 .unwrap();
3626
3627 let peer_id = PeerId(connection_id_rx.next().await.unwrap().0);
3628 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http, cx));
3629 let mut authed_user =
3630 user_store.read_with(cx, |user_store, _| user_store.watch_current_user());
3631 while authed_user.next().await.unwrap().is_none() {}
3632
3633 TestClient {
3634 client,
3635 peer_id,
3636 user_store,
3637 }
3638 }
3639
3640 fn disconnect_client(&self, user_id: UserId) {
3641 if let Some(mut kill_conn) = self.connection_killers.lock().remove(&user_id) {
3642 let _ = kill_conn.try_send(Some(()));
3643 }
3644 }
3645
3646 fn forbid_connections(&self) {
3647 self.forbid_connections.store(true, SeqCst);
3648 }
3649
3650 fn allow_connections(&self) {
3651 self.forbid_connections.store(false, SeqCst);
3652 }
3653
3654 async fn build_app_state(test_db: &TestDb) -> Arc<AppState> {
3655 let mut config = Config::default();
3656 config.session_secret = "a".repeat(32);
3657 config.database_url = test_db.url.clone();
3658 let github_client = github::AppClient::test();
3659 Arc::new(AppState {
3660 db: test_db.db().clone(),
3661 handlebars: Default::default(),
3662 auth_client: auth::build_client("", ""),
3663 repo_client: github::RepoClient::test(&github_client),
3664 github_client,
3665 config,
3666 })
3667 }
3668
3669 async fn state<'a>(&'a self) -> RwLockReadGuard<'a, Store> {
3670 self.server.store.read()
3671 }
3672
3673 async fn condition<F>(&mut self, mut predicate: F)
3674 where
3675 F: FnMut(&Store) -> bool,
3676 {
3677 async_std::future::timeout(Duration::from_millis(500), async {
3678 while !(predicate)(&*self.server.store.read()) {
3679 self.foreground.start_waiting();
3680 self.notifications.next().await;
3681 self.foreground.finish_waiting();
3682 }
3683 })
3684 .await
3685 .expect("condition timed out");
3686 }
3687 }
3688
3689 impl Drop for TestServer {
3690 fn drop(&mut self) {
3691 self.peer.reset();
3692 }
3693 }
3694
3695 struct TestClient {
3696 client: Arc<Client>,
3697 pub peer_id: PeerId,
3698 pub user_store: ModelHandle<UserStore>,
3699 }
3700
3701 impl Deref for TestClient {
3702 type Target = Arc<Client>;
3703
3704 fn deref(&self) -> &Self::Target {
3705 &self.client
3706 }
3707 }
3708
3709 impl TestClient {
3710 pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
3711 UserId::from_proto(
3712 self.user_store
3713 .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
3714 )
3715 }
3716 }
3717
3718 impl Executor for Arc<gpui::executor::Background> {
3719 fn spawn_detached<F: 'static + Send + Future<Output = ()>>(&self, future: F) {
3720 self.spawn(future).detach();
3721 }
3722 }
3723
3724 fn channel_messages(channel: &Channel) -> Vec<(String, String, bool)> {
3725 channel
3726 .messages()
3727 .cursor::<()>()
3728 .map(|m| {
3729 (
3730 m.sender.github_login.clone(),
3731 m.body.clone(),
3732 m.is_pending(),
3733 )
3734 })
3735 .collect()
3736 }
3737
3738 struct EmptyView;
3739
3740 impl gpui::Entity for EmptyView {
3741 type Event = ();
3742 }
3743
3744 impl gpui::View for EmptyView {
3745 fn ui_name() -> &'static str {
3746 "empty view"
3747 }
3748
3749 fn render(&mut self, _: &mut gpui::RenderContext<Self>) -> gpui::ElementBox {
3750 gpui::Element::boxed(gpui::elements::Empty)
3751 }
3752 }
3753}