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, ToOffset, 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 let rename = editor.pending_rename().unwrap();
3144 let buffer = editor.buffer().read(cx).snapshot(cx);
3145 assert_eq!(
3146 rename.range.start.to_offset(&buffer)..rename.range.end.to_offset(&buffer),
3147 6..9
3148 );
3149 rename.editor.update(cx, |rename_editor, cx| {
3150 rename_editor.buffer().update(cx, |rename_buffer, cx| {
3151 rename_buffer.edit([0..3], "THREE", cx);
3152 });
3153 });
3154 });
3155
3156 let confirm_rename = workspace_b.update(&mut cx_b, |workspace, cx| {
3157 Editor::confirm_rename(workspace, &ConfirmRename, cx).unwrap()
3158 });
3159 fake_language_server
3160 .handle_request::<lsp::request::Rename, _>(|params| {
3161 assert_eq!(
3162 params.text_document_position.text_document.uri.as_str(),
3163 "file:///dir/one.rs"
3164 );
3165 assert_eq!(
3166 params.text_document_position.position,
3167 lsp::Position::new(0, 6)
3168 );
3169 assert_eq!(params.new_name, "THREE");
3170 Some(lsp::WorkspaceEdit {
3171 changes: Some(
3172 [
3173 (
3174 lsp::Url::from_file_path("/dir/one.rs").unwrap(),
3175 vec![lsp::TextEdit::new(
3176 lsp::Range::new(
3177 lsp::Position::new(0, 6),
3178 lsp::Position::new(0, 9),
3179 ),
3180 "THREE".to_string(),
3181 )],
3182 ),
3183 (
3184 lsp::Url::from_file_path("/dir/two.rs").unwrap(),
3185 vec![
3186 lsp::TextEdit::new(
3187 lsp::Range::new(
3188 lsp::Position::new(0, 24),
3189 lsp::Position::new(0, 27),
3190 ),
3191 "THREE".to_string(),
3192 ),
3193 lsp::TextEdit::new(
3194 lsp::Range::new(
3195 lsp::Position::new(0, 35),
3196 lsp::Position::new(0, 38),
3197 ),
3198 "THREE".to_string(),
3199 ),
3200 ],
3201 ),
3202 ]
3203 .into_iter()
3204 .collect(),
3205 ),
3206 ..Default::default()
3207 })
3208 })
3209 .next()
3210 .await
3211 .unwrap();
3212 confirm_rename.await.unwrap();
3213
3214 let rename_editor = workspace_b.read_with(&cx_b, |workspace, cx| {
3215 workspace
3216 .active_item(cx)
3217 .unwrap()
3218 .downcast::<Editor>()
3219 .unwrap()
3220 });
3221 rename_editor.update(&mut cx_b, |editor, cx| {
3222 assert_eq!(
3223 editor.text(cx),
3224 "const TWO: usize = one::THREE + one::THREE;\nconst THREE: usize = 1;"
3225 );
3226 editor.undo(&Undo, cx);
3227 assert_eq!(
3228 editor.text(cx),
3229 "const TWO: usize = one::ONE + one::ONE;\nconst ONE: usize = 1;"
3230 );
3231 editor.redo(&Redo, cx);
3232 assert_eq!(
3233 editor.text(cx),
3234 "const TWO: usize = one::THREE + one::THREE;\nconst THREE: usize = 1;"
3235 );
3236 });
3237
3238 // Ensure temporary rename edits cannot be undone/redone.
3239 editor_b.update(&mut cx_b, |editor, cx| {
3240 editor.undo(&Undo, cx);
3241 assert_eq!(editor.text(cx), "const ONE: usize = 1;");
3242 editor.undo(&Undo, cx);
3243 assert_eq!(editor.text(cx), "const ONE: usize = 1;");
3244 editor.redo(&Redo, cx);
3245 assert_eq!(editor.text(cx), "const THREE: usize = 1;");
3246 })
3247 }
3248
3249 #[gpui::test(iterations = 10)]
3250 async fn test_basic_chat(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
3251 cx_a.foreground().forbid_parking();
3252
3253 // Connect to a server as 2 clients.
3254 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
3255 let client_a = server.create_client(&mut cx_a, "user_a").await;
3256 let client_b = server.create_client(&mut cx_b, "user_b").await;
3257
3258 // Create an org that includes these 2 users.
3259 let db = &server.app_state.db;
3260 let org_id = db.create_org("Test Org", "test-org").await.unwrap();
3261 db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
3262 .await
3263 .unwrap();
3264 db.add_org_member(org_id, client_b.current_user_id(&cx_b), false)
3265 .await
3266 .unwrap();
3267
3268 // Create a channel that includes all the users.
3269 let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
3270 db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
3271 .await
3272 .unwrap();
3273 db.add_channel_member(channel_id, client_b.current_user_id(&cx_b), false)
3274 .await
3275 .unwrap();
3276 db.create_channel_message(
3277 channel_id,
3278 client_b.current_user_id(&cx_b),
3279 "hello A, it's B.",
3280 OffsetDateTime::now_utc(),
3281 1,
3282 )
3283 .await
3284 .unwrap();
3285
3286 let channels_a = cx_a
3287 .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
3288 channels_a
3289 .condition(&mut cx_a, |list, _| list.available_channels().is_some())
3290 .await;
3291 channels_a.read_with(&cx_a, |list, _| {
3292 assert_eq!(
3293 list.available_channels().unwrap(),
3294 &[ChannelDetails {
3295 id: channel_id.to_proto(),
3296 name: "test-channel".to_string()
3297 }]
3298 )
3299 });
3300 let channel_a = channels_a.update(&mut cx_a, |this, cx| {
3301 this.get_channel(channel_id.to_proto(), cx).unwrap()
3302 });
3303 channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
3304 channel_a
3305 .condition(&cx_a, |channel, _| {
3306 channel_messages(channel)
3307 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
3308 })
3309 .await;
3310
3311 let channels_b = cx_b
3312 .add_model(|cx| ChannelList::new(client_b.user_store.clone(), client_b.clone(), cx));
3313 channels_b
3314 .condition(&mut cx_b, |list, _| list.available_channels().is_some())
3315 .await;
3316 channels_b.read_with(&cx_b, |list, _| {
3317 assert_eq!(
3318 list.available_channels().unwrap(),
3319 &[ChannelDetails {
3320 id: channel_id.to_proto(),
3321 name: "test-channel".to_string()
3322 }]
3323 )
3324 });
3325
3326 let channel_b = channels_b.update(&mut cx_b, |this, cx| {
3327 this.get_channel(channel_id.to_proto(), cx).unwrap()
3328 });
3329 channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
3330 channel_b
3331 .condition(&cx_b, |channel, _| {
3332 channel_messages(channel)
3333 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
3334 })
3335 .await;
3336
3337 channel_a
3338 .update(&mut cx_a, |channel, cx| {
3339 channel
3340 .send_message("oh, hi B.".to_string(), cx)
3341 .unwrap()
3342 .detach();
3343 let task = channel.send_message("sup".to_string(), cx).unwrap();
3344 assert_eq!(
3345 channel_messages(channel),
3346 &[
3347 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3348 ("user_a".to_string(), "oh, hi B.".to_string(), true),
3349 ("user_a".to_string(), "sup".to_string(), true)
3350 ]
3351 );
3352 task
3353 })
3354 .await
3355 .unwrap();
3356
3357 channel_b
3358 .condition(&cx_b, |channel, _| {
3359 channel_messages(channel)
3360 == [
3361 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3362 ("user_a".to_string(), "oh, hi B.".to_string(), false),
3363 ("user_a".to_string(), "sup".to_string(), false),
3364 ]
3365 })
3366 .await;
3367
3368 assert_eq!(
3369 server
3370 .state()
3371 .await
3372 .channel(channel_id)
3373 .unwrap()
3374 .connection_ids
3375 .len(),
3376 2
3377 );
3378 cx_b.update(|_| drop(channel_b));
3379 server
3380 .condition(|state| state.channel(channel_id).unwrap().connection_ids.len() == 1)
3381 .await;
3382
3383 cx_a.update(|_| drop(channel_a));
3384 server
3385 .condition(|state| state.channel(channel_id).is_none())
3386 .await;
3387 }
3388
3389 #[gpui::test(iterations = 10)]
3390 async fn test_chat_message_validation(mut cx_a: TestAppContext) {
3391 cx_a.foreground().forbid_parking();
3392
3393 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
3394 let client_a = server.create_client(&mut cx_a, "user_a").await;
3395
3396 let db = &server.app_state.db;
3397 let org_id = db.create_org("Test Org", "test-org").await.unwrap();
3398 let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
3399 db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
3400 .await
3401 .unwrap();
3402 db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
3403 .await
3404 .unwrap();
3405
3406 let channels_a = cx_a
3407 .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
3408 channels_a
3409 .condition(&mut cx_a, |list, _| list.available_channels().is_some())
3410 .await;
3411 let channel_a = channels_a.update(&mut cx_a, |this, cx| {
3412 this.get_channel(channel_id.to_proto(), cx).unwrap()
3413 });
3414
3415 // Messages aren't allowed to be too long.
3416 channel_a
3417 .update(&mut cx_a, |channel, cx| {
3418 let long_body = "this is long.\n".repeat(1024);
3419 channel.send_message(long_body, cx).unwrap()
3420 })
3421 .await
3422 .unwrap_err();
3423
3424 // Messages aren't allowed to be blank.
3425 channel_a.update(&mut cx_a, |channel, cx| {
3426 channel.send_message(String::new(), cx).unwrap_err()
3427 });
3428
3429 // Leading and trailing whitespace are trimmed.
3430 channel_a
3431 .update(&mut cx_a, |channel, cx| {
3432 channel
3433 .send_message("\n surrounded by whitespace \n".to_string(), cx)
3434 .unwrap()
3435 })
3436 .await
3437 .unwrap();
3438 assert_eq!(
3439 db.get_channel_messages(channel_id, 10, None)
3440 .await
3441 .unwrap()
3442 .iter()
3443 .map(|m| &m.body)
3444 .collect::<Vec<_>>(),
3445 &["surrounded by whitespace"]
3446 );
3447 }
3448
3449 #[gpui::test(iterations = 10)]
3450 async fn test_chat_reconnection(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
3451 cx_a.foreground().forbid_parking();
3452
3453 // Connect to a server as 2 clients.
3454 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
3455 let client_a = server.create_client(&mut cx_a, "user_a").await;
3456 let client_b = server.create_client(&mut cx_b, "user_b").await;
3457 let mut status_b = client_b.status();
3458
3459 // Create an org that includes these 2 users.
3460 let db = &server.app_state.db;
3461 let org_id = db.create_org("Test Org", "test-org").await.unwrap();
3462 db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
3463 .await
3464 .unwrap();
3465 db.add_org_member(org_id, client_b.current_user_id(&cx_b), false)
3466 .await
3467 .unwrap();
3468
3469 // Create a channel that includes all the users.
3470 let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
3471 db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
3472 .await
3473 .unwrap();
3474 db.add_channel_member(channel_id, client_b.current_user_id(&cx_b), false)
3475 .await
3476 .unwrap();
3477 db.create_channel_message(
3478 channel_id,
3479 client_b.current_user_id(&cx_b),
3480 "hello A, it's B.",
3481 OffsetDateTime::now_utc(),
3482 2,
3483 )
3484 .await
3485 .unwrap();
3486
3487 let channels_a = cx_a
3488 .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
3489 channels_a
3490 .condition(&mut cx_a, |list, _| list.available_channels().is_some())
3491 .await;
3492
3493 channels_a.read_with(&cx_a, |list, _| {
3494 assert_eq!(
3495 list.available_channels().unwrap(),
3496 &[ChannelDetails {
3497 id: channel_id.to_proto(),
3498 name: "test-channel".to_string()
3499 }]
3500 )
3501 });
3502 let channel_a = channels_a.update(&mut cx_a, |this, cx| {
3503 this.get_channel(channel_id.to_proto(), cx).unwrap()
3504 });
3505 channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
3506 channel_a
3507 .condition(&cx_a, |channel, _| {
3508 channel_messages(channel)
3509 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
3510 })
3511 .await;
3512
3513 let channels_b = cx_b
3514 .add_model(|cx| ChannelList::new(client_b.user_store.clone(), client_b.clone(), cx));
3515 channels_b
3516 .condition(&mut cx_b, |list, _| list.available_channels().is_some())
3517 .await;
3518 channels_b.read_with(&cx_b, |list, _| {
3519 assert_eq!(
3520 list.available_channels().unwrap(),
3521 &[ChannelDetails {
3522 id: channel_id.to_proto(),
3523 name: "test-channel".to_string()
3524 }]
3525 )
3526 });
3527
3528 let channel_b = channels_b.update(&mut cx_b, |this, cx| {
3529 this.get_channel(channel_id.to_proto(), cx).unwrap()
3530 });
3531 channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
3532 channel_b
3533 .condition(&cx_b, |channel, _| {
3534 channel_messages(channel)
3535 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
3536 })
3537 .await;
3538
3539 // Disconnect client B, ensuring we can still access its cached channel data.
3540 server.forbid_connections();
3541 server.disconnect_client(client_b.current_user_id(&cx_b));
3542 while !matches!(
3543 status_b.next().await,
3544 Some(client::Status::ReconnectionError { .. })
3545 ) {}
3546
3547 channels_b.read_with(&cx_b, |channels, _| {
3548 assert_eq!(
3549 channels.available_channels().unwrap(),
3550 [ChannelDetails {
3551 id: channel_id.to_proto(),
3552 name: "test-channel".to_string()
3553 }]
3554 )
3555 });
3556 channel_b.read_with(&cx_b, |channel, _| {
3557 assert_eq!(
3558 channel_messages(channel),
3559 [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
3560 )
3561 });
3562
3563 // Send a message from client B while it is disconnected.
3564 channel_b
3565 .update(&mut cx_b, |channel, cx| {
3566 let task = channel
3567 .send_message("can you see this?".to_string(), cx)
3568 .unwrap();
3569 assert_eq!(
3570 channel_messages(channel),
3571 &[
3572 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3573 ("user_b".to_string(), "can you see this?".to_string(), true)
3574 ]
3575 );
3576 task
3577 })
3578 .await
3579 .unwrap_err();
3580
3581 // Send a message from client A while B is disconnected.
3582 channel_a
3583 .update(&mut cx_a, |channel, cx| {
3584 channel
3585 .send_message("oh, hi B.".to_string(), cx)
3586 .unwrap()
3587 .detach();
3588 let task = channel.send_message("sup".to_string(), cx).unwrap();
3589 assert_eq!(
3590 channel_messages(channel),
3591 &[
3592 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3593 ("user_a".to_string(), "oh, hi B.".to_string(), true),
3594 ("user_a".to_string(), "sup".to_string(), true)
3595 ]
3596 );
3597 task
3598 })
3599 .await
3600 .unwrap();
3601
3602 // Give client B a chance to reconnect.
3603 server.allow_connections();
3604 cx_b.foreground().advance_clock(Duration::from_secs(10));
3605
3606 // Verify that B sees the new messages upon reconnection, as well as the message client B
3607 // sent while offline.
3608 channel_b
3609 .condition(&cx_b, |channel, _| {
3610 channel_messages(channel)
3611 == [
3612 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3613 ("user_a".to_string(), "oh, hi B.".to_string(), false),
3614 ("user_a".to_string(), "sup".to_string(), false),
3615 ("user_b".to_string(), "can you see this?".to_string(), false),
3616 ]
3617 })
3618 .await;
3619
3620 // Ensure client A and B can communicate normally after reconnection.
3621 channel_a
3622 .update(&mut cx_a, |channel, cx| {
3623 channel.send_message("you online?".to_string(), cx).unwrap()
3624 })
3625 .await
3626 .unwrap();
3627 channel_b
3628 .condition(&cx_b, |channel, _| {
3629 channel_messages(channel)
3630 == [
3631 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3632 ("user_a".to_string(), "oh, hi B.".to_string(), false),
3633 ("user_a".to_string(), "sup".to_string(), false),
3634 ("user_b".to_string(), "can you see this?".to_string(), false),
3635 ("user_a".to_string(), "you online?".to_string(), false),
3636 ]
3637 })
3638 .await;
3639
3640 channel_b
3641 .update(&mut cx_b, |channel, cx| {
3642 channel.send_message("yep".to_string(), cx).unwrap()
3643 })
3644 .await
3645 .unwrap();
3646 channel_a
3647 .condition(&cx_a, |channel, _| {
3648 channel_messages(channel)
3649 == [
3650 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3651 ("user_a".to_string(), "oh, hi B.".to_string(), false),
3652 ("user_a".to_string(), "sup".to_string(), false),
3653 ("user_b".to_string(), "can you see this?".to_string(), false),
3654 ("user_a".to_string(), "you online?".to_string(), false),
3655 ("user_b".to_string(), "yep".to_string(), false),
3656 ]
3657 })
3658 .await;
3659 }
3660
3661 #[gpui::test(iterations = 10)]
3662 async fn test_contacts(
3663 mut cx_a: TestAppContext,
3664 mut cx_b: TestAppContext,
3665 mut cx_c: TestAppContext,
3666 ) {
3667 cx_a.foreground().forbid_parking();
3668 let lang_registry = Arc::new(LanguageRegistry::new());
3669 let fs = FakeFs::new(cx_a.background());
3670
3671 // Connect to a server as 3 clients.
3672 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
3673 let client_a = server.create_client(&mut cx_a, "user_a").await;
3674 let client_b = server.create_client(&mut cx_b, "user_b").await;
3675 let client_c = server.create_client(&mut cx_c, "user_c").await;
3676
3677 // Share a worktree as client A.
3678 fs.insert_tree(
3679 "/a",
3680 json!({
3681 ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
3682 }),
3683 )
3684 .await;
3685
3686 let project_a = cx_a.update(|cx| {
3687 Project::local(
3688 client_a.clone(),
3689 client_a.user_store.clone(),
3690 lang_registry.clone(),
3691 fs.clone(),
3692 cx,
3693 )
3694 });
3695 let (worktree_a, _) = project_a
3696 .update(&mut cx_a, |p, cx| {
3697 p.find_or_create_local_worktree("/a", false, cx)
3698 })
3699 .await
3700 .unwrap();
3701 worktree_a
3702 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
3703 .await;
3704
3705 client_a
3706 .user_store
3707 .condition(&cx_a, |user_store, _| {
3708 contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
3709 })
3710 .await;
3711 client_b
3712 .user_store
3713 .condition(&cx_b, |user_store, _| {
3714 contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
3715 })
3716 .await;
3717 client_c
3718 .user_store
3719 .condition(&cx_c, |user_store, _| {
3720 contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
3721 })
3722 .await;
3723
3724 let project_id = project_a
3725 .update(&mut cx_a, |project, _| project.next_remote_id())
3726 .await;
3727 project_a
3728 .update(&mut cx_a, |project, cx| project.share(cx))
3729 .await
3730 .unwrap();
3731
3732 let _project_b = Project::remote(
3733 project_id,
3734 client_b.clone(),
3735 client_b.user_store.clone(),
3736 lang_registry.clone(),
3737 fs.clone(),
3738 &mut cx_b.to_async(),
3739 )
3740 .await
3741 .unwrap();
3742
3743 client_a
3744 .user_store
3745 .condition(&cx_a, |user_store, _| {
3746 contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
3747 })
3748 .await;
3749 client_b
3750 .user_store
3751 .condition(&cx_b, |user_store, _| {
3752 contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
3753 })
3754 .await;
3755 client_c
3756 .user_store
3757 .condition(&cx_c, |user_store, _| {
3758 contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
3759 })
3760 .await;
3761
3762 project_a
3763 .condition(&cx_a, |project, _| {
3764 project.collaborators().contains_key(&client_b.peer_id)
3765 })
3766 .await;
3767
3768 cx_a.update(move |_| drop(project_a));
3769 client_a
3770 .user_store
3771 .condition(&cx_a, |user_store, _| contacts(user_store) == vec![])
3772 .await;
3773 client_b
3774 .user_store
3775 .condition(&cx_b, |user_store, _| contacts(user_store) == vec![])
3776 .await;
3777 client_c
3778 .user_store
3779 .condition(&cx_c, |user_store, _| contacts(user_store) == vec![])
3780 .await;
3781
3782 fn contacts(user_store: &UserStore) -> Vec<(&str, Vec<(&str, Vec<&str>)>)> {
3783 user_store
3784 .contacts()
3785 .iter()
3786 .map(|contact| {
3787 let worktrees = contact
3788 .projects
3789 .iter()
3790 .map(|p| {
3791 (
3792 p.worktree_root_names[0].as_str(),
3793 p.guests.iter().map(|p| p.github_login.as_str()).collect(),
3794 )
3795 })
3796 .collect();
3797 (contact.user.github_login.as_str(), worktrees)
3798 })
3799 .collect()
3800 }
3801 }
3802
3803 #[gpui::test(iterations = 100)]
3804 async fn test_random_collaboration(cx: TestAppContext, rng: StdRng) {
3805 cx.foreground().forbid_parking();
3806 let max_peers = env::var("MAX_PEERS")
3807 .map(|i| i.parse().expect("invalid `MAX_PEERS` variable"))
3808 .unwrap_or(5);
3809 let max_operations = env::var("OPERATIONS")
3810 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
3811 .unwrap_or(10);
3812
3813 let rng = Rc::new(RefCell::new(rng));
3814
3815 let mut host_lang_registry = Arc::new(LanguageRegistry::new());
3816 let guest_lang_registry = Arc::new(LanguageRegistry::new());
3817
3818 // Set up a fake language server.
3819 let (mut language_server_config, _fake_language_servers) = LanguageServerConfig::fake();
3820 language_server_config.set_fake_initializer(|fake_server| {
3821 fake_server.handle_request::<lsp::request::Completion, _>(|_| {
3822 Some(lsp::CompletionResponse::Array(vec![lsp::CompletionItem {
3823 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
3824 range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
3825 new_text: "the-new-text".to_string(),
3826 })),
3827 ..Default::default()
3828 }]))
3829 });
3830
3831 fake_server.handle_request::<lsp::request::CodeActionRequest, _>(|_| {
3832 Some(vec![lsp::CodeActionOrCommand::CodeAction(
3833 lsp::CodeAction {
3834 title: "the-code-action".to_string(),
3835 ..Default::default()
3836 },
3837 )])
3838 });
3839
3840 fake_server.handle_request::<lsp::request::PrepareRenameRequest, _>(|params| {
3841 Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(
3842 params.position,
3843 params.position,
3844 )))
3845 });
3846 });
3847
3848 Arc::get_mut(&mut host_lang_registry)
3849 .unwrap()
3850 .add(Arc::new(Language::new(
3851 LanguageConfig {
3852 name: "Rust".to_string(),
3853 path_suffixes: vec!["rs".to_string()],
3854 language_server: Some(language_server_config),
3855 ..Default::default()
3856 },
3857 None,
3858 )));
3859
3860 let fs = FakeFs::new(cx.background());
3861 fs.insert_tree(
3862 "/_collab",
3863 json!({
3864 ".zed.toml": r#"collaborators = ["guest-1", "guest-2", "guest-3", "guest-4", "guest-5"]"#
3865 }),
3866 )
3867 .await;
3868
3869 let operations = Rc::new(Cell::new(0));
3870 let mut server = TestServer::start(cx.foreground(), cx.background()).await;
3871 let mut clients = Vec::new();
3872
3873 let mut next_entity_id = 100000;
3874 let mut host_cx = TestAppContext::new(
3875 cx.foreground_platform(),
3876 cx.platform(),
3877 cx.foreground(),
3878 cx.background(),
3879 cx.font_cache(),
3880 next_entity_id,
3881 );
3882 let host = server.create_client(&mut host_cx, "host").await;
3883 let host_project = host_cx.update(|cx| {
3884 Project::local(
3885 host.client.clone(),
3886 host.user_store.clone(),
3887 host_lang_registry.clone(),
3888 fs.clone(),
3889 cx,
3890 )
3891 });
3892 let host_project_id = host_project
3893 .update(&mut host_cx, |p, _| p.next_remote_id())
3894 .await;
3895
3896 let (collab_worktree, _) = host_project
3897 .update(&mut host_cx, |project, cx| {
3898 project.find_or_create_local_worktree("/_collab", false, cx)
3899 })
3900 .await
3901 .unwrap();
3902 collab_worktree
3903 .read_with(&host_cx, |tree, _| tree.as_local().unwrap().scan_complete())
3904 .await;
3905 host_project
3906 .update(&mut host_cx, |project, cx| project.share(cx))
3907 .await
3908 .unwrap();
3909
3910 clients.push(cx.foreground().spawn(host.simulate_host(
3911 host_project.clone(),
3912 operations.clone(),
3913 max_operations,
3914 rng.clone(),
3915 host_cx.clone(),
3916 )));
3917
3918 while operations.get() < max_operations {
3919 cx.background().simulate_random_delay().await;
3920 if clients.len() < max_peers && rng.borrow_mut().gen_bool(0.05) {
3921 operations.set(operations.get() + 1);
3922
3923 let guest_id = clients.len();
3924 log::info!("Adding guest {}", guest_id);
3925 next_entity_id += 100000;
3926 let mut guest_cx = TestAppContext::new(
3927 cx.foreground_platform(),
3928 cx.platform(),
3929 cx.foreground(),
3930 cx.background(),
3931 cx.font_cache(),
3932 next_entity_id,
3933 );
3934 let guest = server
3935 .create_client(&mut guest_cx, &format!("guest-{}", guest_id))
3936 .await;
3937 let guest_project = Project::remote(
3938 host_project_id,
3939 guest.client.clone(),
3940 guest.user_store.clone(),
3941 guest_lang_registry.clone(),
3942 fs.clone(),
3943 &mut guest_cx.to_async(),
3944 )
3945 .await
3946 .unwrap();
3947 clients.push(cx.foreground().spawn(guest.simulate_guest(
3948 guest_id,
3949 guest_project,
3950 operations.clone(),
3951 max_operations,
3952 rng.clone(),
3953 guest_cx,
3954 )));
3955
3956 log::info!("Guest {} added", guest_id);
3957 }
3958 }
3959
3960 let clients = futures::future::join_all(clients).await;
3961 cx.foreground().run_until_parked();
3962
3963 let host_worktree_snapshots = host_project.read_with(&host_cx, |project, cx| {
3964 project
3965 .worktrees(cx)
3966 .map(|worktree| {
3967 let snapshot = worktree.read(cx).snapshot();
3968 (snapshot.id(), snapshot)
3969 })
3970 .collect::<BTreeMap<_, _>>()
3971 });
3972
3973 for (guest_client, guest_cx) in clients.iter().skip(1) {
3974 let guest_id = guest_client.client.id();
3975 let worktree_snapshots =
3976 guest_client
3977 .project
3978 .as_ref()
3979 .unwrap()
3980 .read_with(guest_cx, |project, cx| {
3981 project
3982 .worktrees(cx)
3983 .map(|worktree| {
3984 let worktree = worktree.read(cx);
3985 assert!(
3986 !worktree.as_remote().unwrap().has_pending_updates(),
3987 "Guest {} worktree {:?} contains deferred updates",
3988 guest_id,
3989 worktree.id()
3990 );
3991 (worktree.id(), worktree.snapshot())
3992 })
3993 .collect::<BTreeMap<_, _>>()
3994 });
3995
3996 assert_eq!(
3997 worktree_snapshots.keys().collect::<Vec<_>>(),
3998 host_worktree_snapshots.keys().collect::<Vec<_>>(),
3999 "guest {} has different worktrees than the host",
4000 guest_id
4001 );
4002 for (id, host_snapshot) in &host_worktree_snapshots {
4003 let guest_snapshot = &worktree_snapshots[id];
4004 assert_eq!(
4005 guest_snapshot.root_name(),
4006 host_snapshot.root_name(),
4007 "guest {} has different root name than the host for worktree {}",
4008 guest_id,
4009 id
4010 );
4011 assert_eq!(
4012 guest_snapshot.entries(false).collect::<Vec<_>>(),
4013 host_snapshot.entries(false).collect::<Vec<_>>(),
4014 "guest {} has different snapshot than the host for worktree {}",
4015 guest_id,
4016 id
4017 );
4018 }
4019
4020 guest_client
4021 .project
4022 .as_ref()
4023 .unwrap()
4024 .read_with(guest_cx, |project, _| {
4025 assert!(
4026 !project.has_buffered_operations(),
4027 "guest {} has buffered operations ",
4028 guest_id,
4029 );
4030 });
4031
4032 for guest_buffer in &guest_client.buffers {
4033 let buffer_id = guest_buffer.read_with(guest_cx, |buffer, _| buffer.remote_id());
4034 let host_buffer = host_project.read_with(&host_cx, |project, _| {
4035 project
4036 .shared_buffer(guest_client.peer_id, buffer_id)
4037 .expect(&format!(
4038 "host doest not have buffer for guest:{}, peer:{}, id:{}",
4039 guest_id, guest_client.peer_id, buffer_id
4040 ))
4041 });
4042 assert_eq!(
4043 guest_buffer.read_with(guest_cx, |buffer, _| buffer.text()),
4044 host_buffer.read_with(&host_cx, |buffer, _| buffer.text()),
4045 "guest {} buffer {} differs from the host's buffer",
4046 guest_id,
4047 buffer_id,
4048 );
4049 }
4050 }
4051 }
4052
4053 struct TestServer {
4054 peer: Arc<Peer>,
4055 app_state: Arc<AppState>,
4056 server: Arc<Server>,
4057 foreground: Rc<executor::Foreground>,
4058 notifications: mpsc::UnboundedReceiver<()>,
4059 connection_killers: Arc<Mutex<HashMap<UserId, watch::Sender<Option<()>>>>>,
4060 forbid_connections: Arc<AtomicBool>,
4061 _test_db: TestDb,
4062 }
4063
4064 impl TestServer {
4065 async fn start(
4066 foreground: Rc<executor::Foreground>,
4067 background: Arc<executor::Background>,
4068 ) -> Self {
4069 let test_db = TestDb::fake(background);
4070 let app_state = Self::build_app_state(&test_db).await;
4071 let peer = Peer::new();
4072 let notifications = mpsc::unbounded();
4073 let server = Server::new(app_state.clone(), peer.clone(), Some(notifications.0));
4074 Self {
4075 peer,
4076 app_state,
4077 server,
4078 foreground,
4079 notifications: notifications.1,
4080 connection_killers: Default::default(),
4081 forbid_connections: Default::default(),
4082 _test_db: test_db,
4083 }
4084 }
4085
4086 async fn create_client(&mut self, cx: &mut TestAppContext, name: &str) -> TestClient {
4087 let http = FakeHttpClient::with_404_response();
4088 let user_id = self.app_state.db.create_user(name, false).await.unwrap();
4089 let client_name = name.to_string();
4090 let mut client = Client::new(http.clone());
4091 let server = self.server.clone();
4092 let connection_killers = self.connection_killers.clone();
4093 let forbid_connections = self.forbid_connections.clone();
4094 let (connection_id_tx, mut connection_id_rx) = mpsc::channel(16);
4095
4096 Arc::get_mut(&mut client)
4097 .unwrap()
4098 .override_authenticate(move |cx| {
4099 cx.spawn(|_| async move {
4100 let access_token = "the-token".to_string();
4101 Ok(Credentials {
4102 user_id: user_id.0 as u64,
4103 access_token,
4104 })
4105 })
4106 })
4107 .override_establish_connection(move |credentials, cx| {
4108 assert_eq!(credentials.user_id, user_id.0 as u64);
4109 assert_eq!(credentials.access_token, "the-token");
4110
4111 let server = server.clone();
4112 let connection_killers = connection_killers.clone();
4113 let forbid_connections = forbid_connections.clone();
4114 let client_name = client_name.clone();
4115 let connection_id_tx = connection_id_tx.clone();
4116 cx.spawn(move |cx| async move {
4117 if forbid_connections.load(SeqCst) {
4118 Err(EstablishConnectionError::other(anyhow!(
4119 "server is forbidding connections"
4120 )))
4121 } else {
4122 let (client_conn, server_conn, kill_conn) =
4123 Connection::in_memory(cx.background());
4124 connection_killers.lock().insert(user_id, kill_conn);
4125 cx.background()
4126 .spawn(server.handle_connection(
4127 server_conn,
4128 client_name,
4129 user_id,
4130 Some(connection_id_tx),
4131 cx.background(),
4132 ))
4133 .detach();
4134 Ok(client_conn)
4135 }
4136 })
4137 });
4138
4139 client
4140 .authenticate_and_connect(&cx.to_async())
4141 .await
4142 .unwrap();
4143
4144 Channel::init(&client);
4145 Project::init(&client);
4146
4147 let peer_id = PeerId(connection_id_rx.next().await.unwrap().0);
4148 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http, cx));
4149 let mut authed_user =
4150 user_store.read_with(cx, |user_store, _| user_store.watch_current_user());
4151 while authed_user.next().await.unwrap().is_none() {}
4152
4153 TestClient {
4154 client,
4155 peer_id,
4156 user_store,
4157 project: Default::default(),
4158 buffers: Default::default(),
4159 }
4160 }
4161
4162 fn disconnect_client(&self, user_id: UserId) {
4163 if let Some(mut kill_conn) = self.connection_killers.lock().remove(&user_id) {
4164 let _ = kill_conn.try_send(Some(()));
4165 }
4166 }
4167
4168 fn forbid_connections(&self) {
4169 self.forbid_connections.store(true, SeqCst);
4170 }
4171
4172 fn allow_connections(&self) {
4173 self.forbid_connections.store(false, SeqCst);
4174 }
4175
4176 async fn build_app_state(test_db: &TestDb) -> Arc<AppState> {
4177 let mut config = Config::default();
4178 config.session_secret = "a".repeat(32);
4179 config.database_url = test_db.url.clone();
4180 let github_client = github::AppClient::test();
4181 Arc::new(AppState {
4182 db: test_db.db().clone(),
4183 handlebars: Default::default(),
4184 auth_client: auth::build_client("", ""),
4185 repo_client: github::RepoClient::test(&github_client),
4186 github_client,
4187 config,
4188 })
4189 }
4190
4191 async fn state<'a>(&'a self) -> RwLockReadGuard<'a, Store> {
4192 self.server.store.read()
4193 }
4194
4195 async fn condition<F>(&mut self, mut predicate: F)
4196 where
4197 F: FnMut(&Store) -> bool,
4198 {
4199 async_std::future::timeout(Duration::from_millis(500), async {
4200 while !(predicate)(&*self.server.store.read()) {
4201 self.foreground.start_waiting();
4202 self.notifications.next().await;
4203 self.foreground.finish_waiting();
4204 }
4205 })
4206 .await
4207 .expect("condition timed out");
4208 }
4209 }
4210
4211 impl Drop for TestServer {
4212 fn drop(&mut self) {
4213 self.peer.reset();
4214 }
4215 }
4216
4217 struct TestClient {
4218 client: Arc<Client>,
4219 pub peer_id: PeerId,
4220 pub user_store: ModelHandle<UserStore>,
4221 project: Option<ModelHandle<Project>>,
4222 buffers: HashSet<ModelHandle<zed::language::Buffer>>,
4223 }
4224
4225 impl Deref for TestClient {
4226 type Target = Arc<Client>;
4227
4228 fn deref(&self) -> &Self::Target {
4229 &self.client
4230 }
4231 }
4232
4233 impl TestClient {
4234 pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
4235 UserId::from_proto(
4236 self.user_store
4237 .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
4238 )
4239 }
4240
4241 async fn simulate_host(
4242 mut self,
4243 project: ModelHandle<Project>,
4244 operations: Rc<Cell<usize>>,
4245 max_operations: usize,
4246 rng: Rc<RefCell<StdRng>>,
4247 mut cx: TestAppContext,
4248 ) -> (Self, TestAppContext) {
4249 let fs = project.read_with(&cx, |project, _| project.fs().clone());
4250 let mut files: Vec<PathBuf> = Default::default();
4251 while operations.get() < max_operations {
4252 operations.set(operations.get() + 1);
4253
4254 let distribution = rng.borrow_mut().gen_range(0..100);
4255 match distribution {
4256 0..=20 if !files.is_empty() => {
4257 let mut path = files.choose(&mut *rng.borrow_mut()).unwrap().as_path();
4258 while let Some(parent_path) = path.parent() {
4259 path = parent_path;
4260 if rng.borrow_mut().gen() {
4261 break;
4262 }
4263 }
4264
4265 log::info!("Host: find/create local worktree {:?}", path);
4266 project
4267 .update(&mut cx, |project, cx| {
4268 project.find_or_create_local_worktree(path, false, cx)
4269 })
4270 .await
4271 .unwrap();
4272 }
4273 10..=80 if !files.is_empty() => {
4274 let buffer = if self.buffers.is_empty() || rng.borrow_mut().gen() {
4275 let file = files.choose(&mut *rng.borrow_mut()).unwrap();
4276 let (worktree, path) = project
4277 .update(&mut cx, |project, cx| {
4278 project.find_or_create_local_worktree(file, false, cx)
4279 })
4280 .await
4281 .unwrap();
4282 let project_path =
4283 worktree.read_with(&cx, |worktree, _| (worktree.id(), path));
4284 log::info!("Host: opening path {:?}", project_path);
4285 let buffer = project
4286 .update(&mut cx, |project, cx| {
4287 project.open_buffer(project_path, cx)
4288 })
4289 .await
4290 .unwrap();
4291 self.buffers.insert(buffer.clone());
4292 buffer
4293 } else {
4294 self.buffers
4295 .iter()
4296 .choose(&mut *rng.borrow_mut())
4297 .unwrap()
4298 .clone()
4299 };
4300
4301 if rng.borrow_mut().gen_bool(0.1) {
4302 cx.update(|cx| {
4303 log::info!(
4304 "Host: dropping buffer {:?}",
4305 buffer.read(cx).file().unwrap().full_path(cx)
4306 );
4307 self.buffers.remove(&buffer);
4308 drop(buffer);
4309 });
4310 } else {
4311 buffer.update(&mut cx, |buffer, cx| {
4312 log::info!(
4313 "Host: updating buffer {:?}",
4314 buffer.file().unwrap().full_path(cx)
4315 );
4316 buffer.randomly_edit(&mut *rng.borrow_mut(), 5, cx)
4317 });
4318 }
4319 }
4320 _ => loop {
4321 let path_component_count = rng.borrow_mut().gen_range(1..=5);
4322 let mut path = PathBuf::new();
4323 path.push("/");
4324 for _ in 0..path_component_count {
4325 let letter = rng.borrow_mut().gen_range(b'a'..=b'z');
4326 path.push(std::str::from_utf8(&[letter]).unwrap());
4327 }
4328 path.set_extension("rs");
4329 let parent_path = path.parent().unwrap();
4330
4331 log::info!("Host: creating file {:?}", path);
4332 if fs.create_dir(&parent_path).await.is_ok()
4333 && fs.create_file(&path, Default::default()).await.is_ok()
4334 {
4335 files.push(path);
4336 break;
4337 } else {
4338 log::info!("Host: cannot create file");
4339 }
4340 },
4341 }
4342
4343 cx.background().simulate_random_delay().await;
4344 }
4345
4346 self.project = Some(project);
4347 (self, cx)
4348 }
4349
4350 pub async fn simulate_guest(
4351 mut self,
4352 guest_id: usize,
4353 project: ModelHandle<Project>,
4354 operations: Rc<Cell<usize>>,
4355 max_operations: usize,
4356 rng: Rc<RefCell<StdRng>>,
4357 mut cx: TestAppContext,
4358 ) -> (Self, TestAppContext) {
4359 while operations.get() < max_operations {
4360 let buffer = if self.buffers.is_empty() || rng.borrow_mut().gen() {
4361 let worktree = if let Some(worktree) = project.read_with(&cx, |project, cx| {
4362 project
4363 .worktrees(&cx)
4364 .filter(|worktree| {
4365 worktree.read(cx).entries(false).any(|e| e.is_file())
4366 })
4367 .choose(&mut *rng.borrow_mut())
4368 }) {
4369 worktree
4370 } else {
4371 cx.background().simulate_random_delay().await;
4372 continue;
4373 };
4374
4375 operations.set(operations.get() + 1);
4376 let project_path = worktree.read_with(&cx, |worktree, _| {
4377 let entry = worktree
4378 .entries(false)
4379 .filter(|e| e.is_file())
4380 .choose(&mut *rng.borrow_mut())
4381 .unwrap();
4382 (worktree.id(), entry.path.clone())
4383 });
4384 log::info!("Guest {}: opening path {:?}", guest_id, project_path);
4385 let buffer = project
4386 .update(&mut cx, |project, cx| project.open_buffer(project_path, cx))
4387 .await
4388 .unwrap();
4389 self.buffers.insert(buffer.clone());
4390 buffer
4391 } else {
4392 operations.set(operations.get() + 1);
4393
4394 self.buffers
4395 .iter()
4396 .choose(&mut *rng.borrow_mut())
4397 .unwrap()
4398 .clone()
4399 };
4400
4401 let choice = rng.borrow_mut().gen_range(0..100);
4402 match choice {
4403 0..=9 => {
4404 cx.update(|cx| {
4405 log::info!(
4406 "Guest {}: dropping buffer {:?}",
4407 guest_id,
4408 buffer.read(cx).file().unwrap().full_path(cx)
4409 );
4410 self.buffers.remove(&buffer);
4411 drop(buffer);
4412 });
4413 }
4414 10..=19 => {
4415 let completions = project.update(&mut cx, |project, cx| {
4416 log::info!(
4417 "Guest {}: requesting completions for buffer {:?}",
4418 guest_id,
4419 buffer.read(cx).file().unwrap().full_path(cx)
4420 );
4421 let offset = rng.borrow_mut().gen_range(0..=buffer.read(cx).len());
4422 project.completions(&buffer, offset, cx)
4423 });
4424 let completions = cx.background().spawn(async move {
4425 completions.await.expect("completions request failed");
4426 });
4427 if rng.borrow_mut().gen_bool(0.3) {
4428 log::info!("Guest {}: detaching completions request", guest_id);
4429 completions.detach();
4430 } else {
4431 completions.await;
4432 }
4433 }
4434 20..=29 => {
4435 let code_actions = project.update(&mut cx, |project, cx| {
4436 log::info!(
4437 "Guest {}: requesting code actions for buffer {:?}",
4438 guest_id,
4439 buffer.read(cx).file().unwrap().full_path(cx)
4440 );
4441 let range =
4442 buffer.read(cx).random_byte_range(0, &mut *rng.borrow_mut());
4443 project.code_actions(&buffer, range, cx)
4444 });
4445 let code_actions = cx.background().spawn(async move {
4446 code_actions.await.expect("code actions request failed");
4447 });
4448 if rng.borrow_mut().gen_bool(0.3) {
4449 log::info!("Guest {}: detaching code actions request", guest_id);
4450 code_actions.detach();
4451 } else {
4452 code_actions.await;
4453 }
4454 }
4455 30..=39 if buffer.read_with(&cx, |buffer, _| buffer.is_dirty()) => {
4456 let (requested_version, save) = buffer.update(&mut cx, |buffer, cx| {
4457 log::info!(
4458 "Guest {}: saving buffer {:?}",
4459 guest_id,
4460 buffer.file().unwrap().full_path(cx)
4461 );
4462 (buffer.version(), buffer.save(cx))
4463 });
4464 let save = cx.spawn(|cx| async move {
4465 let (saved_version, _) = save.await.expect("save request failed");
4466 buffer.read_with(&cx, |buffer, _| {
4467 assert!(buffer.version().observed_all(&saved_version));
4468 assert!(saved_version.observed_all(&requested_version));
4469 });
4470 });
4471 if rng.borrow_mut().gen_bool(0.3) {
4472 log::info!("Guest {}: detaching save request", guest_id);
4473 save.detach();
4474 } else {
4475 save.await;
4476 }
4477 }
4478 40..=45 => {
4479 let prepare_rename = project.update(&mut cx, |project, cx| {
4480 log::info!(
4481 "Guest {}: preparing rename for buffer {:?}",
4482 guest_id,
4483 buffer.read(cx).file().unwrap().full_path(cx)
4484 );
4485 let offset = rng.borrow_mut().gen_range(0..=buffer.read(cx).len());
4486 project.prepare_rename(buffer, offset, cx)
4487 });
4488 let prepare_rename = cx.background().spawn(async move {
4489 prepare_rename.await.expect("prepare rename request failed");
4490 });
4491 if rng.borrow_mut().gen_bool(0.3) {
4492 log::info!("Guest {}: detaching prepare rename request", guest_id);
4493 prepare_rename.detach();
4494 } else {
4495 prepare_rename.await;
4496 }
4497 }
4498 _ => {
4499 buffer.update(&mut cx, |buffer, cx| {
4500 log::info!(
4501 "Guest {}: updating buffer {:?}",
4502 guest_id,
4503 buffer.file().unwrap().full_path(cx)
4504 );
4505 buffer.randomly_edit(&mut *rng.borrow_mut(), 5, cx)
4506 });
4507 }
4508 }
4509 cx.background().simulate_random_delay().await;
4510 }
4511
4512 self.project = Some(project);
4513 (self, cx)
4514 }
4515 }
4516
4517 impl Executor for Arc<gpui::executor::Background> {
4518 fn spawn_detached<F: 'static + Send + Future<Output = ()>>(&self, future: F) {
4519 self.spawn(future).detach();
4520 }
4521 }
4522
4523 fn channel_messages(channel: &Channel) -> Vec<(String, String, bool)> {
4524 channel
4525 .messages()
4526 .cursor::<()>()
4527 .map(|m| {
4528 (
4529 m.sender.github_login.clone(),
4530 m.body.clone(),
4531 m.is_pending(),
4532 )
4533 })
4534 .collect()
4535 }
4536
4537 struct EmptyView;
4538
4539 impl gpui::Entity for EmptyView {
4540 type Event = ();
4541 }
4542
4543 impl gpui::View for EmptyView {
4544 fn ui_name() -> &'static str {
4545 "empty view"
4546 }
4547
4548 fn render(&mut self, _: &mut gpui::RenderContext<Self>) -> gpui::ElementBox {
4549 gpui::Element::boxed(gpui::elements::Empty)
4550 }
4551 }
4552}