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