1mod store;
2
3use super::{
4 auth::process_auth_header,
5 db::{ChannelId, MessageId, UserId},
6 AppState,
7};
8use anyhow::anyhow;
9use async_std::task;
10use async_tungstenite::{tungstenite::protocol::Role, WebSocketStream};
11use collections::{HashMap, HashSet};
12use futures::{future::BoxFuture, FutureExt};
13use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard};
14use postage::{mpsc, prelude::Sink as _, prelude::Stream as _};
15use rpc::{
16 proto::{self, AnyTypedEnvelope, EnvelopedMessage},
17 Connection, ConnectionId, Peer, TypedEnvelope,
18};
19use sha1::{Digest as _, Sha1};
20use std::{any::TypeId, future::Future, mem, path::PathBuf, sync::Arc, time::Instant};
21use store::{Store, Worktree};
22use surf::StatusCode;
23use tide::log;
24use tide::{
25 http::headers::{HeaderName, CONNECTION, UPGRADE},
26 Request, Response,
27};
28use time::OffsetDateTime;
29
30type MessageHandler = Box<
31 dyn Send
32 + Sync
33 + Fn(Arc<Server>, Box<dyn AnyTypedEnvelope>) -> BoxFuture<'static, tide::Result<()>>,
34>;
35
36pub struct Server {
37 peer: Arc<Peer>,
38 store: RwLock<Store>,
39 app_state: Arc<AppState>,
40 handlers: HashMap<TypeId, MessageHandler>,
41 notifications: Option<mpsc::Sender<()>>,
42}
43
44const MESSAGE_COUNT_PER_PAGE: usize = 100;
45const MAX_MESSAGE_LEN: usize = 1024;
46const NO_SUCH_PROJECT: &'static str = "no such project";
47
48impl Server {
49 pub fn new(
50 app_state: Arc<AppState>,
51 peer: Arc<Peer>,
52 notifications: Option<mpsc::Sender<()>>,
53 ) -> Arc<Self> {
54 let mut server = Self {
55 peer,
56 app_state,
57 store: Default::default(),
58 handlers: Default::default(),
59 notifications,
60 };
61
62 server
63 .add_handler(Server::ping)
64 .add_handler(Server::register_project)
65 .add_handler(Server::unregister_project)
66 .add_handler(Server::share_project)
67 .add_handler(Server::unshare_project)
68 .add_handler(Server::join_project)
69 .add_handler(Server::leave_project)
70 .add_handler(Server::register_worktree)
71 .add_handler(Server::unregister_worktree)
72 .add_handler(Server::share_worktree)
73 .add_handler(Server::update_worktree)
74 .add_handler(Server::update_diagnostic_summary)
75 .add_handler(Server::disk_based_diagnostics_updating)
76 .add_handler(Server::disk_based_diagnostics_updated)
77 .add_handler(Server::open_buffer)
78 .add_handler(Server::close_buffer)
79 .add_handler(Server::update_buffer)
80 .add_handler(Server::buffer_saved)
81 .add_handler(Server::save_buffer)
82 .add_handler(Server::format_buffer)
83 .add_handler(Server::get_channels)
84 .add_handler(Server::get_users)
85 .add_handler(Server::join_channel)
86 .add_handler(Server::leave_channel)
87 .add_handler(Server::send_channel_message)
88 .add_handler(Server::get_channel_messages);
89
90 Arc::new(server)
91 }
92
93 fn add_handler<F, Fut, M>(&mut self, handler: F) -> &mut Self
94 where
95 F: 'static + Send + Sync + Fn(Arc<Self>, TypedEnvelope<M>) -> Fut,
96 Fut: 'static + Send + Future<Output = tide::Result<()>>,
97 M: EnvelopedMessage,
98 {
99 let prev_handler = self.handlers.insert(
100 TypeId::of::<M>(),
101 Box::new(move |server, envelope| {
102 let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
103 (handler)(server, *envelope).boxed()
104 }),
105 );
106 if prev_handler.is_some() {
107 panic!("registered a handler for the same message twice");
108 }
109 self
110 }
111
112 pub fn handle_connection(
113 self: &Arc<Self>,
114 connection: Connection,
115 addr: String,
116 user_id: UserId,
117 mut send_connection_id: Option<postage::mpsc::Sender<ConnectionId>>,
118 ) -> impl Future<Output = ()> {
119 let mut this = self.clone();
120 async move {
121 let (connection_id, handle_io, mut incoming_rx) =
122 this.peer.add_connection(connection).await;
123
124 if let Some(send_connection_id) = send_connection_id.as_mut() {
125 let _ = send_connection_id.send(connection_id).await;
126 }
127
128 this.state_mut().add_connection(connection_id, user_id);
129 if let Err(err) = this.update_contacts_for_users(&[user_id]).await {
130 log::error!("error updating contacts for {:?}: {}", user_id, err);
131 }
132
133 let handle_io = handle_io.fuse();
134 futures::pin_mut!(handle_io);
135 loop {
136 let next_message = incoming_rx.recv().fuse();
137 futures::pin_mut!(next_message);
138 futures::select_biased! {
139 message = next_message => {
140 if let Some(message) = message {
141 let start_time = Instant::now();
142 log::info!("RPC message received: {}", message.payload_type_name());
143 if let Some(handler) = this.handlers.get(&message.payload_type_id()) {
144 if let Err(err) = (handler)(this.clone(), message).await {
145 log::error!("error handling message: {:?}", err);
146 } else {
147 log::info!("RPC message handled. duration:{:?}", start_time.elapsed());
148 }
149
150 if let Some(mut notifications) = this.notifications.clone() {
151 let _ = notifications.send(()).await;
152 }
153 } else {
154 log::warn!("unhandled message: {}", message.payload_type_name());
155 }
156 } else {
157 log::info!("rpc connection closed {:?}", addr);
158 break;
159 }
160 }
161 handle_io = handle_io => {
162 if let Err(err) = handle_io {
163 log::error!("error handling rpc connection {:?} - {:?}", addr, err);
164 }
165 break;
166 }
167 }
168 }
169
170 if let Err(err) = this.sign_out(connection_id).await {
171 log::error!("error signing out connection {:?} - {:?}", addr, err);
172 }
173 }
174 }
175
176 async fn sign_out(self: &mut Arc<Self>, connection_id: ConnectionId) -> tide::Result<()> {
177 self.peer.disconnect(connection_id).await;
178 let removed_connection = self.state_mut().remove_connection(connection_id)?;
179
180 for (project_id, project) in removed_connection.hosted_projects {
181 if let Some(share) = project.share {
182 broadcast(
183 connection_id,
184 share.guests.keys().copied().collect(),
185 |conn_id| {
186 self.peer
187 .send(conn_id, proto::UnshareProject { project_id })
188 },
189 )
190 .await?;
191 }
192 }
193
194 for (project_id, peer_ids) in removed_connection.guest_project_ids {
195 broadcast(connection_id, peer_ids, |conn_id| {
196 self.peer.send(
197 conn_id,
198 proto::RemoveProjectCollaborator {
199 project_id,
200 peer_id: connection_id.0,
201 },
202 )
203 })
204 .await?;
205 }
206
207 self.update_contacts_for_users(removed_connection.contact_ids.iter())
208 .await?;
209
210 Ok(())
211 }
212
213 async fn ping(self: Arc<Server>, request: TypedEnvelope<proto::Ping>) -> tide::Result<()> {
214 self.peer.respond(request.receipt(), proto::Ack {}).await?;
215 Ok(())
216 }
217
218 async fn register_project(
219 mut self: Arc<Server>,
220 request: TypedEnvelope<proto::RegisterProject>,
221 ) -> tide::Result<()> {
222 let project_id = {
223 let mut state = self.state_mut();
224 let user_id = state.user_id_for_connection(request.sender_id)?;
225 state.register_project(request.sender_id, user_id)
226 };
227 self.peer
228 .respond(
229 request.receipt(),
230 proto::RegisterProjectResponse { project_id },
231 )
232 .await?;
233 Ok(())
234 }
235
236 async fn unregister_project(
237 mut self: Arc<Server>,
238 request: TypedEnvelope<proto::UnregisterProject>,
239 ) -> tide::Result<()> {
240 let project = self
241 .state_mut()
242 .unregister_project(request.payload.project_id, request.sender_id)
243 .ok_or_else(|| anyhow!("no such project"))?;
244 self.update_contacts_for_users(project.authorized_user_ids().iter())
245 .await?;
246 Ok(())
247 }
248
249 async fn share_project(
250 mut self: Arc<Server>,
251 request: TypedEnvelope<proto::ShareProject>,
252 ) -> tide::Result<()> {
253 self.state_mut()
254 .share_project(request.payload.project_id, request.sender_id);
255 self.peer.respond(request.receipt(), proto::Ack {}).await?;
256 Ok(())
257 }
258
259 async fn unshare_project(
260 mut self: Arc<Server>,
261 request: TypedEnvelope<proto::UnshareProject>,
262 ) -> tide::Result<()> {
263 let project_id = request.payload.project_id;
264 let project = self
265 .state_mut()
266 .unshare_project(project_id, request.sender_id)?;
267
268 broadcast(request.sender_id, project.connection_ids, |conn_id| {
269 self.peer
270 .send(conn_id, proto::UnshareProject { project_id })
271 })
272 .await?;
273 self.update_contacts_for_users(&project.authorized_user_ids)
274 .await?;
275
276 Ok(())
277 }
278
279 async fn join_project(
280 mut self: Arc<Server>,
281 request: TypedEnvelope<proto::JoinProject>,
282 ) -> tide::Result<()> {
283 let project_id = request.payload.project_id;
284
285 let user_id = self.state().user_id_for_connection(request.sender_id)?;
286 let response_data = self
287 .state_mut()
288 .join_project(request.sender_id, user_id, project_id)
289 .and_then(|joined| {
290 let share = joined.project.share()?;
291 let peer_count = share.guests.len();
292 let mut collaborators = Vec::with_capacity(peer_count);
293 collaborators.push(proto::Collaborator {
294 peer_id: joined.project.host_connection_id.0,
295 replica_id: 0,
296 user_id: joined.project.host_user_id.to_proto(),
297 });
298 let worktrees = joined
299 .project
300 .worktrees
301 .iter()
302 .filter_map(|(id, worktree)| {
303 worktree.share.as_ref().map(|share| proto::Worktree {
304 id: *id,
305 root_name: worktree.root_name.clone(),
306 entries: share.entries.values().cloned().collect(),
307 diagnostic_summaries: share
308 .diagnostic_summaries
309 .values()
310 .cloned()
311 .collect(),
312 })
313 })
314 .collect();
315 for (peer_conn_id, (peer_replica_id, peer_user_id)) in &share.guests {
316 if *peer_conn_id != request.sender_id {
317 collaborators.push(proto::Collaborator {
318 peer_id: peer_conn_id.0,
319 replica_id: *peer_replica_id as u32,
320 user_id: peer_user_id.to_proto(),
321 });
322 }
323 }
324 let response = proto::JoinProjectResponse {
325 worktrees,
326 replica_id: joined.replica_id as u32,
327 collaborators,
328 };
329 let connection_ids = joined.project.connection_ids();
330 let contact_user_ids = joined.project.authorized_user_ids();
331 Ok((response, connection_ids, contact_user_ids))
332 });
333
334 match response_data {
335 Ok((response, connection_ids, contact_user_ids)) => {
336 broadcast(request.sender_id, connection_ids, |conn_id| {
337 self.peer.send(
338 conn_id,
339 proto::AddProjectCollaborator {
340 project_id: project_id,
341 collaborator: Some(proto::Collaborator {
342 peer_id: request.sender_id.0,
343 replica_id: response.replica_id,
344 user_id: user_id.to_proto(),
345 }),
346 },
347 )
348 })
349 .await?;
350 self.peer.respond(request.receipt(), response).await?;
351 self.update_contacts_for_users(&contact_user_ids).await?;
352 }
353 Err(error) => {
354 self.peer
355 .respond_with_error(
356 request.receipt(),
357 proto::Error {
358 message: error.to_string(),
359 },
360 )
361 .await?;
362 }
363 }
364
365 Ok(())
366 }
367
368 async fn leave_project(
369 mut self: Arc<Server>,
370 request: TypedEnvelope<proto::LeaveProject>,
371 ) -> tide::Result<()> {
372 let sender_id = request.sender_id;
373 let project_id = request.payload.project_id;
374 let worktree = self.state_mut().leave_project(sender_id, project_id);
375 if let Some(worktree) = worktree {
376 broadcast(sender_id, worktree.connection_ids, |conn_id| {
377 self.peer.send(
378 conn_id,
379 proto::RemoveProjectCollaborator {
380 project_id,
381 peer_id: sender_id.0,
382 },
383 )
384 })
385 .await?;
386 self.update_contacts_for_users(&worktree.authorized_user_ids)
387 .await?;
388 }
389 Ok(())
390 }
391
392 async fn register_worktree(
393 mut self: Arc<Server>,
394 request: TypedEnvelope<proto::RegisterWorktree>,
395 ) -> tide::Result<()> {
396 let receipt = request.receipt();
397 let host_user_id = self.state().user_id_for_connection(request.sender_id)?;
398
399 let mut contact_user_ids = HashSet::default();
400 contact_user_ids.insert(host_user_id);
401 for github_login in request.payload.authorized_logins {
402 match self.app_state.db.create_user(&github_login, false).await {
403 Ok(contact_user_id) => {
404 contact_user_ids.insert(contact_user_id);
405 }
406 Err(err) => {
407 let message = err.to_string();
408 self.peer
409 .respond_with_error(receipt, proto::Error { message })
410 .await?;
411 return Ok(());
412 }
413 }
414 }
415
416 let contact_user_ids = contact_user_ids.into_iter().collect::<Vec<_>>();
417 let ok = self.state_mut().register_worktree(
418 request.payload.project_id,
419 request.payload.worktree_id,
420 Worktree {
421 authorized_user_ids: contact_user_ids.clone(),
422 root_name: request.payload.root_name,
423 share: None,
424 },
425 );
426
427 if ok {
428 self.peer.respond(receipt, proto::Ack {}).await?;
429 self.update_contacts_for_users(&contact_user_ids).await?;
430 } else {
431 self.peer
432 .respond_with_error(
433 receipt,
434 proto::Error {
435 message: NO_SUCH_PROJECT.to_string(),
436 },
437 )
438 .await?;
439 }
440
441 Ok(())
442 }
443
444 async fn unregister_worktree(
445 mut self: Arc<Server>,
446 request: TypedEnvelope<proto::UnregisterWorktree>,
447 ) -> tide::Result<()> {
448 let project_id = request.payload.project_id;
449 let worktree_id = request.payload.worktree_id;
450 let (worktree, guest_connection_ids) =
451 self.state_mut()
452 .unregister_worktree(project_id, worktree_id, request.sender_id)?;
453
454 broadcast(request.sender_id, guest_connection_ids, |conn_id| {
455 self.peer.send(
456 conn_id,
457 proto::UnregisterWorktree {
458 project_id,
459 worktree_id,
460 },
461 )
462 })
463 .await?;
464 self.update_contacts_for_users(&worktree.authorized_user_ids)
465 .await?;
466 Ok(())
467 }
468
469 async fn share_worktree(
470 mut self: Arc<Server>,
471 mut request: TypedEnvelope<proto::ShareWorktree>,
472 ) -> tide::Result<()> {
473 let worktree = request
474 .payload
475 .worktree
476 .as_mut()
477 .ok_or_else(|| anyhow!("missing worktree"))?;
478 let entries = mem::take(&mut worktree.entries)
479 .into_iter()
480 .map(|entry| (entry.id, entry))
481 .collect();
482
483 let diagnostic_summaries = mem::take(&mut worktree.diagnostic_summaries)
484 .into_iter()
485 .map(|summary| (PathBuf::from(summary.path.clone()), summary))
486 .collect();
487
488 let contact_user_ids = self.state_mut().share_worktree(
489 request.payload.project_id,
490 worktree.id,
491 request.sender_id,
492 entries,
493 diagnostic_summaries,
494 );
495 if let Some(contact_user_ids) = contact_user_ids {
496 self.peer.respond(request.receipt(), proto::Ack {}).await?;
497 self.update_contacts_for_users(&contact_user_ids).await?;
498 } else {
499 self.peer
500 .respond_with_error(
501 request.receipt(),
502 proto::Error {
503 message: "no such worktree".to_string(),
504 },
505 )
506 .await?;
507 }
508 Ok(())
509 }
510
511 async fn update_worktree(
512 mut self: Arc<Server>,
513 request: TypedEnvelope<proto::UpdateWorktree>,
514 ) -> tide::Result<()> {
515 let connection_ids = self
516 .state_mut()
517 .update_worktree(
518 request.sender_id,
519 request.payload.project_id,
520 request.payload.worktree_id,
521 &request.payload.removed_entries,
522 &request.payload.updated_entries,
523 )
524 .ok_or_else(|| anyhow!("no such worktree"))?;
525
526 broadcast(request.sender_id, connection_ids, |connection_id| {
527 self.peer
528 .forward_send(request.sender_id, connection_id, request.payload.clone())
529 })
530 .await?;
531
532 Ok(())
533 }
534
535 async fn update_diagnostic_summary(
536 mut self: Arc<Server>,
537 request: TypedEnvelope<proto::UpdateDiagnosticSummary>,
538 ) -> tide::Result<()> {
539 let receiver_ids = request
540 .payload
541 .summary
542 .clone()
543 .and_then(|summary| {
544 self.state_mut().update_diagnostic_summary(
545 request.payload.project_id,
546 request.payload.worktree_id,
547 request.sender_id,
548 summary,
549 )
550 })
551 .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
552
553 broadcast(request.sender_id, receiver_ids, |connection_id| {
554 self.peer
555 .forward_send(request.sender_id, connection_id, request.payload.clone())
556 })
557 .await?;
558 Ok(())
559 }
560
561 async fn disk_based_diagnostics_updating(
562 self: Arc<Server>,
563 request: TypedEnvelope<proto::DiskBasedDiagnosticsUpdating>,
564 ) -> tide::Result<()> {
565 let receiver_ids = self
566 .state()
567 .project_connection_ids(request.payload.project_id, request.sender_id)
568 .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
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 .await?;
574 Ok(())
575 }
576
577 async fn disk_based_diagnostics_updated(
578 self: Arc<Server>,
579 request: TypedEnvelope<proto::DiskBasedDiagnosticsUpdated>,
580 ) -> tide::Result<()> {
581 let receiver_ids = self
582 .state()
583 .project_connection_ids(request.payload.project_id, request.sender_id)
584 .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
585 broadcast(request.sender_id, receiver_ids, |connection_id| {
586 self.peer
587 .forward_send(request.sender_id, connection_id, request.payload.clone())
588 })
589 .await?;
590 Ok(())
591 }
592
593 async fn open_buffer(
594 self: Arc<Server>,
595 request: TypedEnvelope<proto::OpenBuffer>,
596 ) -> tide::Result<()> {
597 let receipt = request.receipt();
598 let host_connection_id = self
599 .state()
600 .read_project(request.payload.project_id, request.sender_id)
601 .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?
602 .host_connection_id;
603 let response = self
604 .peer
605 .forward_request(request.sender_id, host_connection_id, request.payload)
606 .await?;
607 self.peer.respond(receipt, response).await?;
608 Ok(())
609 }
610
611 async fn close_buffer(
612 self: Arc<Server>,
613 request: TypedEnvelope<proto::CloseBuffer>,
614 ) -> tide::Result<()> {
615 let host_connection_id = self
616 .state()
617 .read_project(request.payload.project_id, request.sender_id)
618 .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?
619 .host_connection_id;
620 self.peer
621 .forward_send(request.sender_id, host_connection_id, request.payload)
622 .await?;
623 Ok(())
624 }
625
626 async fn save_buffer(
627 self: Arc<Server>,
628 request: TypedEnvelope<proto::SaveBuffer>,
629 ) -> tide::Result<()> {
630 let host;
631 let guests;
632 {
633 let state = self.state();
634 let project = state
635 .read_project(request.payload.project_id, request.sender_id)
636 .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
637 host = project.host_connection_id;
638 guests = project.guest_connection_ids()
639 }
640
641 let sender = request.sender_id;
642 let receipt = request.receipt();
643 let response = self
644 .peer
645 .forward_request(sender, host, request.payload.clone())
646 .await?;
647
648 broadcast(host, guests, |conn_id| {
649 let response = response.clone();
650 let peer = &self.peer;
651 async move {
652 if conn_id == sender {
653 peer.respond(receipt, response).await
654 } else {
655 peer.forward_send(host, conn_id, response).await
656 }
657 }
658 })
659 .await?;
660
661 Ok(())
662 }
663
664 async fn format_buffer(
665 self: Arc<Server>,
666 request: TypedEnvelope<proto::FormatBuffer>,
667 ) -> tide::Result<()> {
668 let host;
669 {
670 let state = self.state();
671 let project = state
672 .read_project(request.payload.project_id, request.sender_id)
673 .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
674 host = project.host_connection_id;
675 }
676
677 let sender = request.sender_id;
678 let receipt = request.receipt();
679 let response = self
680 .peer
681 .forward_request(sender, host, request.payload.clone())
682 .await?;
683 self.peer.respond(receipt, response).await?;
684
685 Ok(())
686 }
687
688 async fn update_buffer(
689 self: Arc<Server>,
690 request: TypedEnvelope<proto::UpdateBuffer>,
691 ) -> tide::Result<()> {
692 let receiver_ids = self
693 .state()
694 .project_connection_ids(request.payload.project_id, request.sender_id)
695 .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
696 broadcast(request.sender_id, receiver_ids, |connection_id| {
697 self.peer
698 .forward_send(request.sender_id, connection_id, request.payload.clone())
699 })
700 .await?;
701 self.peer.respond(request.receipt(), proto::Ack {}).await?;
702 Ok(())
703 }
704
705 async fn buffer_saved(
706 self: Arc<Server>,
707 request: TypedEnvelope<proto::BufferSaved>,
708 ) -> tide::Result<()> {
709 let receiver_ids = self
710 .state()
711 .project_connection_ids(request.payload.project_id, request.sender_id)
712 .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
713 broadcast(request.sender_id, receiver_ids, |connection_id| {
714 self.peer
715 .forward_send(request.sender_id, connection_id, request.payload.clone())
716 })
717 .await?;
718 Ok(())
719 }
720
721 async fn get_channels(
722 self: Arc<Server>,
723 request: TypedEnvelope<proto::GetChannels>,
724 ) -> tide::Result<()> {
725 let user_id = self.state().user_id_for_connection(request.sender_id)?;
726 let channels = self.app_state.db.get_accessible_channels(user_id).await?;
727 self.peer
728 .respond(
729 request.receipt(),
730 proto::GetChannelsResponse {
731 channels: channels
732 .into_iter()
733 .map(|chan| proto::Channel {
734 id: chan.id.to_proto(),
735 name: chan.name,
736 })
737 .collect(),
738 },
739 )
740 .await?;
741 Ok(())
742 }
743
744 async fn get_users(
745 self: Arc<Server>,
746 request: TypedEnvelope<proto::GetUsers>,
747 ) -> tide::Result<()> {
748 let receipt = request.receipt();
749 let user_ids = request.payload.user_ids.into_iter().map(UserId::from_proto);
750 let users = self
751 .app_state
752 .db
753 .get_users_by_ids(user_ids)
754 .await?
755 .into_iter()
756 .map(|user| proto::User {
757 id: user.id.to_proto(),
758 avatar_url: format!("https://github.com/{}.png?size=128", user.github_login),
759 github_login: user.github_login,
760 })
761 .collect();
762 self.peer
763 .respond(receipt, proto::GetUsersResponse { users })
764 .await?;
765 Ok(())
766 }
767
768 async fn update_contacts_for_users<'a>(
769 self: &Arc<Server>,
770 user_ids: impl IntoIterator<Item = &'a UserId>,
771 ) -> tide::Result<()> {
772 let mut send_futures = Vec::new();
773
774 {
775 let state = self.state();
776 for user_id in user_ids {
777 let contacts = state.contacts_for_user(*user_id);
778 for connection_id in state.connection_ids_for_user(*user_id) {
779 send_futures.push(self.peer.send(
780 connection_id,
781 proto::UpdateContacts {
782 contacts: contacts.clone(),
783 },
784 ));
785 }
786 }
787 }
788 futures::future::try_join_all(send_futures).await?;
789
790 Ok(())
791 }
792
793 async fn join_channel(
794 mut self: Arc<Self>,
795 request: TypedEnvelope<proto::JoinChannel>,
796 ) -> tide::Result<()> {
797 let user_id = self.state().user_id_for_connection(request.sender_id)?;
798 let channel_id = ChannelId::from_proto(request.payload.channel_id);
799 if !self
800 .app_state
801 .db
802 .can_user_access_channel(user_id, channel_id)
803 .await?
804 {
805 Err(anyhow!("access denied"))?;
806 }
807
808 self.state_mut().join_channel(request.sender_id, channel_id);
809 let messages = self
810 .app_state
811 .db
812 .get_channel_messages(channel_id, MESSAGE_COUNT_PER_PAGE, None)
813 .await?
814 .into_iter()
815 .map(|msg| proto::ChannelMessage {
816 id: msg.id.to_proto(),
817 body: msg.body,
818 timestamp: msg.sent_at.unix_timestamp() as u64,
819 sender_id: msg.sender_id.to_proto(),
820 nonce: Some(msg.nonce.as_u128().into()),
821 })
822 .collect::<Vec<_>>();
823 self.peer
824 .respond(
825 request.receipt(),
826 proto::JoinChannelResponse {
827 done: messages.len() < MESSAGE_COUNT_PER_PAGE,
828 messages,
829 },
830 )
831 .await?;
832 Ok(())
833 }
834
835 async fn leave_channel(
836 mut self: Arc<Self>,
837 request: TypedEnvelope<proto::LeaveChannel>,
838 ) -> tide::Result<()> {
839 let user_id = self.state().user_id_for_connection(request.sender_id)?;
840 let channel_id = ChannelId::from_proto(request.payload.channel_id);
841 if !self
842 .app_state
843 .db
844 .can_user_access_channel(user_id, channel_id)
845 .await?
846 {
847 Err(anyhow!("access denied"))?;
848 }
849
850 self.state_mut()
851 .leave_channel(request.sender_id, channel_id);
852
853 Ok(())
854 }
855
856 async fn send_channel_message(
857 self: Arc<Self>,
858 request: TypedEnvelope<proto::SendChannelMessage>,
859 ) -> tide::Result<()> {
860 let receipt = request.receipt();
861 let channel_id = ChannelId::from_proto(request.payload.channel_id);
862 let user_id;
863 let connection_ids;
864 {
865 let state = self.state();
866 user_id = state.user_id_for_connection(request.sender_id)?;
867 if let Some(ids) = state.channel_connection_ids(channel_id) {
868 connection_ids = ids;
869 } else {
870 return Ok(());
871 }
872 }
873
874 // Validate the message body.
875 let body = request.payload.body.trim().to_string();
876 if body.len() > MAX_MESSAGE_LEN {
877 self.peer
878 .respond_with_error(
879 receipt,
880 proto::Error {
881 message: "message is too long".to_string(),
882 },
883 )
884 .await?;
885 return Ok(());
886 }
887 if body.is_empty() {
888 self.peer
889 .respond_with_error(
890 receipt,
891 proto::Error {
892 message: "message can't be blank".to_string(),
893 },
894 )
895 .await?;
896 return Ok(());
897 }
898
899 let timestamp = OffsetDateTime::now_utc();
900 let nonce = if let Some(nonce) = request.payload.nonce {
901 nonce
902 } else {
903 self.peer
904 .respond_with_error(
905 receipt,
906 proto::Error {
907 message: "nonce can't be blank".to_string(),
908 },
909 )
910 .await?;
911 return Ok(());
912 };
913
914 let message_id = self
915 .app_state
916 .db
917 .create_channel_message(channel_id, user_id, &body, timestamp, nonce.clone().into())
918 .await?
919 .to_proto();
920 let message = proto::ChannelMessage {
921 sender_id: user_id.to_proto(),
922 id: message_id,
923 body,
924 timestamp: timestamp.unix_timestamp() as u64,
925 nonce: Some(nonce),
926 };
927 broadcast(request.sender_id, connection_ids, |conn_id| {
928 self.peer.send(
929 conn_id,
930 proto::ChannelMessageSent {
931 channel_id: channel_id.to_proto(),
932 message: Some(message.clone()),
933 },
934 )
935 })
936 .await?;
937 self.peer
938 .respond(
939 receipt,
940 proto::SendChannelMessageResponse {
941 message: Some(message),
942 },
943 )
944 .await?;
945 Ok(())
946 }
947
948 async fn get_channel_messages(
949 self: Arc<Self>,
950 request: TypedEnvelope<proto::GetChannelMessages>,
951 ) -> tide::Result<()> {
952 let user_id = self.state().user_id_for_connection(request.sender_id)?;
953 let channel_id = ChannelId::from_proto(request.payload.channel_id);
954 if !self
955 .app_state
956 .db
957 .can_user_access_channel(user_id, channel_id)
958 .await?
959 {
960 Err(anyhow!("access denied"))?;
961 }
962
963 let messages = self
964 .app_state
965 .db
966 .get_channel_messages(
967 channel_id,
968 MESSAGE_COUNT_PER_PAGE,
969 Some(MessageId::from_proto(request.payload.before_message_id)),
970 )
971 .await?
972 .into_iter()
973 .map(|msg| proto::ChannelMessage {
974 id: msg.id.to_proto(),
975 body: msg.body,
976 timestamp: msg.sent_at.unix_timestamp() as u64,
977 sender_id: msg.sender_id.to_proto(),
978 nonce: Some(msg.nonce.as_u128().into()),
979 })
980 .collect::<Vec<_>>();
981 self.peer
982 .respond(
983 request.receipt(),
984 proto::GetChannelMessagesResponse {
985 done: messages.len() < MESSAGE_COUNT_PER_PAGE,
986 messages,
987 },
988 )
989 .await?;
990 Ok(())
991 }
992
993 fn state<'a>(self: &'a Arc<Self>) -> RwLockReadGuard<'a, Store> {
994 self.store.read()
995 }
996
997 fn state_mut<'a>(self: &'a mut Arc<Self>) -> RwLockWriteGuard<'a, Store> {
998 self.store.write()
999 }
1000}
1001
1002pub async fn broadcast<F, T>(
1003 sender_id: ConnectionId,
1004 receiver_ids: Vec<ConnectionId>,
1005 mut f: F,
1006) -> anyhow::Result<()>
1007where
1008 F: FnMut(ConnectionId) -> T,
1009 T: Future<Output = anyhow::Result<()>>,
1010{
1011 let futures = receiver_ids
1012 .into_iter()
1013 .filter(|id| *id != sender_id)
1014 .map(|id| f(id));
1015 futures::future::try_join_all(futures).await?;
1016 Ok(())
1017}
1018
1019pub fn add_routes(app: &mut tide::Server<Arc<AppState>>, rpc: &Arc<Peer>) {
1020 let server = Server::new(app.state().clone(), rpc.clone(), None);
1021 app.at("/rpc").get(move |request: Request<Arc<AppState>>| {
1022 let server = server.clone();
1023 async move {
1024 const WEBSOCKET_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
1025
1026 let connection_upgrade = header_contains_ignore_case(&request, CONNECTION, "upgrade");
1027 let upgrade_to_websocket = header_contains_ignore_case(&request, UPGRADE, "websocket");
1028 let upgrade_requested = connection_upgrade && upgrade_to_websocket;
1029 let client_protocol_version: Option<u32> = request
1030 .header("X-Zed-Protocol-Version")
1031 .and_then(|v| v.as_str().parse().ok());
1032
1033 if !upgrade_requested || client_protocol_version != Some(rpc::PROTOCOL_VERSION) {
1034 return Ok(Response::new(StatusCode::UpgradeRequired));
1035 }
1036
1037 let header = match request.header("Sec-Websocket-Key") {
1038 Some(h) => h.as_str(),
1039 None => return Err(anyhow!("expected sec-websocket-key"))?,
1040 };
1041
1042 let user_id = process_auth_header(&request).await?;
1043
1044 let mut response = Response::new(StatusCode::SwitchingProtocols);
1045 response.insert_header(UPGRADE, "websocket");
1046 response.insert_header(CONNECTION, "Upgrade");
1047 let hash = Sha1::new().chain(header).chain(WEBSOCKET_GUID).finalize();
1048 response.insert_header("Sec-Websocket-Accept", base64::encode(&hash[..]));
1049 response.insert_header("Sec-Websocket-Version", "13");
1050
1051 let http_res: &mut tide::http::Response = response.as_mut();
1052 let upgrade_receiver = http_res.recv_upgrade().await;
1053 let addr = request.remote().unwrap_or("unknown").to_string();
1054 task::spawn(async move {
1055 if let Some(stream) = upgrade_receiver.await {
1056 server
1057 .handle_connection(
1058 Connection::new(
1059 WebSocketStream::from_raw_socket(stream, Role::Server, None).await,
1060 ),
1061 addr,
1062 user_id,
1063 None,
1064 )
1065 .await;
1066 }
1067 });
1068
1069 Ok(response)
1070 }
1071 });
1072}
1073
1074fn header_contains_ignore_case<T>(
1075 request: &tide::Request<T>,
1076 header_name: HeaderName,
1077 value: &str,
1078) -> bool {
1079 request
1080 .header(header_name)
1081 .map(|h| {
1082 h.as_str()
1083 .split(',')
1084 .any(|s| s.trim().eq_ignore_ascii_case(value.trim()))
1085 })
1086 .unwrap_or(false)
1087}
1088
1089#[cfg(test)]
1090mod tests {
1091 use super::*;
1092 use crate::{
1093 auth,
1094 db::{tests::TestDb, UserId},
1095 github, AppState, Config,
1096 };
1097 use ::rpc::Peer;
1098 use async_std::task;
1099 use gpui::{executor, ModelHandle, TestAppContext};
1100 use parking_lot::Mutex;
1101 use postage::{mpsc, watch};
1102 use rpc::PeerId;
1103 use serde_json::json;
1104 use sqlx::types::time::OffsetDateTime;
1105 use std::{
1106 ops::Deref,
1107 path::Path,
1108 rc::Rc,
1109 sync::{
1110 atomic::{AtomicBool, Ordering::SeqCst},
1111 Arc,
1112 },
1113 time::Duration,
1114 };
1115 use zed::{
1116 client::{
1117 self, test::FakeHttpClient, Channel, ChannelDetails, ChannelList, Client, Credentials,
1118 EstablishConnectionError, UserStore,
1119 },
1120 editor::{Editor, EditorSettings, Input, MultiBuffer},
1121 fs::{FakeFs, Fs as _},
1122 language::{
1123 tree_sitter_rust, Diagnostic, DiagnosticEntry, Language, LanguageConfig,
1124 LanguageRegistry, LanguageServerConfig, Point,
1125 },
1126 lsp,
1127 project::{DiagnosticSummary, Project, ProjectPath},
1128 };
1129
1130 #[gpui::test]
1131 async fn test_share_project(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1132 let (window_b, _) = cx_b.add_window(|_| EmptyView);
1133 let lang_registry = Arc::new(LanguageRegistry::new());
1134 let fs = Arc::new(FakeFs::new());
1135 cx_a.foreground().forbid_parking();
1136
1137 // Connect to a server as 2 clients.
1138 let mut server = TestServer::start(cx_a.foreground()).await;
1139 let client_a = server.create_client(&mut cx_a, "user_a").await;
1140 let client_b = server.create_client(&mut cx_b, "user_b").await;
1141
1142 // Share a project as client A
1143 fs.insert_tree(
1144 "/a",
1145 json!({
1146 ".zed.toml": r#"collaborators = ["user_b"]"#,
1147 "a.txt": "a-contents",
1148 "b.txt": "b-contents",
1149 }),
1150 )
1151 .await;
1152 let project_a = cx_a.update(|cx| {
1153 Project::local(
1154 client_a.clone(),
1155 client_a.user_store.clone(),
1156 lang_registry.clone(),
1157 fs.clone(),
1158 cx,
1159 )
1160 });
1161 let worktree_a = project_a
1162 .update(&mut cx_a, |p, cx| p.add_local_worktree("/a", cx))
1163 .await
1164 .unwrap();
1165 worktree_a
1166 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1167 .await;
1168 let project_id = project_a
1169 .update(&mut cx_a, |project, _| project.next_remote_id())
1170 .await;
1171 project_a
1172 .update(&mut cx_a, |project, cx| project.share(cx))
1173 .await
1174 .unwrap();
1175
1176 // Join that project as client B
1177 let project_b = Project::remote(
1178 project_id,
1179 client_b.clone(),
1180 client_b.user_store.clone(),
1181 lang_registry.clone(),
1182 fs.clone(),
1183 &mut cx_b.to_async(),
1184 )
1185 .await
1186 .unwrap();
1187 let worktree_b = project_b.update(&mut cx_b, |p, _| p.worktrees()[0].clone());
1188
1189 let replica_id_b = project_b.read_with(&cx_b, |project, _| {
1190 assert_eq!(
1191 project
1192 .collaborators()
1193 .get(&client_a.peer_id)
1194 .unwrap()
1195 .user
1196 .github_login,
1197 "user_a"
1198 );
1199 project.replica_id()
1200 });
1201 project_a
1202 .condition(&cx_a, |tree, _| {
1203 tree.collaborators()
1204 .get(&client_b.peer_id)
1205 .map_or(false, |collaborator| {
1206 collaborator.replica_id == replica_id_b
1207 && collaborator.user.github_login == "user_b"
1208 })
1209 })
1210 .await;
1211
1212 // Open the same file as client B and client A.
1213 let buffer_b = worktree_b
1214 .update(&mut cx_b, |worktree, cx| worktree.open_buffer("b.txt", cx))
1215 .await
1216 .unwrap();
1217 let buffer_b = cx_b.add_model(|cx| MultiBuffer::singleton(buffer_b, cx));
1218 buffer_b.read_with(&cx_b, |buf, cx| {
1219 assert_eq!(buf.read(cx).text(), "b-contents")
1220 });
1221 worktree_a.read_with(&cx_a, |tree, cx| assert!(tree.has_open_buffer("b.txt", cx)));
1222 let buffer_a = worktree_a
1223 .update(&mut cx_a, |tree, cx| tree.open_buffer("b.txt", cx))
1224 .await
1225 .unwrap();
1226
1227 let editor_b = cx_b.add_view(window_b, |cx| {
1228 Editor::for_buffer(buffer_b, Arc::new(|cx| EditorSettings::test(cx)), cx)
1229 });
1230 // TODO
1231 // // Create a selection set as client B and see that selection set as client A.
1232 // buffer_a
1233 // .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 1)
1234 // .await;
1235
1236 // Edit the buffer as client B and see that edit as client A.
1237 editor_b.update(&mut cx_b, |editor, cx| {
1238 editor.handle_input(&Input("ok, ".into()), cx)
1239 });
1240 buffer_a
1241 .condition(&cx_a, |buffer, _| buffer.text() == "ok, b-contents")
1242 .await;
1243
1244 // TODO
1245 // // Remove the selection set as client B, see those selections disappear as client A.
1246 cx_b.update(move |_| drop(editor_b));
1247 // buffer_a
1248 // .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 0)
1249 // .await;
1250
1251 // Close the buffer as client A, see that the buffer is closed.
1252 cx_a.update(move |_| drop(buffer_a));
1253 worktree_a
1254 .condition(&cx_a, |tree, cx| !tree.has_open_buffer("b.txt", cx))
1255 .await;
1256
1257 // Dropping the client B's project removes client B from client A's collaborators.
1258 cx_b.update(move |_| drop(project_b));
1259 project_a
1260 .condition(&cx_a, |project, _| project.collaborators().is_empty())
1261 .await;
1262 }
1263
1264 #[gpui::test]
1265 async fn test_unshare_project(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1266 let lang_registry = Arc::new(LanguageRegistry::new());
1267 let fs = Arc::new(FakeFs::new());
1268 cx_a.foreground().forbid_parking();
1269
1270 // Connect to a server as 2 clients.
1271 let mut server = TestServer::start(cx_a.foreground()).await;
1272 let client_a = server.create_client(&mut cx_a, "user_a").await;
1273 let client_b = server.create_client(&mut cx_b, "user_b").await;
1274
1275 // Share a project as client A
1276 fs.insert_tree(
1277 "/a",
1278 json!({
1279 ".zed.toml": r#"collaborators = ["user_b"]"#,
1280 "a.txt": "a-contents",
1281 "b.txt": "b-contents",
1282 }),
1283 )
1284 .await;
1285 let project_a = cx_a.update(|cx| {
1286 Project::local(
1287 client_a.clone(),
1288 client_a.user_store.clone(),
1289 lang_registry.clone(),
1290 fs.clone(),
1291 cx,
1292 )
1293 });
1294 let worktree_a = project_a
1295 .update(&mut cx_a, |p, cx| p.add_local_worktree("/a", cx))
1296 .await
1297 .unwrap();
1298 worktree_a
1299 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1300 .await;
1301 let project_id = project_a
1302 .update(&mut cx_a, |project, _| project.next_remote_id())
1303 .await;
1304 project_a
1305 .update(&mut cx_a, |project, cx| project.share(cx))
1306 .await
1307 .unwrap();
1308
1309 // Join that project as client B
1310 let project_b = Project::remote(
1311 project_id,
1312 client_b.clone(),
1313 client_b.user_store.clone(),
1314 lang_registry.clone(),
1315 fs.clone(),
1316 &mut cx_b.to_async(),
1317 )
1318 .await
1319 .unwrap();
1320
1321 let worktree_b = project_b.read_with(&cx_b, |p, _| p.worktrees()[0].clone());
1322 worktree_b
1323 .update(&mut cx_b, |tree, cx| tree.open_buffer("a.txt", cx))
1324 .await
1325 .unwrap();
1326
1327 project_a
1328 .update(&mut cx_a, |project, cx| project.unshare(cx))
1329 .await
1330 .unwrap();
1331 project_b
1332 .condition(&mut cx_b, |project, _| project.is_read_only())
1333 .await;
1334 }
1335
1336 #[gpui::test]
1337 async fn test_propagate_saves_and_fs_changes(
1338 mut cx_a: TestAppContext,
1339 mut cx_b: TestAppContext,
1340 mut cx_c: TestAppContext,
1341 ) {
1342 let lang_registry = Arc::new(LanguageRegistry::new());
1343 let fs = Arc::new(FakeFs::new());
1344 cx_a.foreground().forbid_parking();
1345
1346 // Connect to a server as 3 clients.
1347 let mut server = TestServer::start(cx_a.foreground()).await;
1348 let client_a = server.create_client(&mut cx_a, "user_a").await;
1349 let client_b = server.create_client(&mut cx_b, "user_b").await;
1350 let client_c = server.create_client(&mut cx_c, "user_c").await;
1351
1352 // Share a worktree as client A.
1353 fs.insert_tree(
1354 "/a",
1355 json!({
1356 ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
1357 "file1": "",
1358 "file2": ""
1359 }),
1360 )
1361 .await;
1362 let project_a = cx_a.update(|cx| {
1363 Project::local(
1364 client_a.clone(),
1365 client_a.user_store.clone(),
1366 lang_registry.clone(),
1367 fs.clone(),
1368 cx,
1369 )
1370 });
1371 let worktree_a = project_a
1372 .update(&mut cx_a, |p, cx| p.add_local_worktree("/a", cx))
1373 .await
1374 .unwrap();
1375 worktree_a
1376 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1377 .await;
1378 let project_id = project_a
1379 .update(&mut cx_a, |project, _| project.next_remote_id())
1380 .await;
1381 project_a
1382 .update(&mut cx_a, |project, cx| project.share(cx))
1383 .await
1384 .unwrap();
1385
1386 // Join that worktree as clients B and C.
1387 let project_b = Project::remote(
1388 project_id,
1389 client_b.clone(),
1390 client_b.user_store.clone(),
1391 lang_registry.clone(),
1392 fs.clone(),
1393 &mut cx_b.to_async(),
1394 )
1395 .await
1396 .unwrap();
1397 let project_c = Project::remote(
1398 project_id,
1399 client_c.clone(),
1400 client_c.user_store.clone(),
1401 lang_registry.clone(),
1402 fs.clone(),
1403 &mut cx_c.to_async(),
1404 )
1405 .await
1406 .unwrap();
1407
1408 // Open and edit a buffer as both guests B and C.
1409 let worktree_b = project_b.read_with(&cx_b, |p, _| p.worktrees()[0].clone());
1410 let worktree_c = project_c.read_with(&cx_c, |p, _| p.worktrees()[0].clone());
1411 let buffer_b = worktree_b
1412 .update(&mut cx_b, |tree, cx| tree.open_buffer("file1", cx))
1413 .await
1414 .unwrap();
1415 let buffer_c = worktree_c
1416 .update(&mut cx_c, |tree, cx| tree.open_buffer("file1", cx))
1417 .await
1418 .unwrap();
1419 buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "i-am-b, ", cx));
1420 buffer_c.update(&mut cx_c, |buf, cx| buf.edit([0..0], "i-am-c, ", cx));
1421
1422 // Open and edit that buffer as the host.
1423 let buffer_a = worktree_a
1424 .update(&mut cx_a, |tree, cx| tree.open_buffer("file1", cx))
1425 .await
1426 .unwrap();
1427
1428 buffer_a
1429 .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, ")
1430 .await;
1431 buffer_a.update(&mut cx_a, |buf, cx| {
1432 buf.edit([buf.len()..buf.len()], "i-am-a", cx)
1433 });
1434
1435 // Wait for edits to propagate
1436 buffer_a
1437 .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1438 .await;
1439 buffer_b
1440 .condition(&mut cx_b, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1441 .await;
1442 buffer_c
1443 .condition(&mut cx_c, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1444 .await;
1445
1446 // Edit the buffer as the host and concurrently save as guest B.
1447 let save_b = buffer_b.update(&mut cx_b, |buf, cx| buf.save(cx).unwrap());
1448 buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "hi-a, ", cx));
1449 save_b.await.unwrap();
1450 assert_eq!(
1451 fs.load("/a/file1".as_ref()).await.unwrap(),
1452 "hi-a, i-am-c, i-am-b, i-am-a"
1453 );
1454 buffer_a.read_with(&cx_a, |buf, _| assert!(!buf.is_dirty()));
1455 buffer_b.read_with(&cx_b, |buf, _| assert!(!buf.is_dirty()));
1456 buffer_c.condition(&cx_c, |buf, _| !buf.is_dirty()).await;
1457
1458 // Make changes on host's file system, see those changes on the guests.
1459 fs.rename("/a/file2".as_ref(), "/a/file3".as_ref())
1460 .await
1461 .unwrap();
1462 fs.insert_file(Path::new("/a/file4"), "4".into())
1463 .await
1464 .unwrap();
1465
1466 worktree_b
1467 .condition(&cx_b, |tree, _| tree.file_count() == 4)
1468 .await;
1469 worktree_c
1470 .condition(&cx_c, |tree, _| tree.file_count() == 4)
1471 .await;
1472 worktree_b.read_with(&cx_b, |tree, _| {
1473 assert_eq!(
1474 tree.paths()
1475 .map(|p| p.to_string_lossy())
1476 .collect::<Vec<_>>(),
1477 &[".zed.toml", "file1", "file3", "file4"]
1478 )
1479 });
1480 worktree_c.read_with(&cx_c, |tree, _| {
1481 assert_eq!(
1482 tree.paths()
1483 .map(|p| p.to_string_lossy())
1484 .collect::<Vec<_>>(),
1485 &[".zed.toml", "file1", "file3", "file4"]
1486 )
1487 });
1488 }
1489
1490 #[gpui::test]
1491 async fn test_buffer_conflict_after_save(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1492 cx_a.foreground().forbid_parking();
1493 let lang_registry = Arc::new(LanguageRegistry::new());
1494 let fs = Arc::new(FakeFs::new());
1495
1496 // Connect to a server as 2 clients.
1497 let mut server = TestServer::start(cx_a.foreground()).await;
1498 let client_a = server.create_client(&mut cx_a, "user_a").await;
1499 let client_b = server.create_client(&mut cx_b, "user_b").await;
1500
1501 // Share a project as client A
1502 fs.insert_tree(
1503 "/dir",
1504 json!({
1505 ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
1506 "a.txt": "a-contents",
1507 }),
1508 )
1509 .await;
1510
1511 let project_a = cx_a.update(|cx| {
1512 Project::local(
1513 client_a.clone(),
1514 client_a.user_store.clone(),
1515 lang_registry.clone(),
1516 fs.clone(),
1517 cx,
1518 )
1519 });
1520 let worktree_a = project_a
1521 .update(&mut cx_a, |p, cx| p.add_local_worktree("/dir", cx))
1522 .await
1523 .unwrap();
1524 worktree_a
1525 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1526 .await;
1527 let project_id = project_a
1528 .update(&mut cx_a, |project, _| project.next_remote_id())
1529 .await;
1530 project_a
1531 .update(&mut cx_a, |project, cx| project.share(cx))
1532 .await
1533 .unwrap();
1534
1535 // Join that project as client B
1536 let project_b = Project::remote(
1537 project_id,
1538 client_b.clone(),
1539 client_b.user_store.clone(),
1540 lang_registry.clone(),
1541 fs.clone(),
1542 &mut cx_b.to_async(),
1543 )
1544 .await
1545 .unwrap();
1546 let worktree_b = project_b.update(&mut cx_b, |p, _| p.worktrees()[0].clone());
1547
1548 // Open a buffer as client B
1549 let buffer_b = worktree_b
1550 .update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx))
1551 .await
1552 .unwrap();
1553 let mtime = buffer_b.read_with(&cx_b, |buf, _| buf.file().unwrap().mtime());
1554
1555 buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "world ", cx));
1556 buffer_b.read_with(&cx_b, |buf, _| {
1557 assert!(buf.is_dirty());
1558 assert!(!buf.has_conflict());
1559 });
1560
1561 buffer_b
1562 .update(&mut cx_b, |buf, cx| buf.save(cx))
1563 .unwrap()
1564 .await
1565 .unwrap();
1566 worktree_b
1567 .condition(&cx_b, |_, cx| {
1568 buffer_b.read(cx).file().unwrap().mtime() != mtime
1569 })
1570 .await;
1571 buffer_b.read_with(&cx_b, |buf, _| {
1572 assert!(!buf.is_dirty());
1573 assert!(!buf.has_conflict());
1574 });
1575
1576 buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "hello ", cx));
1577 buffer_b.read_with(&cx_b, |buf, _| {
1578 assert!(buf.is_dirty());
1579 assert!(!buf.has_conflict());
1580 });
1581 }
1582
1583 #[gpui::test]
1584 async fn test_editing_while_guest_opens_buffer(
1585 mut cx_a: TestAppContext,
1586 mut cx_b: TestAppContext,
1587 ) {
1588 cx_a.foreground().forbid_parking();
1589 let lang_registry = Arc::new(LanguageRegistry::new());
1590 let fs = Arc::new(FakeFs::new());
1591
1592 // Connect to a server as 2 clients.
1593 let mut server = TestServer::start(cx_a.foreground()).await;
1594 let client_a = server.create_client(&mut cx_a, "user_a").await;
1595 let client_b = server.create_client(&mut cx_b, "user_b").await;
1596
1597 // Share a project as client A
1598 fs.insert_tree(
1599 "/dir",
1600 json!({
1601 ".zed.toml": r#"collaborators = ["user_b"]"#,
1602 "a.txt": "a-contents",
1603 }),
1604 )
1605 .await;
1606 let project_a = cx_a.update(|cx| {
1607 Project::local(
1608 client_a.clone(),
1609 client_a.user_store.clone(),
1610 lang_registry.clone(),
1611 fs.clone(),
1612 cx,
1613 )
1614 });
1615 let worktree_a = project_a
1616 .update(&mut cx_a, |p, cx| p.add_local_worktree("/dir", cx))
1617 .await
1618 .unwrap();
1619 worktree_a
1620 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1621 .await;
1622 let project_id = project_a
1623 .update(&mut cx_a, |project, _| project.next_remote_id())
1624 .await;
1625 project_a
1626 .update(&mut cx_a, |project, cx| project.share(cx))
1627 .await
1628 .unwrap();
1629
1630 // Join that project as client B
1631 let project_b = Project::remote(
1632 project_id,
1633 client_b.clone(),
1634 client_b.user_store.clone(),
1635 lang_registry.clone(),
1636 fs.clone(),
1637 &mut cx_b.to_async(),
1638 )
1639 .await
1640 .unwrap();
1641 let worktree_b = project_b.update(&mut cx_b, |p, _| p.worktrees()[0].clone());
1642
1643 // Open a buffer as client A
1644 let buffer_a = worktree_a
1645 .update(&mut cx_a, |tree, cx| tree.open_buffer("a.txt", cx))
1646 .await
1647 .unwrap();
1648
1649 // Start opening the same buffer as client B
1650 let buffer_b = cx_b
1651 .background()
1652 .spawn(worktree_b.update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx)));
1653 task::yield_now().await;
1654
1655 // Edit the buffer as client A while client B is still opening it.
1656 buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "z", cx));
1657
1658 let text = buffer_a.read_with(&cx_a, |buf, _| buf.text());
1659 let buffer_b = buffer_b.await.unwrap();
1660 buffer_b.condition(&cx_b, |buf, _| buf.text() == text).await;
1661 }
1662
1663 #[gpui::test]
1664 async fn test_leaving_worktree_while_opening_buffer(
1665 mut cx_a: TestAppContext,
1666 mut cx_b: TestAppContext,
1667 ) {
1668 cx_a.foreground().forbid_parking();
1669 let lang_registry = Arc::new(LanguageRegistry::new());
1670 let fs = Arc::new(FakeFs::new());
1671
1672 // Connect to a server as 2 clients.
1673 let mut server = TestServer::start(cx_a.foreground()).await;
1674 let client_a = server.create_client(&mut cx_a, "user_a").await;
1675 let client_b = server.create_client(&mut cx_b, "user_b").await;
1676
1677 // Share a project as client A
1678 fs.insert_tree(
1679 "/dir",
1680 json!({
1681 ".zed.toml": r#"collaborators = ["user_b"]"#,
1682 "a.txt": "a-contents",
1683 }),
1684 )
1685 .await;
1686 let project_a = cx_a.update(|cx| {
1687 Project::local(
1688 client_a.clone(),
1689 client_a.user_store.clone(),
1690 lang_registry.clone(),
1691 fs.clone(),
1692 cx,
1693 )
1694 });
1695 let worktree_a = project_a
1696 .update(&mut cx_a, |p, cx| p.add_local_worktree("/dir", cx))
1697 .await
1698 .unwrap();
1699 worktree_a
1700 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1701 .await;
1702 let project_id = project_a
1703 .update(&mut cx_a, |project, _| project.next_remote_id())
1704 .await;
1705 project_a
1706 .update(&mut cx_a, |project, cx| project.share(cx))
1707 .await
1708 .unwrap();
1709
1710 // Join that project as client B
1711 let project_b = Project::remote(
1712 project_id,
1713 client_b.clone(),
1714 client_b.user_store.clone(),
1715 lang_registry.clone(),
1716 fs.clone(),
1717 &mut cx_b.to_async(),
1718 )
1719 .await
1720 .unwrap();
1721 let worktree_b = project_b.update(&mut cx_b, |p, _| p.worktrees()[0].clone());
1722
1723 // See that a guest has joined as client A.
1724 project_a
1725 .condition(&cx_a, |p, _| p.collaborators().len() == 1)
1726 .await;
1727
1728 // Begin opening a buffer as client B, but leave the project before the open completes.
1729 let buffer_b = cx_b
1730 .background()
1731 .spawn(worktree_b.update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx)));
1732 cx_b.update(|_| drop(project_b));
1733 drop(buffer_b);
1734
1735 // See that the guest has left.
1736 project_a
1737 .condition(&cx_a, |p, _| p.collaborators().len() == 0)
1738 .await;
1739 }
1740
1741 #[gpui::test]
1742 async fn test_peer_disconnection(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1743 cx_a.foreground().forbid_parking();
1744 let lang_registry = Arc::new(LanguageRegistry::new());
1745 let fs = Arc::new(FakeFs::new());
1746
1747 // Connect to a server as 2 clients.
1748 let mut server = TestServer::start(cx_a.foreground()).await;
1749 let client_a = server.create_client(&mut cx_a, "user_a").await;
1750 let client_b = server.create_client(&mut cx_b, "user_b").await;
1751
1752 // Share a project as client A
1753 fs.insert_tree(
1754 "/a",
1755 json!({
1756 ".zed.toml": r#"collaborators = ["user_b"]"#,
1757 "a.txt": "a-contents",
1758 "b.txt": "b-contents",
1759 }),
1760 )
1761 .await;
1762 let project_a = cx_a.update(|cx| {
1763 Project::local(
1764 client_a.clone(),
1765 client_a.user_store.clone(),
1766 lang_registry.clone(),
1767 fs.clone(),
1768 cx,
1769 )
1770 });
1771 let worktree_a = project_a
1772 .update(&mut cx_a, |p, cx| p.add_local_worktree("/a", cx))
1773 .await
1774 .unwrap();
1775 worktree_a
1776 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1777 .await;
1778 let project_id = project_a
1779 .update(&mut cx_a, |project, _| project.next_remote_id())
1780 .await;
1781 project_a
1782 .update(&mut cx_a, |project, cx| project.share(cx))
1783 .await
1784 .unwrap();
1785
1786 // Join that project as client B
1787 let _project_b = Project::remote(
1788 project_id,
1789 client_b.clone(),
1790 client_b.user_store.clone(),
1791 lang_registry.clone(),
1792 fs.clone(),
1793 &mut cx_b.to_async(),
1794 )
1795 .await
1796 .unwrap();
1797
1798 // See that a guest has joined as client A.
1799 project_a
1800 .condition(&cx_a, |p, _| p.collaborators().len() == 1)
1801 .await;
1802
1803 // Drop client B's connection and ensure client A observes client B leaving the worktree.
1804 client_b.disconnect(&cx_b.to_async()).await.unwrap();
1805 project_a
1806 .condition(&cx_a, |p, _| p.collaborators().len() == 0)
1807 .await;
1808 }
1809
1810 #[gpui::test]
1811 async fn test_collaborating_with_diagnostics(
1812 mut cx_a: TestAppContext,
1813 mut cx_b: TestAppContext,
1814 ) {
1815 cx_a.foreground().forbid_parking();
1816 let mut lang_registry = Arc::new(LanguageRegistry::new());
1817 let fs = Arc::new(FakeFs::new());
1818
1819 // Set up a fake language server.
1820 let (language_server_config, mut fake_language_server) =
1821 LanguageServerConfig::fake(cx_a.background()).await;
1822 Arc::get_mut(&mut lang_registry)
1823 .unwrap()
1824 .add(Arc::new(Language::new(
1825 LanguageConfig {
1826 name: "Rust".to_string(),
1827 path_suffixes: vec!["rs".to_string()],
1828 language_server: Some(language_server_config),
1829 ..Default::default()
1830 },
1831 Some(tree_sitter_rust::language()),
1832 )));
1833
1834 // Connect to a server as 2 clients.
1835 let mut server = TestServer::start(cx_a.foreground()).await;
1836 let client_a = server.create_client(&mut cx_a, "user_a").await;
1837 let client_b = server.create_client(&mut cx_b, "user_b").await;
1838
1839 // Share a project as client A
1840 fs.insert_tree(
1841 "/a",
1842 json!({
1843 ".zed.toml": r#"collaborators = ["user_b"]"#,
1844 "a.rs": "let one = two",
1845 "other.rs": "",
1846 }),
1847 )
1848 .await;
1849 let project_a = cx_a.update(|cx| {
1850 Project::local(
1851 client_a.clone(),
1852 client_a.user_store.clone(),
1853 lang_registry.clone(),
1854 fs.clone(),
1855 cx,
1856 )
1857 });
1858 let worktree_a = project_a
1859 .update(&mut cx_a, |p, cx| p.add_local_worktree("/a", cx))
1860 .await
1861 .unwrap();
1862 worktree_a
1863 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1864 .await;
1865 let project_id = project_a
1866 .update(&mut cx_a, |project, _| project.next_remote_id())
1867 .await;
1868 let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1869 project_a
1870 .update(&mut cx_a, |project, cx| project.share(cx))
1871 .await
1872 .unwrap();
1873
1874 // Cause the language server to start.
1875 let _ = cx_a
1876 .background()
1877 .spawn(worktree_a.update(&mut cx_a, |worktree, cx| {
1878 worktree.open_buffer("other.rs", cx)
1879 }))
1880 .await
1881 .unwrap();
1882
1883 // Simulate a language server reporting errors for a file.
1884 fake_language_server
1885 .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
1886 uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
1887 version: None,
1888 diagnostics: vec![lsp::Diagnostic {
1889 severity: Some(lsp::DiagnosticSeverity::ERROR),
1890 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
1891 message: "message 1".to_string(),
1892 ..Default::default()
1893 }],
1894 })
1895 .await;
1896
1897 // Wait for server to see the diagnostics update.
1898 server
1899 .condition(|store| {
1900 let worktree = store
1901 .project(project_id)
1902 .unwrap()
1903 .worktrees
1904 .get(&worktree_id.to_proto())
1905 .unwrap();
1906
1907 !worktree
1908 .share
1909 .as_ref()
1910 .unwrap()
1911 .diagnostic_summaries
1912 .is_empty()
1913 })
1914 .await;
1915
1916 // Join the worktree as client B.
1917 let project_b = Project::remote(
1918 project_id,
1919 client_b.clone(),
1920 client_b.user_store.clone(),
1921 lang_registry.clone(),
1922 fs.clone(),
1923 &mut cx_b.to_async(),
1924 )
1925 .await
1926 .unwrap();
1927
1928 project_b.read_with(&cx_b, |project, cx| {
1929 assert_eq!(
1930 project.diagnostic_summaries(cx).collect::<Vec<_>>(),
1931 &[(
1932 ProjectPath {
1933 worktree_id,
1934 path: Arc::from(Path::new("a.rs")),
1935 },
1936 DiagnosticSummary {
1937 error_count: 1,
1938 warning_count: 0,
1939 ..Default::default()
1940 },
1941 )]
1942 )
1943 });
1944
1945 // Simulate a language server reporting more errors for a file.
1946 fake_language_server
1947 .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
1948 uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
1949 version: None,
1950 diagnostics: vec![
1951 lsp::Diagnostic {
1952 severity: Some(lsp::DiagnosticSeverity::ERROR),
1953 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
1954 message: "message 1".to_string(),
1955 ..Default::default()
1956 },
1957 lsp::Diagnostic {
1958 severity: Some(lsp::DiagnosticSeverity::WARNING),
1959 range: lsp::Range::new(
1960 lsp::Position::new(0, 10),
1961 lsp::Position::new(0, 13),
1962 ),
1963 message: "message 2".to_string(),
1964 ..Default::default()
1965 },
1966 ],
1967 })
1968 .await;
1969
1970 // Client b gets the updated summaries
1971 project_b
1972 .condition(&cx_b, |project, cx| {
1973 project.diagnostic_summaries(cx).collect::<Vec<_>>()
1974 == &[(
1975 ProjectPath {
1976 worktree_id,
1977 path: Arc::from(Path::new("a.rs")),
1978 },
1979 DiagnosticSummary {
1980 error_count: 1,
1981 warning_count: 1,
1982 ..Default::default()
1983 },
1984 )]
1985 })
1986 .await;
1987
1988 // Open the file with the errors on client B. They should be present.
1989 let worktree_b = project_b.update(&mut cx_b, |p, _| p.worktrees()[0].clone());
1990 let buffer_b = cx_b
1991 .background()
1992 .spawn(worktree_b.update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.rs", cx)))
1993 .await
1994 .unwrap();
1995
1996 buffer_b.read_with(&cx_b, |buffer, _| {
1997 assert_eq!(
1998 buffer
1999 .snapshot()
2000 .diagnostics_in_range::<_, Point>(0..buffer.len())
2001 .map(|entry| entry)
2002 .collect::<Vec<_>>(),
2003 &[
2004 DiagnosticEntry {
2005 range: Point::new(0, 4)..Point::new(0, 7),
2006 diagnostic: Diagnostic {
2007 group_id: 0,
2008 message: "message 1".to_string(),
2009 severity: lsp::DiagnosticSeverity::ERROR,
2010 is_primary: true,
2011 ..Default::default()
2012 }
2013 },
2014 DiagnosticEntry {
2015 range: Point::new(0, 10)..Point::new(0, 13),
2016 diagnostic: Diagnostic {
2017 group_id: 1,
2018 severity: lsp::DiagnosticSeverity::WARNING,
2019 message: "message 2".to_string(),
2020 is_primary: true,
2021 ..Default::default()
2022 }
2023 }
2024 ]
2025 );
2026 });
2027 }
2028
2029 #[gpui::test(iterations = 1, seed = 2)]
2030 async fn test_formatting_buffer(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
2031 cx_a.foreground().forbid_parking();
2032 let mut lang_registry = Arc::new(LanguageRegistry::new());
2033 let fs = Arc::new(FakeFs::new());
2034
2035 // Set up a fake language server.
2036 let (language_server_config, mut fake_language_server) =
2037 LanguageServerConfig::fake(cx_a.background()).await;
2038 Arc::get_mut(&mut lang_registry)
2039 .unwrap()
2040 .add(Arc::new(Language::new(
2041 LanguageConfig {
2042 name: "Rust".to_string(),
2043 path_suffixes: vec!["rs".to_string()],
2044 language_server: Some(language_server_config),
2045 ..Default::default()
2046 },
2047 Some(tree_sitter_rust::language()),
2048 )));
2049
2050 // Connect to a server as 2 clients.
2051 let mut server = TestServer::start(cx_a.foreground()).await;
2052 let client_a = server.create_client(&mut cx_a, "user_a").await;
2053 let client_b = server.create_client(&mut cx_b, "user_b").await;
2054
2055 // Share a project as client A
2056 fs.insert_tree(
2057 "/a",
2058 json!({
2059 ".zed.toml": r#"collaborators = ["user_b"]"#,
2060 "a.rs": "let one = two",
2061 }),
2062 )
2063 .await;
2064 let project_a = cx_a.update(|cx| {
2065 Project::local(
2066 client_a.clone(),
2067 client_a.user_store.clone(),
2068 lang_registry.clone(),
2069 fs.clone(),
2070 cx,
2071 )
2072 });
2073 let worktree_a = project_a
2074 .update(&mut cx_a, |p, cx| p.add_local_worktree("/a", cx))
2075 .await
2076 .unwrap();
2077 worktree_a
2078 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2079 .await;
2080 let project_id = project_a
2081 .update(&mut cx_a, |project, _| project.next_remote_id())
2082 .await;
2083 project_a
2084 .update(&mut cx_a, |project, cx| project.share(cx))
2085 .await
2086 .unwrap();
2087
2088 // Join the worktree as client B.
2089 let project_b = Project::remote(
2090 project_id,
2091 client_b.clone(),
2092 client_b.user_store.clone(),
2093 lang_registry.clone(),
2094 fs.clone(),
2095 &mut cx_b.to_async(),
2096 )
2097 .await
2098 .unwrap();
2099
2100 // Open the file to be formatted on client B.
2101 let worktree_b = project_b.update(&mut cx_b, |p, _| p.worktrees()[0].clone());
2102 let buffer_b = cx_b
2103 .background()
2104 .spawn(worktree_b.update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.rs", cx)))
2105 .await
2106 .unwrap();
2107
2108 let format = buffer_b.update(&mut cx_b, |buffer, cx| buffer.format(cx));
2109 let (request_id, _) = fake_language_server
2110 .receive_request::<lsp::request::Formatting>()
2111 .await;
2112 fake_language_server
2113 .respond(
2114 request_id,
2115 Some(vec![
2116 lsp::TextEdit {
2117 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 4)),
2118 new_text: "h".to_string(),
2119 },
2120 lsp::TextEdit {
2121 range: lsp::Range::new(lsp::Position::new(0, 7), lsp::Position::new(0, 7)),
2122 new_text: "y".to_string(),
2123 },
2124 ]),
2125 )
2126 .await;
2127 format.await.unwrap();
2128 assert_eq!(
2129 buffer_b.read_with(&cx_b, |buffer, _| buffer.text()),
2130 "let honey = two"
2131 );
2132 }
2133
2134 #[gpui::test]
2135 async fn test_basic_chat(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
2136 cx_a.foreground().forbid_parking();
2137
2138 // Connect to a server as 2 clients.
2139 let mut server = TestServer::start(cx_a.foreground()).await;
2140 let client_a = server.create_client(&mut cx_a, "user_a").await;
2141 let client_b = server.create_client(&mut cx_b, "user_b").await;
2142
2143 // Create an org that includes these 2 users.
2144 let db = &server.app_state.db;
2145 let org_id = db.create_org("Test Org", "test-org").await.unwrap();
2146 db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
2147 .await
2148 .unwrap();
2149 db.add_org_member(org_id, client_b.current_user_id(&cx_b), false)
2150 .await
2151 .unwrap();
2152
2153 // Create a channel that includes all the users.
2154 let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
2155 db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
2156 .await
2157 .unwrap();
2158 db.add_channel_member(channel_id, client_b.current_user_id(&cx_b), false)
2159 .await
2160 .unwrap();
2161 db.create_channel_message(
2162 channel_id,
2163 client_b.current_user_id(&cx_b),
2164 "hello A, it's B.",
2165 OffsetDateTime::now_utc(),
2166 1,
2167 )
2168 .await
2169 .unwrap();
2170
2171 let channels_a = cx_a
2172 .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
2173 channels_a
2174 .condition(&mut cx_a, |list, _| list.available_channels().is_some())
2175 .await;
2176 channels_a.read_with(&cx_a, |list, _| {
2177 assert_eq!(
2178 list.available_channels().unwrap(),
2179 &[ChannelDetails {
2180 id: channel_id.to_proto(),
2181 name: "test-channel".to_string()
2182 }]
2183 )
2184 });
2185 let channel_a = channels_a.update(&mut cx_a, |this, cx| {
2186 this.get_channel(channel_id.to_proto(), cx).unwrap()
2187 });
2188 channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
2189 channel_a
2190 .condition(&cx_a, |channel, _| {
2191 channel_messages(channel)
2192 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2193 })
2194 .await;
2195
2196 let channels_b = cx_b
2197 .add_model(|cx| ChannelList::new(client_b.user_store.clone(), client_b.clone(), cx));
2198 channels_b
2199 .condition(&mut cx_b, |list, _| list.available_channels().is_some())
2200 .await;
2201 channels_b.read_with(&cx_b, |list, _| {
2202 assert_eq!(
2203 list.available_channels().unwrap(),
2204 &[ChannelDetails {
2205 id: channel_id.to_proto(),
2206 name: "test-channel".to_string()
2207 }]
2208 )
2209 });
2210
2211 let channel_b = channels_b.update(&mut cx_b, |this, cx| {
2212 this.get_channel(channel_id.to_proto(), cx).unwrap()
2213 });
2214 channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
2215 channel_b
2216 .condition(&cx_b, |channel, _| {
2217 channel_messages(channel)
2218 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2219 })
2220 .await;
2221
2222 channel_a
2223 .update(&mut cx_a, |channel, cx| {
2224 channel
2225 .send_message("oh, hi B.".to_string(), cx)
2226 .unwrap()
2227 .detach();
2228 let task = channel.send_message("sup".to_string(), cx).unwrap();
2229 assert_eq!(
2230 channel_messages(channel),
2231 &[
2232 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2233 ("user_a".to_string(), "oh, hi B.".to_string(), true),
2234 ("user_a".to_string(), "sup".to_string(), true)
2235 ]
2236 );
2237 task
2238 })
2239 .await
2240 .unwrap();
2241
2242 channel_b
2243 .condition(&cx_b, |channel, _| {
2244 channel_messages(channel)
2245 == [
2246 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2247 ("user_a".to_string(), "oh, hi B.".to_string(), false),
2248 ("user_a".to_string(), "sup".to_string(), false),
2249 ]
2250 })
2251 .await;
2252
2253 assert_eq!(
2254 server
2255 .state()
2256 .await
2257 .channel(channel_id)
2258 .unwrap()
2259 .connection_ids
2260 .len(),
2261 2
2262 );
2263 cx_b.update(|_| drop(channel_b));
2264 server
2265 .condition(|state| state.channel(channel_id).unwrap().connection_ids.len() == 1)
2266 .await;
2267
2268 cx_a.update(|_| drop(channel_a));
2269 server
2270 .condition(|state| state.channel(channel_id).is_none())
2271 .await;
2272 }
2273
2274 #[gpui::test]
2275 async fn test_chat_message_validation(mut cx_a: TestAppContext) {
2276 cx_a.foreground().forbid_parking();
2277
2278 let mut server = TestServer::start(cx_a.foreground()).await;
2279 let client_a = server.create_client(&mut cx_a, "user_a").await;
2280
2281 let db = &server.app_state.db;
2282 let org_id = db.create_org("Test Org", "test-org").await.unwrap();
2283 let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
2284 db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
2285 .await
2286 .unwrap();
2287 db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
2288 .await
2289 .unwrap();
2290
2291 let channels_a = cx_a
2292 .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
2293 channels_a
2294 .condition(&mut cx_a, |list, _| list.available_channels().is_some())
2295 .await;
2296 let channel_a = channels_a.update(&mut cx_a, |this, cx| {
2297 this.get_channel(channel_id.to_proto(), cx).unwrap()
2298 });
2299
2300 // Messages aren't allowed to be too long.
2301 channel_a
2302 .update(&mut cx_a, |channel, cx| {
2303 let long_body = "this is long.\n".repeat(1024);
2304 channel.send_message(long_body, cx).unwrap()
2305 })
2306 .await
2307 .unwrap_err();
2308
2309 // Messages aren't allowed to be blank.
2310 channel_a.update(&mut cx_a, |channel, cx| {
2311 channel.send_message(String::new(), cx).unwrap_err()
2312 });
2313
2314 // Leading and trailing whitespace are trimmed.
2315 channel_a
2316 .update(&mut cx_a, |channel, cx| {
2317 channel
2318 .send_message("\n surrounded by whitespace \n".to_string(), cx)
2319 .unwrap()
2320 })
2321 .await
2322 .unwrap();
2323 assert_eq!(
2324 db.get_channel_messages(channel_id, 10, None)
2325 .await
2326 .unwrap()
2327 .iter()
2328 .map(|m| &m.body)
2329 .collect::<Vec<_>>(),
2330 &["surrounded by whitespace"]
2331 );
2332 }
2333
2334 #[gpui::test]
2335 async fn test_chat_reconnection(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
2336 cx_a.foreground().forbid_parking();
2337
2338 // Connect to a server as 2 clients.
2339 let mut server = TestServer::start(cx_a.foreground()).await;
2340 let client_a = server.create_client(&mut cx_a, "user_a").await;
2341 let client_b = server.create_client(&mut cx_b, "user_b").await;
2342 let mut status_b = client_b.status();
2343
2344 // Create an org that includes these 2 users.
2345 let db = &server.app_state.db;
2346 let org_id = db.create_org("Test Org", "test-org").await.unwrap();
2347 db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
2348 .await
2349 .unwrap();
2350 db.add_org_member(org_id, client_b.current_user_id(&cx_b), false)
2351 .await
2352 .unwrap();
2353
2354 // Create a channel that includes all the users.
2355 let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
2356 db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
2357 .await
2358 .unwrap();
2359 db.add_channel_member(channel_id, client_b.current_user_id(&cx_b), false)
2360 .await
2361 .unwrap();
2362 db.create_channel_message(
2363 channel_id,
2364 client_b.current_user_id(&cx_b),
2365 "hello A, it's B.",
2366 OffsetDateTime::now_utc(),
2367 2,
2368 )
2369 .await
2370 .unwrap();
2371
2372 let channels_a = cx_a
2373 .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
2374 channels_a
2375 .condition(&mut cx_a, |list, _| list.available_channels().is_some())
2376 .await;
2377
2378 channels_a.read_with(&cx_a, |list, _| {
2379 assert_eq!(
2380 list.available_channels().unwrap(),
2381 &[ChannelDetails {
2382 id: channel_id.to_proto(),
2383 name: "test-channel".to_string()
2384 }]
2385 )
2386 });
2387 let channel_a = channels_a.update(&mut cx_a, |this, cx| {
2388 this.get_channel(channel_id.to_proto(), cx).unwrap()
2389 });
2390 channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
2391 channel_a
2392 .condition(&cx_a, |channel, _| {
2393 channel_messages(channel)
2394 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2395 })
2396 .await;
2397
2398 let channels_b = cx_b
2399 .add_model(|cx| ChannelList::new(client_b.user_store.clone(), client_b.clone(), cx));
2400 channels_b
2401 .condition(&mut cx_b, |list, _| list.available_channels().is_some())
2402 .await;
2403 channels_b.read_with(&cx_b, |list, _| {
2404 assert_eq!(
2405 list.available_channels().unwrap(),
2406 &[ChannelDetails {
2407 id: channel_id.to_proto(),
2408 name: "test-channel".to_string()
2409 }]
2410 )
2411 });
2412
2413 let channel_b = channels_b.update(&mut cx_b, |this, cx| {
2414 this.get_channel(channel_id.to_proto(), cx).unwrap()
2415 });
2416 channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
2417 channel_b
2418 .condition(&cx_b, |channel, _| {
2419 channel_messages(channel)
2420 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2421 })
2422 .await;
2423
2424 // Disconnect client B, ensuring we can still access its cached channel data.
2425 server.forbid_connections();
2426 server.disconnect_client(client_b.current_user_id(&cx_b));
2427 while !matches!(
2428 status_b.recv().await,
2429 Some(client::Status::ReconnectionError { .. })
2430 ) {}
2431
2432 channels_b.read_with(&cx_b, |channels, _| {
2433 assert_eq!(
2434 channels.available_channels().unwrap(),
2435 [ChannelDetails {
2436 id: channel_id.to_proto(),
2437 name: "test-channel".to_string()
2438 }]
2439 )
2440 });
2441 channel_b.read_with(&cx_b, |channel, _| {
2442 assert_eq!(
2443 channel_messages(channel),
2444 [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2445 )
2446 });
2447
2448 // Send a message from client B while it is disconnected.
2449 channel_b
2450 .update(&mut cx_b, |channel, cx| {
2451 let task = channel
2452 .send_message("can you see this?".to_string(), cx)
2453 .unwrap();
2454 assert_eq!(
2455 channel_messages(channel),
2456 &[
2457 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2458 ("user_b".to_string(), "can you see this?".to_string(), true)
2459 ]
2460 );
2461 task
2462 })
2463 .await
2464 .unwrap_err();
2465
2466 // Send a message from client A while B is disconnected.
2467 channel_a
2468 .update(&mut cx_a, |channel, cx| {
2469 channel
2470 .send_message("oh, hi B.".to_string(), cx)
2471 .unwrap()
2472 .detach();
2473 let task = channel.send_message("sup".to_string(), cx).unwrap();
2474 assert_eq!(
2475 channel_messages(channel),
2476 &[
2477 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2478 ("user_a".to_string(), "oh, hi B.".to_string(), true),
2479 ("user_a".to_string(), "sup".to_string(), true)
2480 ]
2481 );
2482 task
2483 })
2484 .await
2485 .unwrap();
2486
2487 // Give client B a chance to reconnect.
2488 server.allow_connections();
2489 cx_b.foreground().advance_clock(Duration::from_secs(10));
2490
2491 // Verify that B sees the new messages upon reconnection, as well as the message client B
2492 // sent while offline.
2493 channel_b
2494 .condition(&cx_b, |channel, _| {
2495 channel_messages(channel)
2496 == [
2497 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2498 ("user_a".to_string(), "oh, hi B.".to_string(), false),
2499 ("user_a".to_string(), "sup".to_string(), false),
2500 ("user_b".to_string(), "can you see this?".to_string(), false),
2501 ]
2502 })
2503 .await;
2504
2505 // Ensure client A and B can communicate normally after reconnection.
2506 channel_a
2507 .update(&mut cx_a, |channel, cx| {
2508 channel.send_message("you online?".to_string(), cx).unwrap()
2509 })
2510 .await
2511 .unwrap();
2512 channel_b
2513 .condition(&cx_b, |channel, _| {
2514 channel_messages(channel)
2515 == [
2516 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2517 ("user_a".to_string(), "oh, hi B.".to_string(), false),
2518 ("user_a".to_string(), "sup".to_string(), false),
2519 ("user_b".to_string(), "can you see this?".to_string(), false),
2520 ("user_a".to_string(), "you online?".to_string(), false),
2521 ]
2522 })
2523 .await;
2524
2525 channel_b
2526 .update(&mut cx_b, |channel, cx| {
2527 channel.send_message("yep".to_string(), cx).unwrap()
2528 })
2529 .await
2530 .unwrap();
2531 channel_a
2532 .condition(&cx_a, |channel, _| {
2533 channel_messages(channel)
2534 == [
2535 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2536 ("user_a".to_string(), "oh, hi B.".to_string(), false),
2537 ("user_a".to_string(), "sup".to_string(), false),
2538 ("user_b".to_string(), "can you see this?".to_string(), false),
2539 ("user_a".to_string(), "you online?".to_string(), false),
2540 ("user_b".to_string(), "yep".to_string(), false),
2541 ]
2542 })
2543 .await;
2544 }
2545
2546 #[gpui::test]
2547 async fn test_contacts(
2548 mut cx_a: TestAppContext,
2549 mut cx_b: TestAppContext,
2550 mut cx_c: TestAppContext,
2551 ) {
2552 cx_a.foreground().forbid_parking();
2553 let lang_registry = Arc::new(LanguageRegistry::new());
2554 let fs = Arc::new(FakeFs::new());
2555
2556 // Connect to a server as 3 clients.
2557 let mut server = TestServer::start(cx_a.foreground()).await;
2558 let client_a = server.create_client(&mut cx_a, "user_a").await;
2559 let client_b = server.create_client(&mut cx_b, "user_b").await;
2560 let client_c = server.create_client(&mut cx_c, "user_c").await;
2561
2562 // Share a worktree as client A.
2563 fs.insert_tree(
2564 "/a",
2565 json!({
2566 ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
2567 }),
2568 )
2569 .await;
2570
2571 let project_a = cx_a.update(|cx| {
2572 Project::local(
2573 client_a.clone(),
2574 client_a.user_store.clone(),
2575 lang_registry.clone(),
2576 fs.clone(),
2577 cx,
2578 )
2579 });
2580 let worktree_a = project_a
2581 .update(&mut cx_a, |p, cx| p.add_local_worktree("/a", cx))
2582 .await
2583 .unwrap();
2584 worktree_a
2585 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2586 .await;
2587
2588 client_a
2589 .user_store
2590 .condition(&cx_a, |user_store, _| {
2591 contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
2592 })
2593 .await;
2594 client_b
2595 .user_store
2596 .condition(&cx_b, |user_store, _| {
2597 contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
2598 })
2599 .await;
2600 client_c
2601 .user_store
2602 .condition(&cx_c, |user_store, _| {
2603 contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
2604 })
2605 .await;
2606
2607 let project_id = project_a
2608 .update(&mut cx_a, |project, _| project.next_remote_id())
2609 .await;
2610 project_a
2611 .update(&mut cx_a, |project, cx| project.share(cx))
2612 .await
2613 .unwrap();
2614
2615 let _project_b = Project::remote(
2616 project_id,
2617 client_b.clone(),
2618 client_b.user_store.clone(),
2619 lang_registry.clone(),
2620 fs.clone(),
2621 &mut cx_b.to_async(),
2622 )
2623 .await
2624 .unwrap();
2625
2626 client_a
2627 .user_store
2628 .condition(&cx_a, |user_store, _| {
2629 contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
2630 })
2631 .await;
2632 client_b
2633 .user_store
2634 .condition(&cx_b, |user_store, _| {
2635 contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
2636 })
2637 .await;
2638 client_c
2639 .user_store
2640 .condition(&cx_c, |user_store, _| {
2641 contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
2642 })
2643 .await;
2644
2645 project_a
2646 .condition(&cx_a, |project, _| {
2647 project.collaborators().contains_key(&client_b.peer_id)
2648 })
2649 .await;
2650
2651 cx_a.update(move |_| drop(project_a));
2652 client_a
2653 .user_store
2654 .condition(&cx_a, |user_store, _| contacts(user_store) == vec![])
2655 .await;
2656 client_b
2657 .user_store
2658 .condition(&cx_b, |user_store, _| contacts(user_store) == vec![])
2659 .await;
2660 client_c
2661 .user_store
2662 .condition(&cx_c, |user_store, _| contacts(user_store) == vec![])
2663 .await;
2664
2665 fn contacts(user_store: &UserStore) -> Vec<(&str, Vec<(&str, Vec<&str>)>)> {
2666 user_store
2667 .contacts()
2668 .iter()
2669 .map(|contact| {
2670 let worktrees = contact
2671 .projects
2672 .iter()
2673 .map(|p| {
2674 (
2675 p.worktree_root_names[0].as_str(),
2676 p.guests.iter().map(|p| p.github_login.as_str()).collect(),
2677 )
2678 })
2679 .collect();
2680 (contact.user.github_login.as_str(), worktrees)
2681 })
2682 .collect()
2683 }
2684 }
2685
2686 struct TestServer {
2687 peer: Arc<Peer>,
2688 app_state: Arc<AppState>,
2689 server: Arc<Server>,
2690 foreground: Rc<executor::Foreground>,
2691 notifications: mpsc::Receiver<()>,
2692 connection_killers: Arc<Mutex<HashMap<UserId, watch::Sender<Option<()>>>>>,
2693 forbid_connections: Arc<AtomicBool>,
2694 _test_db: TestDb,
2695 }
2696
2697 impl TestServer {
2698 async fn start(foreground: Rc<executor::Foreground>) -> Self {
2699 let test_db = TestDb::new();
2700 let app_state = Self::build_app_state(&test_db).await;
2701 let peer = Peer::new();
2702 let notifications = mpsc::channel(128);
2703 let server = Server::new(app_state.clone(), peer.clone(), Some(notifications.0));
2704 Self {
2705 peer,
2706 app_state,
2707 server,
2708 foreground,
2709 notifications: notifications.1,
2710 connection_killers: Default::default(),
2711 forbid_connections: Default::default(),
2712 _test_db: test_db,
2713 }
2714 }
2715
2716 async fn create_client(&mut self, cx: &mut TestAppContext, name: &str) -> TestClient {
2717 let http = FakeHttpClient::with_404_response();
2718 let user_id = self.app_state.db.create_user(name, false).await.unwrap();
2719 let client_name = name.to_string();
2720 let mut client = Client::new(http.clone());
2721 let server = self.server.clone();
2722 let connection_killers = self.connection_killers.clone();
2723 let forbid_connections = self.forbid_connections.clone();
2724 let (connection_id_tx, mut connection_id_rx) = postage::mpsc::channel(16);
2725
2726 Arc::get_mut(&mut client)
2727 .unwrap()
2728 .override_authenticate(move |cx| {
2729 cx.spawn(|_| async move {
2730 let access_token = "the-token".to_string();
2731 Ok(Credentials {
2732 user_id: user_id.0 as u64,
2733 access_token,
2734 })
2735 })
2736 })
2737 .override_establish_connection(move |credentials, cx| {
2738 assert_eq!(credentials.user_id, user_id.0 as u64);
2739 assert_eq!(credentials.access_token, "the-token");
2740
2741 let server = server.clone();
2742 let connection_killers = connection_killers.clone();
2743 let forbid_connections = forbid_connections.clone();
2744 let client_name = client_name.clone();
2745 let connection_id_tx = connection_id_tx.clone();
2746 cx.spawn(move |cx| async move {
2747 if forbid_connections.load(SeqCst) {
2748 Err(EstablishConnectionError::other(anyhow!(
2749 "server is forbidding connections"
2750 )))
2751 } else {
2752 let (client_conn, server_conn, kill_conn) = Connection::in_memory();
2753 connection_killers.lock().insert(user_id, kill_conn);
2754 cx.background()
2755 .spawn(server.handle_connection(
2756 server_conn,
2757 client_name,
2758 user_id,
2759 Some(connection_id_tx),
2760 ))
2761 .detach();
2762 Ok(client_conn)
2763 }
2764 })
2765 });
2766
2767 client
2768 .authenticate_and_connect(&cx.to_async())
2769 .await
2770 .unwrap();
2771
2772 let peer_id = PeerId(connection_id_rx.recv().await.unwrap().0);
2773 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http, cx));
2774 let mut authed_user =
2775 user_store.read_with(cx, |user_store, _| user_store.watch_current_user());
2776 while authed_user.recv().await.unwrap().is_none() {}
2777
2778 TestClient {
2779 client,
2780 peer_id,
2781 user_store,
2782 }
2783 }
2784
2785 fn disconnect_client(&self, user_id: UserId) {
2786 if let Some(mut kill_conn) = self.connection_killers.lock().remove(&user_id) {
2787 let _ = kill_conn.try_send(Some(()));
2788 }
2789 }
2790
2791 fn forbid_connections(&self) {
2792 self.forbid_connections.store(true, SeqCst);
2793 }
2794
2795 fn allow_connections(&self) {
2796 self.forbid_connections.store(false, SeqCst);
2797 }
2798
2799 async fn build_app_state(test_db: &TestDb) -> Arc<AppState> {
2800 let mut config = Config::default();
2801 config.session_secret = "a".repeat(32);
2802 config.database_url = test_db.url.clone();
2803 let github_client = github::AppClient::test();
2804 Arc::new(AppState {
2805 db: test_db.db().clone(),
2806 handlebars: Default::default(),
2807 auth_client: auth::build_client("", ""),
2808 repo_client: github::RepoClient::test(&github_client),
2809 github_client,
2810 config,
2811 })
2812 }
2813
2814 async fn state<'a>(&'a self) -> RwLockReadGuard<'a, Store> {
2815 self.server.store.read()
2816 }
2817
2818 async fn condition<F>(&mut self, mut predicate: F)
2819 where
2820 F: FnMut(&Store) -> bool,
2821 {
2822 async_std::future::timeout(Duration::from_millis(500), async {
2823 while !(predicate)(&*self.server.store.read()) {
2824 self.foreground.start_waiting();
2825 self.notifications.recv().await;
2826 self.foreground.finish_waiting();
2827 }
2828 })
2829 .await
2830 .expect("condition timed out");
2831 }
2832 }
2833
2834 impl Drop for TestServer {
2835 fn drop(&mut self) {
2836 task::block_on(self.peer.reset());
2837 }
2838 }
2839
2840 struct TestClient {
2841 client: Arc<Client>,
2842 pub peer_id: PeerId,
2843 pub user_store: ModelHandle<UserStore>,
2844 }
2845
2846 impl Deref for TestClient {
2847 type Target = Arc<Client>;
2848
2849 fn deref(&self) -> &Self::Target {
2850 &self.client
2851 }
2852 }
2853
2854 impl TestClient {
2855 pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
2856 UserId::from_proto(
2857 self.user_store
2858 .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
2859 )
2860 }
2861 }
2862
2863 fn channel_messages(channel: &Channel) -> Vec<(String, String, bool)> {
2864 channel
2865 .messages()
2866 .cursor::<()>()
2867 .map(|m| {
2868 (
2869 m.sender.github_login.clone(),
2870 m.body.clone(),
2871 m.is_pending(),
2872 )
2873 })
2874 .collect()
2875 }
2876
2877 struct EmptyView;
2878
2879 impl gpui::Entity for EmptyView {
2880 type Event = ();
2881 }
2882
2883 impl gpui::View for EmptyView {
2884 fn ui_name() -> &'static str {
2885 "empty view"
2886 }
2887
2888 fn render(&mut self, _: &mut gpui::RenderContext<Self>) -> gpui::ElementBox {
2889 gpui::Element::boxed(gpui::elements::Empty)
2890 }
2891 }
2892}