1use crate::{
2 rpc::{CLEANUP_TIMEOUT, RECONNECT_TIMEOUT},
3 tests::{
4 channel_id, following_tests::join_channel, room_participants, rust_lang, RoomParticipants,
5 TestClient, TestServer,
6 },
7};
8use anyhow::{anyhow, Result};
9use call::{room, ActiveCall, ParticipantLocation, Room};
10use client::{User, RECEIVE_TIMEOUT};
11use collections::{HashMap, HashSet};
12use fs::{FakeFs, Fs as _, RemoveOptions};
13use futures::{channel::mpsc, StreamExt as _};
14use git::repository::GitFileStatus;
15use gpui::{
16 px, size, AppContext, BackgroundExecutor, BorrowAppContext, Model, Modifiers, MouseButton,
17 MouseDownEvent, TestAppContext,
18};
19use language::{
20 language_settings::{AllLanguageSettings, Formatter},
21 tree_sitter_rust, Diagnostic, DiagnosticEntry, FakeLspAdapter, Language, LanguageConfig,
22 LanguageMatcher, LineEnding, OffsetRangeExt, Point, Rope,
23};
24use live_kit_client::MacOSDisplay;
25use lsp::LanguageServerId;
26use parking_lot::Mutex;
27use project::{
28 search::SearchQuery, DiagnosticSummary, FormatTrigger, HoverBlockKind, Project, ProjectPath,
29 SearchResult,
30};
31use rand::prelude::*;
32use serde_json::json;
33use settings::SettingsStore;
34use std::{
35 cell::{Cell, RefCell},
36 env, future, mem,
37 path::{Path, PathBuf},
38 rc::Rc,
39 sync::{
40 atomic::{AtomicBool, Ordering::SeqCst},
41 Arc,
42 },
43 time::Duration,
44};
45use unindent::Unindent as _;
46use workspace::Pane;
47
48#[ctor::ctor]
49fn init_logger() {
50 if std::env::var("RUST_LOG").is_ok() {
51 env_logger::init();
52 }
53}
54
55#[gpui::test(iterations = 10)]
56async fn test_basic_calls(
57 executor: BackgroundExecutor,
58 cx_a: &mut TestAppContext,
59 cx_b: &mut TestAppContext,
60 cx_b2: &mut TestAppContext,
61 cx_c: &mut TestAppContext,
62) {
63 let mut server = TestServer::start(executor.clone()).await;
64
65 let client_a = server.create_client(cx_a, "user_a").await;
66 let client_b = server.create_client(cx_b, "user_b").await;
67 let client_c = server.create_client(cx_c, "user_c").await;
68 server
69 .make_contacts(&mut [(&client_a, cx_a), (&client_b, cx_b), (&client_c, cx_c)])
70 .await;
71
72 let active_call_a = cx_a.read(ActiveCall::global);
73 let active_call_b = cx_b.read(ActiveCall::global);
74 let active_call_c = cx_c.read(ActiveCall::global);
75
76 // Call user B from client A.
77 active_call_a
78 .update(cx_a, |call, cx| {
79 call.invite(client_b.user_id().unwrap(), None, cx)
80 })
81 .await
82 .unwrap();
83 let room_a = active_call_a.read_with(cx_a, |call, _| call.room().unwrap().clone());
84 executor.run_until_parked();
85 assert_eq!(
86 room_participants(&room_a, cx_a),
87 RoomParticipants {
88 remote: Default::default(),
89 pending: vec!["user_b".to_string()]
90 }
91 );
92
93 // User B receives the call.
94
95 let mut incoming_call_b = active_call_b.read_with(cx_b, |call, _| call.incoming());
96 let call_b = incoming_call_b.next().await.unwrap().unwrap();
97 assert_eq!(call_b.calling_user.github_login, "user_a");
98
99 // User B connects via another client and also receives a ring on the newly-connected client.
100 let _client_b2 = server.create_client(cx_b2, "user_b").await;
101 let active_call_b2 = cx_b2.read(ActiveCall::global);
102
103 let mut incoming_call_b2 = active_call_b2.read_with(cx_b2, |call, _| call.incoming());
104 executor.run_until_parked();
105 let call_b2 = incoming_call_b2.next().await.unwrap().unwrap();
106 assert_eq!(call_b2.calling_user.github_login, "user_a");
107
108 // User B joins the room using the first client.
109 active_call_b
110 .update(cx_b, |call, cx| call.accept_incoming(cx))
111 .await
112 .unwrap();
113
114 let room_b = active_call_b.read_with(cx_b, |call, _| call.room().unwrap().clone());
115 assert!(incoming_call_b.next().await.unwrap().is_none());
116
117 executor.run_until_parked();
118 assert_eq!(
119 room_participants(&room_a, cx_a),
120 RoomParticipants {
121 remote: vec!["user_b".to_string()],
122 pending: Default::default()
123 }
124 );
125 assert_eq!(
126 room_participants(&room_b, cx_b),
127 RoomParticipants {
128 remote: vec!["user_a".to_string()],
129 pending: Default::default()
130 }
131 );
132
133 // Call user C from client B.
134
135 let mut incoming_call_c = active_call_c.read_with(cx_c, |call, _| call.incoming());
136 active_call_b
137 .update(cx_b, |call, cx| {
138 call.invite(client_c.user_id().unwrap(), None, cx)
139 })
140 .await
141 .unwrap();
142
143 executor.run_until_parked();
144 assert_eq!(
145 room_participants(&room_a, cx_a),
146 RoomParticipants {
147 remote: vec!["user_b".to_string()],
148 pending: vec!["user_c".to_string()]
149 }
150 );
151 assert_eq!(
152 room_participants(&room_b, cx_b),
153 RoomParticipants {
154 remote: vec!["user_a".to_string()],
155 pending: vec!["user_c".to_string()]
156 }
157 );
158
159 // User C receives the call, but declines it.
160 let call_c = incoming_call_c.next().await.unwrap().unwrap();
161 assert_eq!(call_c.calling_user.github_login, "user_b");
162 active_call_c.update(cx_c, |call, cx| call.decline_incoming(cx).unwrap());
163 assert!(incoming_call_c.next().await.unwrap().is_none());
164
165 executor.run_until_parked();
166 assert_eq!(
167 room_participants(&room_a, cx_a),
168 RoomParticipants {
169 remote: vec!["user_b".to_string()],
170 pending: Default::default()
171 }
172 );
173 assert_eq!(
174 room_participants(&room_b, cx_b),
175 RoomParticipants {
176 remote: vec!["user_a".to_string()],
177 pending: Default::default()
178 }
179 );
180
181 // Call user C again from user A.
182 active_call_a
183 .update(cx_a, |call, cx| {
184 call.invite(client_c.user_id().unwrap(), None, cx)
185 })
186 .await
187 .unwrap();
188
189 executor.run_until_parked();
190 assert_eq!(
191 room_participants(&room_a, cx_a),
192 RoomParticipants {
193 remote: vec!["user_b".to_string()],
194 pending: vec!["user_c".to_string()]
195 }
196 );
197 assert_eq!(
198 room_participants(&room_b, cx_b),
199 RoomParticipants {
200 remote: vec!["user_a".to_string()],
201 pending: vec!["user_c".to_string()]
202 }
203 );
204
205 // User C accepts the call.
206 let call_c = incoming_call_c.next().await.unwrap().unwrap();
207 assert_eq!(call_c.calling_user.github_login, "user_a");
208 active_call_c
209 .update(cx_c, |call, cx| call.accept_incoming(cx))
210 .await
211 .unwrap();
212 assert!(incoming_call_c.next().await.unwrap().is_none());
213
214 let room_c = active_call_c.read_with(cx_c, |call, _| call.room().unwrap().clone());
215
216 executor.run_until_parked();
217 assert_eq!(
218 room_participants(&room_a, cx_a),
219 RoomParticipants {
220 remote: vec!["user_b".to_string(), "user_c".to_string()],
221 pending: Default::default()
222 }
223 );
224 assert_eq!(
225 room_participants(&room_b, cx_b),
226 RoomParticipants {
227 remote: vec!["user_a".to_string(), "user_c".to_string()],
228 pending: Default::default()
229 }
230 );
231 assert_eq!(
232 room_participants(&room_c, cx_c),
233 RoomParticipants {
234 remote: vec!["user_a".to_string(), "user_b".to_string()],
235 pending: Default::default()
236 }
237 );
238
239 // User A shares their screen
240 let display = MacOSDisplay::new();
241 let events_b = active_call_events(cx_b);
242 let events_c = active_call_events(cx_c);
243 active_call_a
244 .update(cx_a, |call, cx| {
245 call.room().unwrap().update(cx, |room, cx| {
246 room.set_display_sources(vec![display.clone()]);
247 room.share_screen(cx)
248 })
249 })
250 .await
251 .unwrap();
252
253 executor.run_until_parked();
254
255 // User B observes the remote screen sharing track.
256 assert_eq!(events_b.borrow().len(), 1);
257 let event_b = events_b.borrow().first().unwrap().clone();
258 if let call::room::Event::RemoteVideoTracksChanged { participant_id } = event_b {
259 assert_eq!(participant_id, client_a.peer_id().unwrap());
260
261 room_b.read_with(cx_b, |room, _| {
262 assert_eq!(
263 room.remote_participants()[&client_a.user_id().unwrap()]
264 .video_tracks
265 .len(),
266 1
267 );
268 });
269 } else {
270 panic!("unexpected event")
271 }
272
273 // User C observes the remote screen sharing track.
274 assert_eq!(events_c.borrow().len(), 1);
275 let event_c = events_c.borrow().first().unwrap().clone();
276 if let call::room::Event::RemoteVideoTracksChanged { participant_id } = event_c {
277 assert_eq!(participant_id, client_a.peer_id().unwrap());
278
279 room_c.read_with(cx_c, |room, _| {
280 assert_eq!(
281 room.remote_participants()[&client_a.user_id().unwrap()]
282 .video_tracks
283 .len(),
284 1
285 );
286 });
287 } else {
288 panic!("unexpected event")
289 }
290
291 // User A leaves the room.
292 active_call_a
293 .update(cx_a, |call, cx| {
294 let hang_up = call.hang_up(cx);
295 assert!(call.room().is_none());
296 hang_up
297 })
298 .await
299 .unwrap();
300 executor.run_until_parked();
301 assert_eq!(
302 room_participants(&room_a, cx_a),
303 RoomParticipants {
304 remote: Default::default(),
305 pending: Default::default()
306 }
307 );
308 assert_eq!(
309 room_participants(&room_b, cx_b),
310 RoomParticipants {
311 remote: vec!["user_c".to_string()],
312 pending: Default::default()
313 }
314 );
315 assert_eq!(
316 room_participants(&room_c, cx_c),
317 RoomParticipants {
318 remote: vec!["user_b".to_string()],
319 pending: Default::default()
320 }
321 );
322
323 // User B gets disconnected from the LiveKit server, which causes them
324 // to automatically leave the room. User C leaves the room as well because
325 // nobody else is in there.
326 server
327 .test_live_kit_server
328 .disconnect_client(client_b.user_id().unwrap().to_string())
329 .await;
330 executor.run_until_parked();
331
332 active_call_b.read_with(cx_b, |call, _| assert!(call.room().is_none()));
333
334 active_call_c.read_with(cx_c, |call, _| assert!(call.room().is_none()));
335 assert_eq!(
336 room_participants(&room_a, cx_a),
337 RoomParticipants {
338 remote: Default::default(),
339 pending: Default::default()
340 }
341 );
342 assert_eq!(
343 room_participants(&room_b, cx_b),
344 RoomParticipants {
345 remote: Default::default(),
346 pending: Default::default()
347 }
348 );
349 assert_eq!(
350 room_participants(&room_c, cx_c),
351 RoomParticipants {
352 remote: Default::default(),
353 pending: Default::default()
354 }
355 );
356}
357
358#[gpui::test(iterations = 10)]
359async fn test_calling_multiple_users_simultaneously(
360 executor: BackgroundExecutor,
361 cx_a: &mut TestAppContext,
362 cx_b: &mut TestAppContext,
363 cx_c: &mut TestAppContext,
364 cx_d: &mut TestAppContext,
365) {
366 let mut server = TestServer::start(executor.clone()).await;
367
368 let client_a = server.create_client(cx_a, "user_a").await;
369 let client_b = server.create_client(cx_b, "user_b").await;
370 let client_c = server.create_client(cx_c, "user_c").await;
371 let client_d = server.create_client(cx_d, "user_d").await;
372 server
373 .make_contacts(&mut [
374 (&client_a, cx_a),
375 (&client_b, cx_b),
376 (&client_c, cx_c),
377 (&client_d, cx_d),
378 ])
379 .await;
380
381 let active_call_a = cx_a.read(ActiveCall::global);
382 let active_call_b = cx_b.read(ActiveCall::global);
383 let active_call_c = cx_c.read(ActiveCall::global);
384 let active_call_d = cx_d.read(ActiveCall::global);
385
386 // Simultaneously call user B and user C from client A.
387 let b_invite = active_call_a.update(cx_a, |call, cx| {
388 call.invite(client_b.user_id().unwrap(), None, cx)
389 });
390 let c_invite = active_call_a.update(cx_a, |call, cx| {
391 call.invite(client_c.user_id().unwrap(), None, cx)
392 });
393 b_invite.await.unwrap();
394 c_invite.await.unwrap();
395
396 let room_a = active_call_a.read_with(cx_a, |call, _| call.room().unwrap().clone());
397 executor.run_until_parked();
398 assert_eq!(
399 room_participants(&room_a, cx_a),
400 RoomParticipants {
401 remote: Default::default(),
402 pending: vec!["user_b".to_string(), "user_c".to_string()]
403 }
404 );
405
406 // Call client D from client A.
407 active_call_a
408 .update(cx_a, |call, cx| {
409 call.invite(client_d.user_id().unwrap(), None, cx)
410 })
411 .await
412 .unwrap();
413 executor.run_until_parked();
414 assert_eq!(
415 room_participants(&room_a, cx_a),
416 RoomParticipants {
417 remote: Default::default(),
418 pending: vec![
419 "user_b".to_string(),
420 "user_c".to_string(),
421 "user_d".to_string()
422 ]
423 }
424 );
425
426 // Accept the call on all clients simultaneously.
427 let accept_b = active_call_b.update(cx_b, |call, cx| call.accept_incoming(cx));
428 let accept_c = active_call_c.update(cx_c, |call, cx| call.accept_incoming(cx));
429 let accept_d = active_call_d.update(cx_d, |call, cx| call.accept_incoming(cx));
430 accept_b.await.unwrap();
431 accept_c.await.unwrap();
432 accept_d.await.unwrap();
433
434 executor.run_until_parked();
435
436 let room_b = active_call_b.read_with(cx_b, |call, _| call.room().unwrap().clone());
437
438 let room_c = active_call_c.read_with(cx_c, |call, _| call.room().unwrap().clone());
439
440 let room_d = active_call_d.read_with(cx_d, |call, _| call.room().unwrap().clone());
441 assert_eq!(
442 room_participants(&room_a, cx_a),
443 RoomParticipants {
444 remote: vec![
445 "user_b".to_string(),
446 "user_c".to_string(),
447 "user_d".to_string(),
448 ],
449 pending: Default::default()
450 }
451 );
452 assert_eq!(
453 room_participants(&room_b, cx_b),
454 RoomParticipants {
455 remote: vec![
456 "user_a".to_string(),
457 "user_c".to_string(),
458 "user_d".to_string(),
459 ],
460 pending: Default::default()
461 }
462 );
463 assert_eq!(
464 room_participants(&room_c, cx_c),
465 RoomParticipants {
466 remote: vec![
467 "user_a".to_string(),
468 "user_b".to_string(),
469 "user_d".to_string(),
470 ],
471 pending: Default::default()
472 }
473 );
474 assert_eq!(
475 room_participants(&room_d, cx_d),
476 RoomParticipants {
477 remote: vec![
478 "user_a".to_string(),
479 "user_b".to_string(),
480 "user_c".to_string(),
481 ],
482 pending: Default::default()
483 }
484 );
485}
486
487#[gpui::test(iterations = 10)]
488async fn test_joining_channels_and_calling_multiple_users_simultaneously(
489 executor: BackgroundExecutor,
490 cx_a: &mut TestAppContext,
491 cx_b: &mut TestAppContext,
492 cx_c: &mut TestAppContext,
493) {
494 let mut server = TestServer::start(executor.clone()).await;
495
496 let client_a = server.create_client(cx_a, "user_a").await;
497 let client_b = server.create_client(cx_b, "user_b").await;
498 let client_c = server.create_client(cx_c, "user_c").await;
499 server
500 .make_contacts(&mut [(&client_a, cx_a), (&client_b, cx_b), (&client_c, cx_c)])
501 .await;
502
503 let channel_1 = server
504 .make_channel(
505 "channel1",
506 None,
507 (&client_a, cx_a),
508 &mut [(&client_b, cx_b), (&client_c, cx_c)],
509 )
510 .await;
511
512 let channel_2 = server
513 .make_channel(
514 "channel2",
515 None,
516 (&client_a, cx_a),
517 &mut [(&client_b, cx_b), (&client_c, cx_c)],
518 )
519 .await;
520
521 let active_call_a = cx_a.read(ActiveCall::global);
522
523 // Simultaneously join channel 1 and then channel 2
524 active_call_a
525 .update(cx_a, |call, cx| call.join_channel(channel_1, cx))
526 .detach();
527 let join_channel_2 = active_call_a.update(cx_a, |call, cx| call.join_channel(channel_2, cx));
528
529 join_channel_2.await.unwrap();
530
531 let room_a = active_call_a.read_with(cx_a, |call, _| call.room().unwrap().clone());
532 executor.run_until_parked();
533
534 assert_eq!(channel_id(&room_a, cx_a), Some(channel_2));
535
536 // Leave the room
537 active_call_a
538 .update(cx_a, |call, cx| {
539 let hang_up = call.hang_up(cx);
540 hang_up
541 })
542 .await
543 .unwrap();
544
545 // Initiating invites and then joining a channel should fail gracefully
546 let b_invite = active_call_a.update(cx_a, |call, cx| {
547 call.invite(client_b.user_id().unwrap(), None, cx)
548 });
549 let c_invite = active_call_a.update(cx_a, |call, cx| {
550 call.invite(client_c.user_id().unwrap(), None, cx)
551 });
552
553 let join_channel = active_call_a.update(cx_a, |call, cx| call.join_channel(channel_1, cx));
554
555 b_invite.await.unwrap();
556 c_invite.await.unwrap();
557 join_channel.await.unwrap();
558
559 let room_a = active_call_a.read_with(cx_a, |call, _| call.room().unwrap().clone());
560 executor.run_until_parked();
561
562 assert_eq!(
563 room_participants(&room_a, cx_a),
564 RoomParticipants {
565 remote: Default::default(),
566 pending: vec!["user_b".to_string(), "user_c".to_string()]
567 }
568 );
569
570 assert_eq!(channel_id(&room_a, cx_a), None);
571
572 // Leave the room
573 active_call_a
574 .update(cx_a, |call, cx| {
575 let hang_up = call.hang_up(cx);
576 hang_up
577 })
578 .await
579 .unwrap();
580
581 // Simultaneously join channel 1 and call user B and user C from client A.
582 let join_channel = active_call_a.update(cx_a, |call, cx| call.join_channel(channel_1, cx));
583
584 let b_invite = active_call_a.update(cx_a, |call, cx| {
585 call.invite(client_b.user_id().unwrap(), None, cx)
586 });
587 let c_invite = active_call_a.update(cx_a, |call, cx| {
588 call.invite(client_c.user_id().unwrap(), None, cx)
589 });
590
591 join_channel.await.unwrap();
592 b_invite.await.unwrap();
593 c_invite.await.unwrap();
594
595 active_call_a.read_with(cx_a, |call, _| call.room().unwrap().clone());
596 executor.run_until_parked();
597}
598
599#[gpui::test(iterations = 10)]
600async fn test_room_uniqueness(
601 executor: BackgroundExecutor,
602 cx_a: &mut TestAppContext,
603 cx_a2: &mut TestAppContext,
604 cx_b: &mut TestAppContext,
605 cx_b2: &mut TestAppContext,
606 cx_c: &mut TestAppContext,
607) {
608 let mut server = TestServer::start(executor.clone()).await;
609 let client_a = server.create_client(cx_a, "user_a").await;
610 let _client_a2 = server.create_client(cx_a2, "user_a").await;
611 let client_b = server.create_client(cx_b, "user_b").await;
612 let _client_b2 = server.create_client(cx_b2, "user_b").await;
613 let client_c = server.create_client(cx_c, "user_c").await;
614 server
615 .make_contacts(&mut [(&client_a, cx_a), (&client_b, cx_b), (&client_c, cx_c)])
616 .await;
617
618 let active_call_a = cx_a.read(ActiveCall::global);
619 let active_call_a2 = cx_a2.read(ActiveCall::global);
620 let active_call_b = cx_b.read(ActiveCall::global);
621 let active_call_b2 = cx_b2.read(ActiveCall::global);
622 let active_call_c = cx_c.read(ActiveCall::global);
623
624 // Call user B from client A.
625 active_call_a
626 .update(cx_a, |call, cx| {
627 call.invite(client_b.user_id().unwrap(), None, cx)
628 })
629 .await
630 .unwrap();
631
632 // Ensure a new room can't be created given user A just created one.
633 active_call_a2
634 .update(cx_a2, |call, cx| {
635 call.invite(client_c.user_id().unwrap(), None, cx)
636 })
637 .await
638 .unwrap_err();
639
640 active_call_a2.read_with(cx_a2, |call, _| assert!(call.room().is_none()));
641
642 // User B receives the call from user A.
643
644 let mut incoming_call_b = active_call_b.read_with(cx_b, |call, _| call.incoming());
645 let call_b1 = incoming_call_b.next().await.unwrap().unwrap();
646 assert_eq!(call_b1.calling_user.github_login, "user_a");
647
648 // Ensure calling users A and B from client C fails.
649 active_call_c
650 .update(cx_c, |call, cx| {
651 call.invite(client_a.user_id().unwrap(), None, cx)
652 })
653 .await
654 .unwrap_err();
655 active_call_c
656 .update(cx_c, |call, cx| {
657 call.invite(client_b.user_id().unwrap(), None, cx)
658 })
659 .await
660 .unwrap_err();
661
662 // Ensure User B can't create a room while they still have an incoming call.
663 active_call_b2
664 .update(cx_b2, |call, cx| {
665 call.invite(client_c.user_id().unwrap(), None, cx)
666 })
667 .await
668 .unwrap_err();
669
670 active_call_b2.read_with(cx_b2, |call, _| assert!(call.room().is_none()));
671
672 // User B joins the room and calling them after they've joined still fails.
673 active_call_b
674 .update(cx_b, |call, cx| call.accept_incoming(cx))
675 .await
676 .unwrap();
677 active_call_c
678 .update(cx_c, |call, cx| {
679 call.invite(client_b.user_id().unwrap(), None, cx)
680 })
681 .await
682 .unwrap_err();
683
684 // Ensure User B can't create a room while they belong to another room.
685 active_call_b2
686 .update(cx_b2, |call, cx| {
687 call.invite(client_c.user_id().unwrap(), None, cx)
688 })
689 .await
690 .unwrap_err();
691
692 active_call_b2.read_with(cx_b2, |call, _| assert!(call.room().is_none()));
693
694 // Client C can successfully call client B after client B leaves the room.
695 active_call_b
696 .update(cx_b, |call, cx| call.hang_up(cx))
697 .await
698 .unwrap();
699 executor.run_until_parked();
700 active_call_c
701 .update(cx_c, |call, cx| {
702 call.invite(client_b.user_id().unwrap(), None, cx)
703 })
704 .await
705 .unwrap();
706 executor.run_until_parked();
707 let call_b2 = incoming_call_b.next().await.unwrap().unwrap();
708 assert_eq!(call_b2.calling_user.github_login, "user_c");
709}
710
711#[gpui::test(iterations = 10)]
712async fn test_client_disconnecting_from_room(
713 executor: BackgroundExecutor,
714 cx_a: &mut TestAppContext,
715 cx_b: &mut TestAppContext,
716) {
717 let mut server = TestServer::start(executor.clone()).await;
718 let client_a = server.create_client(cx_a, "user_a").await;
719 let client_b = server.create_client(cx_b, "user_b").await;
720 server
721 .make_contacts(&mut [(&client_a, cx_a), (&client_b, cx_b)])
722 .await;
723
724 let active_call_a = cx_a.read(ActiveCall::global);
725 let active_call_b = cx_b.read(ActiveCall::global);
726
727 // Call user B from client A.
728 active_call_a
729 .update(cx_a, |call, cx| {
730 call.invite(client_b.user_id().unwrap(), None, cx)
731 })
732 .await
733 .unwrap();
734
735 let room_a = active_call_a.read_with(cx_a, |call, _| call.room().unwrap().clone());
736
737 // User B receives the call and joins the room.
738
739 let mut incoming_call_b = active_call_b.read_with(cx_b, |call, _| call.incoming());
740 incoming_call_b.next().await.unwrap().unwrap();
741 active_call_b
742 .update(cx_b, |call, cx| call.accept_incoming(cx))
743 .await
744 .unwrap();
745
746 let room_b = active_call_b.read_with(cx_b, |call, _| call.room().unwrap().clone());
747 executor.run_until_parked();
748 assert_eq!(
749 room_participants(&room_a, cx_a),
750 RoomParticipants {
751 remote: vec!["user_b".to_string()],
752 pending: Default::default()
753 }
754 );
755 assert_eq!(
756 room_participants(&room_b, cx_b),
757 RoomParticipants {
758 remote: vec!["user_a".to_string()],
759 pending: Default::default()
760 }
761 );
762
763 // User A automatically reconnects to the room upon disconnection.
764 server.disconnect_client(client_a.peer_id().unwrap());
765 executor.advance_clock(RECEIVE_TIMEOUT);
766 executor.run_until_parked();
767 assert_eq!(
768 room_participants(&room_a, cx_a),
769 RoomParticipants {
770 remote: vec!["user_b".to_string()],
771 pending: Default::default()
772 }
773 );
774 assert_eq!(
775 room_participants(&room_b, cx_b),
776 RoomParticipants {
777 remote: vec!["user_a".to_string()],
778 pending: Default::default()
779 }
780 );
781
782 // When user A disconnects, both client A and B clear their room on the active call.
783 server.forbid_connections();
784 server.disconnect_client(client_a.peer_id().unwrap());
785 executor.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
786
787 active_call_a.read_with(cx_a, |call, _| assert!(call.room().is_none()));
788
789 active_call_b.read_with(cx_b, |call, _| assert!(call.room().is_none()));
790 assert_eq!(
791 room_participants(&room_a, cx_a),
792 RoomParticipants {
793 remote: Default::default(),
794 pending: Default::default()
795 }
796 );
797 assert_eq!(
798 room_participants(&room_b, cx_b),
799 RoomParticipants {
800 remote: Default::default(),
801 pending: Default::default()
802 }
803 );
804
805 // Allow user A to reconnect to the server.
806 server.allow_connections();
807 executor.advance_clock(RECEIVE_TIMEOUT);
808
809 // Call user B again from client A.
810 active_call_a
811 .update(cx_a, |call, cx| {
812 call.invite(client_b.user_id().unwrap(), None, cx)
813 })
814 .await
815 .unwrap();
816
817 let room_a = active_call_a.read_with(cx_a, |call, _| call.room().unwrap().clone());
818
819 // User B receives the call and joins the room.
820
821 let mut incoming_call_b = active_call_b.read_with(cx_b, |call, _| call.incoming());
822 incoming_call_b.next().await.unwrap().unwrap();
823 active_call_b
824 .update(cx_b, |call, cx| call.accept_incoming(cx))
825 .await
826 .unwrap();
827
828 let room_b = active_call_b.read_with(cx_b, |call, _| call.room().unwrap().clone());
829 executor.run_until_parked();
830 assert_eq!(
831 room_participants(&room_a, cx_a),
832 RoomParticipants {
833 remote: vec!["user_b".to_string()],
834 pending: Default::default()
835 }
836 );
837 assert_eq!(
838 room_participants(&room_b, cx_b),
839 RoomParticipants {
840 remote: vec!["user_a".to_string()],
841 pending: Default::default()
842 }
843 );
844
845 // User B gets disconnected from the LiveKit server, which causes it
846 // to automatically leave the room.
847 server
848 .test_live_kit_server
849 .disconnect_client(client_b.user_id().unwrap().to_string())
850 .await;
851 executor.run_until_parked();
852 active_call_a.update(cx_a, |call, _| assert!(call.room().is_none()));
853 active_call_b.update(cx_b, |call, _| assert!(call.room().is_none()));
854 assert_eq!(
855 room_participants(&room_a, cx_a),
856 RoomParticipants {
857 remote: Default::default(),
858 pending: Default::default()
859 }
860 );
861 assert_eq!(
862 room_participants(&room_b, cx_b),
863 RoomParticipants {
864 remote: Default::default(),
865 pending: Default::default()
866 }
867 );
868}
869
870#[gpui::test(iterations = 10)]
871async fn test_server_restarts(
872 executor: BackgroundExecutor,
873 cx_a: &mut TestAppContext,
874 cx_b: &mut TestAppContext,
875 cx_c: &mut TestAppContext,
876 cx_d: &mut TestAppContext,
877) {
878 let mut server = TestServer::start(executor.clone()).await;
879 let client_a = server.create_client(cx_a, "user_a").await;
880 client_a
881 .fs()
882 .insert_tree("/a", json!({ "a.txt": "a-contents" }))
883 .await;
884
885 // Invite client B to collaborate on a project
886 let (project_a, _) = client_a.build_local_project("/a", cx_a).await;
887
888 let client_b = server.create_client(cx_b, "user_b").await;
889 let client_c = server.create_client(cx_c, "user_c").await;
890 let client_d = server.create_client(cx_d, "user_d").await;
891 server
892 .make_contacts(&mut [
893 (&client_a, cx_a),
894 (&client_b, cx_b),
895 (&client_c, cx_c),
896 (&client_d, cx_d),
897 ])
898 .await;
899
900 let active_call_a = cx_a.read(ActiveCall::global);
901 let active_call_b = cx_b.read(ActiveCall::global);
902 let active_call_c = cx_c.read(ActiveCall::global);
903 let active_call_d = cx_d.read(ActiveCall::global);
904
905 // User A calls users B, C, and D.
906 active_call_a
907 .update(cx_a, |call, cx| {
908 call.invite(client_b.user_id().unwrap(), Some(project_a.clone()), cx)
909 })
910 .await
911 .unwrap();
912 active_call_a
913 .update(cx_a, |call, cx| {
914 call.invite(client_c.user_id().unwrap(), Some(project_a.clone()), cx)
915 })
916 .await
917 .unwrap();
918 active_call_a
919 .update(cx_a, |call, cx| {
920 call.invite(client_d.user_id().unwrap(), Some(project_a.clone()), cx)
921 })
922 .await
923 .unwrap();
924
925 let room_a = active_call_a.read_with(cx_a, |call, _| call.room().unwrap().clone());
926
927 // User B receives the call and joins the room.
928
929 let mut incoming_call_b = active_call_b.read_with(cx_b, |call, _| call.incoming());
930 assert!(incoming_call_b.next().await.unwrap().is_some());
931 active_call_b
932 .update(cx_b, |call, cx| call.accept_incoming(cx))
933 .await
934 .unwrap();
935
936 let room_b = active_call_b.read_with(cx_b, |call, _| call.room().unwrap().clone());
937
938 // User C receives the call and joins the room.
939
940 let mut incoming_call_c = active_call_c.read_with(cx_c, |call, _| call.incoming());
941 assert!(incoming_call_c.next().await.unwrap().is_some());
942 active_call_c
943 .update(cx_c, |call, cx| call.accept_incoming(cx))
944 .await
945 .unwrap();
946
947 let room_c = active_call_c.read_with(cx_c, |call, _| call.room().unwrap().clone());
948
949 // User D receives the call but doesn't join the room yet.
950
951 let mut incoming_call_d = active_call_d.read_with(cx_d, |call, _| call.incoming());
952 assert!(incoming_call_d.next().await.unwrap().is_some());
953
954 executor.run_until_parked();
955 assert_eq!(
956 room_participants(&room_a, cx_a),
957 RoomParticipants {
958 remote: vec!["user_b".to_string(), "user_c".to_string()],
959 pending: vec!["user_d".to_string()]
960 }
961 );
962 assert_eq!(
963 room_participants(&room_b, cx_b),
964 RoomParticipants {
965 remote: vec!["user_a".to_string(), "user_c".to_string()],
966 pending: vec!["user_d".to_string()]
967 }
968 );
969 assert_eq!(
970 room_participants(&room_c, cx_c),
971 RoomParticipants {
972 remote: vec!["user_a".to_string(), "user_b".to_string()],
973 pending: vec!["user_d".to_string()]
974 }
975 );
976
977 // The server is torn down.
978 server.reset().await;
979
980 // Users A and B reconnect to the call. User C has troubles reconnecting, so it leaves the room.
981 client_c.override_establish_connection(|_, cx| cx.spawn(|_| future::pending()));
982 executor.advance_clock(RECONNECT_TIMEOUT);
983 assert_eq!(
984 room_participants(&room_a, cx_a),
985 RoomParticipants {
986 remote: vec!["user_b".to_string(), "user_c".to_string()],
987 pending: vec!["user_d".to_string()]
988 }
989 );
990 assert_eq!(
991 room_participants(&room_b, cx_b),
992 RoomParticipants {
993 remote: vec!["user_a".to_string(), "user_c".to_string()],
994 pending: vec!["user_d".to_string()]
995 }
996 );
997 assert_eq!(
998 room_participants(&room_c, cx_c),
999 RoomParticipants {
1000 remote: vec![],
1001 pending: vec![]
1002 }
1003 );
1004
1005 // User D is notified again of the incoming call and accepts it.
1006 assert!(incoming_call_d.next().await.unwrap().is_some());
1007 active_call_d
1008 .update(cx_d, |call, cx| call.accept_incoming(cx))
1009 .await
1010 .unwrap();
1011 executor.run_until_parked();
1012
1013 let room_d = active_call_d.read_with(cx_d, |call, _| call.room().unwrap().clone());
1014 assert_eq!(
1015 room_participants(&room_a, cx_a),
1016 RoomParticipants {
1017 remote: vec![
1018 "user_b".to_string(),
1019 "user_c".to_string(),
1020 "user_d".to_string(),
1021 ],
1022 pending: vec![]
1023 }
1024 );
1025 assert_eq!(
1026 room_participants(&room_b, cx_b),
1027 RoomParticipants {
1028 remote: vec![
1029 "user_a".to_string(),
1030 "user_c".to_string(),
1031 "user_d".to_string(),
1032 ],
1033 pending: vec![]
1034 }
1035 );
1036 assert_eq!(
1037 room_participants(&room_c, cx_c),
1038 RoomParticipants {
1039 remote: vec![],
1040 pending: vec![]
1041 }
1042 );
1043 assert_eq!(
1044 room_participants(&room_d, cx_d),
1045 RoomParticipants {
1046 remote: vec![
1047 "user_a".to_string(),
1048 "user_b".to_string(),
1049 "user_c".to_string(),
1050 ],
1051 pending: vec![]
1052 }
1053 );
1054
1055 // The server finishes restarting, cleaning up stale connections.
1056 server.start().await.unwrap();
1057 executor.advance_clock(CLEANUP_TIMEOUT);
1058 assert_eq!(
1059 room_participants(&room_a, cx_a),
1060 RoomParticipants {
1061 remote: vec!["user_b".to_string(), "user_d".to_string()],
1062 pending: vec![]
1063 }
1064 );
1065 assert_eq!(
1066 room_participants(&room_b, cx_b),
1067 RoomParticipants {
1068 remote: vec!["user_a".to_string(), "user_d".to_string()],
1069 pending: vec![]
1070 }
1071 );
1072 assert_eq!(
1073 room_participants(&room_c, cx_c),
1074 RoomParticipants {
1075 remote: vec![],
1076 pending: vec![]
1077 }
1078 );
1079 assert_eq!(
1080 room_participants(&room_d, cx_d),
1081 RoomParticipants {
1082 remote: vec!["user_a".to_string(), "user_b".to_string()],
1083 pending: vec![]
1084 }
1085 );
1086
1087 // User D hangs up.
1088 active_call_d
1089 .update(cx_d, |call, cx| call.hang_up(cx))
1090 .await
1091 .unwrap();
1092 executor.run_until_parked();
1093 assert_eq!(
1094 room_participants(&room_a, cx_a),
1095 RoomParticipants {
1096 remote: vec!["user_b".to_string()],
1097 pending: vec![]
1098 }
1099 );
1100 assert_eq!(
1101 room_participants(&room_b, cx_b),
1102 RoomParticipants {
1103 remote: vec!["user_a".to_string()],
1104 pending: vec![]
1105 }
1106 );
1107 assert_eq!(
1108 room_participants(&room_c, cx_c),
1109 RoomParticipants {
1110 remote: vec![],
1111 pending: vec![]
1112 }
1113 );
1114 assert_eq!(
1115 room_participants(&room_d, cx_d),
1116 RoomParticipants {
1117 remote: vec![],
1118 pending: vec![]
1119 }
1120 );
1121
1122 // User B calls user D again.
1123 active_call_b
1124 .update(cx_b, |call, cx| {
1125 call.invite(client_d.user_id().unwrap(), None, cx)
1126 })
1127 .await
1128 .unwrap();
1129
1130 // User D receives the call but doesn't join the room yet.
1131
1132 let mut incoming_call_d = active_call_d.read_with(cx_d, |call, _| call.incoming());
1133 assert!(incoming_call_d.next().await.unwrap().is_some());
1134 executor.run_until_parked();
1135 assert_eq!(
1136 room_participants(&room_a, cx_a),
1137 RoomParticipants {
1138 remote: vec!["user_b".to_string()],
1139 pending: vec!["user_d".to_string()]
1140 }
1141 );
1142 assert_eq!(
1143 room_participants(&room_b, cx_b),
1144 RoomParticipants {
1145 remote: vec!["user_a".to_string()],
1146 pending: vec!["user_d".to_string()]
1147 }
1148 );
1149
1150 // The server is torn down.
1151 server.reset().await;
1152
1153 // Users A and B have troubles reconnecting, so they leave the room.
1154 client_a.override_establish_connection(|_, cx| cx.spawn(|_| future::pending()));
1155 client_b.override_establish_connection(|_, cx| cx.spawn(|_| future::pending()));
1156 client_c.override_establish_connection(|_, cx| cx.spawn(|_| future::pending()));
1157 executor.advance_clock(RECONNECT_TIMEOUT);
1158 assert_eq!(
1159 room_participants(&room_a, cx_a),
1160 RoomParticipants {
1161 remote: vec![],
1162 pending: vec![]
1163 }
1164 );
1165 assert_eq!(
1166 room_participants(&room_b, cx_b),
1167 RoomParticipants {
1168 remote: vec![],
1169 pending: vec![]
1170 }
1171 );
1172
1173 // User D is notified again of the incoming call but doesn't accept it.
1174 assert!(incoming_call_d.next().await.unwrap().is_some());
1175
1176 // The server finishes restarting, cleaning up stale connections and canceling the
1177 // call to user D because the room has become empty.
1178 server.start().await.unwrap();
1179 executor.advance_clock(CLEANUP_TIMEOUT);
1180 assert!(incoming_call_d.next().await.unwrap().is_none());
1181}
1182
1183#[gpui::test(iterations = 10)]
1184async fn test_calls_on_multiple_connections(
1185 executor: BackgroundExecutor,
1186 cx_a: &mut TestAppContext,
1187 cx_b1: &mut TestAppContext,
1188 cx_b2: &mut TestAppContext,
1189) {
1190 let mut server = TestServer::start(executor.clone()).await;
1191 let client_a = server.create_client(cx_a, "user_a").await;
1192 let client_b1 = server.create_client(cx_b1, "user_b").await;
1193 let client_b2 = server.create_client(cx_b2, "user_b").await;
1194 server
1195 .make_contacts(&mut [(&client_a, cx_a), (&client_b1, cx_b1)])
1196 .await;
1197
1198 let active_call_a = cx_a.read(ActiveCall::global);
1199 let active_call_b1 = cx_b1.read(ActiveCall::global);
1200 let active_call_b2 = cx_b2.read(ActiveCall::global);
1201
1202 let mut incoming_call_b1 = active_call_b1.read_with(cx_b1, |call, _| call.incoming());
1203
1204 let mut incoming_call_b2 = active_call_b2.read_with(cx_b2, |call, _| call.incoming());
1205 assert!(incoming_call_b1.next().await.unwrap().is_none());
1206 assert!(incoming_call_b2.next().await.unwrap().is_none());
1207
1208 // Call user B from client A, ensuring both clients for user B ring.
1209 active_call_a
1210 .update(cx_a, |call, cx| {
1211 call.invite(client_b1.user_id().unwrap(), None, cx)
1212 })
1213 .await
1214 .unwrap();
1215 executor.run_until_parked();
1216 assert!(incoming_call_b1.next().await.unwrap().is_some());
1217 assert!(incoming_call_b2.next().await.unwrap().is_some());
1218
1219 // User B declines the call on one of the two connections, causing both connections
1220 // to stop ringing.
1221 active_call_b2.update(cx_b2, |call, cx| call.decline_incoming(cx).unwrap());
1222 executor.run_until_parked();
1223 assert!(incoming_call_b1.next().await.unwrap().is_none());
1224 assert!(incoming_call_b2.next().await.unwrap().is_none());
1225
1226 // Call user B again from client A.
1227 active_call_a
1228 .update(cx_a, |call, cx| {
1229 call.invite(client_b1.user_id().unwrap(), None, cx)
1230 })
1231 .await
1232 .unwrap();
1233 executor.run_until_parked();
1234 assert!(incoming_call_b1.next().await.unwrap().is_some());
1235 assert!(incoming_call_b2.next().await.unwrap().is_some());
1236
1237 // User B accepts the call on one of the two connections, causing both connections
1238 // to stop ringing.
1239 active_call_b2
1240 .update(cx_b2, |call, cx| call.accept_incoming(cx))
1241 .await
1242 .unwrap();
1243 executor.run_until_parked();
1244 assert!(incoming_call_b1.next().await.unwrap().is_none());
1245 assert!(incoming_call_b2.next().await.unwrap().is_none());
1246
1247 // User B disconnects the client that is not on the call. Everything should be fine.
1248 client_b1.disconnect(&cx_b1.to_async());
1249 executor.advance_clock(RECEIVE_TIMEOUT);
1250 client_b1
1251 .authenticate_and_connect(false, &cx_b1.to_async())
1252 .await
1253 .unwrap();
1254
1255 // User B hangs up, and user A calls them again.
1256 active_call_b2
1257 .update(cx_b2, |call, cx| call.hang_up(cx))
1258 .await
1259 .unwrap();
1260 executor.run_until_parked();
1261 active_call_a
1262 .update(cx_a, |call, cx| {
1263 call.invite(client_b1.user_id().unwrap(), None, cx)
1264 })
1265 .await
1266 .unwrap();
1267 executor.run_until_parked();
1268 assert!(incoming_call_b1.next().await.unwrap().is_some());
1269 assert!(incoming_call_b2.next().await.unwrap().is_some());
1270
1271 // User A cancels the call, causing both connections to stop ringing.
1272 active_call_a
1273 .update(cx_a, |call, cx| {
1274 call.cancel_invite(client_b1.user_id().unwrap(), cx)
1275 })
1276 .await
1277 .unwrap();
1278 executor.run_until_parked();
1279 assert!(incoming_call_b1.next().await.unwrap().is_none());
1280 assert!(incoming_call_b2.next().await.unwrap().is_none());
1281
1282 // User A calls user B again.
1283 active_call_a
1284 .update(cx_a, |call, cx| {
1285 call.invite(client_b1.user_id().unwrap(), None, cx)
1286 })
1287 .await
1288 .unwrap();
1289 executor.run_until_parked();
1290 assert!(incoming_call_b1.next().await.unwrap().is_some());
1291 assert!(incoming_call_b2.next().await.unwrap().is_some());
1292
1293 // User A hangs up, causing both connections to stop ringing.
1294 active_call_a
1295 .update(cx_a, |call, cx| call.hang_up(cx))
1296 .await
1297 .unwrap();
1298 executor.run_until_parked();
1299 assert!(incoming_call_b1.next().await.unwrap().is_none());
1300 assert!(incoming_call_b2.next().await.unwrap().is_none());
1301
1302 // User A calls user B again.
1303 active_call_a
1304 .update(cx_a, |call, cx| {
1305 call.invite(client_b1.user_id().unwrap(), None, cx)
1306 })
1307 .await
1308 .unwrap();
1309 executor.run_until_parked();
1310 assert!(incoming_call_b1.next().await.unwrap().is_some());
1311 assert!(incoming_call_b2.next().await.unwrap().is_some());
1312
1313 // User A disconnects, causing both connections to stop ringing.
1314 server.forbid_connections();
1315 server.disconnect_client(client_a.peer_id().unwrap());
1316 executor.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
1317 assert!(incoming_call_b1.next().await.unwrap().is_none());
1318 assert!(incoming_call_b2.next().await.unwrap().is_none());
1319
1320 // User A reconnects automatically, then calls user B again.
1321 server.allow_connections();
1322 executor.advance_clock(RECEIVE_TIMEOUT);
1323 active_call_a
1324 .update(cx_a, |call, cx| {
1325 call.invite(client_b1.user_id().unwrap(), None, cx)
1326 })
1327 .await
1328 .unwrap();
1329 executor.run_until_parked();
1330 assert!(incoming_call_b1.next().await.unwrap().is_some());
1331 assert!(incoming_call_b2.next().await.unwrap().is_some());
1332
1333 // User B disconnects all clients, causing user A to no longer see a pending call for them.
1334 server.forbid_connections();
1335 server.disconnect_client(client_b1.peer_id().unwrap());
1336 server.disconnect_client(client_b2.peer_id().unwrap());
1337 executor.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
1338
1339 active_call_a.read_with(cx_a, |call, _| assert!(call.room().is_none()));
1340}
1341
1342#[gpui::test(iterations = 10)]
1343async fn test_unshare_project(
1344 executor: BackgroundExecutor,
1345 cx_a: &mut TestAppContext,
1346 cx_b: &mut TestAppContext,
1347 cx_c: &mut TestAppContext,
1348) {
1349 let mut server = TestServer::start(executor.clone()).await;
1350 let client_a = server.create_client(cx_a, "user_a").await;
1351 let client_b = server.create_client(cx_b, "user_b").await;
1352 let client_c = server.create_client(cx_c, "user_c").await;
1353 server
1354 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b), (&client_c, cx_c)])
1355 .await;
1356
1357 let active_call_a = cx_a.read(ActiveCall::global);
1358 let active_call_b = cx_b.read(ActiveCall::global);
1359
1360 client_a
1361 .fs()
1362 .insert_tree(
1363 "/a",
1364 json!({
1365 "a.txt": "a-contents",
1366 "b.txt": "b-contents",
1367 }),
1368 )
1369 .await;
1370
1371 let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
1372 let project_id = active_call_a
1373 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
1374 .await
1375 .unwrap();
1376
1377 let worktree_a = project_a.read_with(cx_a, |project, _| project.worktrees().next().unwrap());
1378 let project_b = client_b.build_remote_project(project_id, cx_b).await;
1379 executor.run_until_parked();
1380
1381 assert!(worktree_a.read_with(cx_a, |tree, _| tree.as_local().unwrap().is_shared()));
1382
1383 project_b
1384 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1385 .await
1386 .unwrap();
1387
1388 // When client B leaves the room, the project becomes read-only.
1389 active_call_b
1390 .update(cx_b, |call, cx| call.hang_up(cx))
1391 .await
1392 .unwrap();
1393 executor.run_until_parked();
1394
1395 assert!(project_b.read_with(cx_b, |project, _| project.is_disconnected()));
1396
1397 // Client C opens the project.
1398 let project_c = client_c.build_remote_project(project_id, cx_c).await;
1399
1400 // When client A unshares the project, client C's project becomes read-only.
1401 project_a
1402 .update(cx_a, |project, cx| project.unshare(cx))
1403 .unwrap();
1404 executor.run_until_parked();
1405
1406 assert!(worktree_a.read_with(cx_a, |tree, _| !tree.as_local().unwrap().is_shared()));
1407
1408 assert!(project_c.read_with(cx_c, |project, _| project.is_disconnected()));
1409
1410 // Client C can open the project again after client A re-shares.
1411 let project_id = active_call_a
1412 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
1413 .await
1414 .unwrap();
1415 let project_c2 = client_c.build_remote_project(project_id, cx_c).await;
1416 executor.run_until_parked();
1417
1418 assert!(worktree_a.read_with(cx_a, |tree, _| tree.as_local().unwrap().is_shared()));
1419 project_c2
1420 .update(cx_c, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1421 .await
1422 .unwrap();
1423
1424 // When client A (the host) leaves the room, the project gets unshared and guests are notified.
1425 active_call_a
1426 .update(cx_a, |call, cx| call.hang_up(cx))
1427 .await
1428 .unwrap();
1429 executor.run_until_parked();
1430
1431 project_a.read_with(cx_a, |project, _| assert!(!project.is_shared()));
1432
1433 project_c2.read_with(cx_c, |project, _| {
1434 assert!(project.is_disconnected());
1435 assert!(project.collaborators().is_empty());
1436 });
1437}
1438
1439#[gpui::test(iterations = 10)]
1440async fn test_project_reconnect(
1441 executor: BackgroundExecutor,
1442 cx_a: &mut TestAppContext,
1443 cx_b: &mut TestAppContext,
1444) {
1445 let mut server = TestServer::start(executor.clone()).await;
1446 let client_a = server.create_client(cx_a, "user_a").await;
1447 let client_b = server.create_client(cx_b, "user_b").await;
1448 server
1449 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
1450 .await;
1451
1452 cx_b.update(editor::init);
1453
1454 client_a
1455 .fs()
1456 .insert_tree(
1457 "/root-1",
1458 json!({
1459 "dir1": {
1460 "a.txt": "a",
1461 "b.txt": "b",
1462 "subdir1": {
1463 "c.txt": "c",
1464 "d.txt": "d",
1465 "e.txt": "e",
1466 }
1467 },
1468 "dir2": {
1469 "v.txt": "v",
1470 },
1471 "dir3": {
1472 "w.txt": "w",
1473 "x.txt": "x",
1474 "y.txt": "y",
1475 },
1476 "dir4": {
1477 "z.txt": "z",
1478 },
1479 }),
1480 )
1481 .await;
1482 client_a
1483 .fs()
1484 .insert_tree(
1485 "/root-2",
1486 json!({
1487 "2.txt": "2",
1488 }),
1489 )
1490 .await;
1491 client_a
1492 .fs()
1493 .insert_tree(
1494 "/root-3",
1495 json!({
1496 "3.txt": "3",
1497 }),
1498 )
1499 .await;
1500
1501 let active_call_a = cx_a.read(ActiveCall::global);
1502 let (project_a1, _) = client_a.build_local_project("/root-1/dir1", cx_a).await;
1503 let (project_a2, _) = client_a.build_local_project("/root-2", cx_a).await;
1504 let (project_a3, _) = client_a.build_local_project("/root-3", cx_a).await;
1505 let worktree_a1 = project_a1.read_with(cx_a, |project, _| project.worktrees().next().unwrap());
1506 let project1_id = active_call_a
1507 .update(cx_a, |call, cx| call.share_project(project_a1.clone(), cx))
1508 .await
1509 .unwrap();
1510 let project2_id = active_call_a
1511 .update(cx_a, |call, cx| call.share_project(project_a2.clone(), cx))
1512 .await
1513 .unwrap();
1514 let project3_id = active_call_a
1515 .update(cx_a, |call, cx| call.share_project(project_a3.clone(), cx))
1516 .await
1517 .unwrap();
1518
1519 let project_b1 = client_b.build_remote_project(project1_id, cx_b).await;
1520 let project_b2 = client_b.build_remote_project(project2_id, cx_b).await;
1521 let project_b3 = client_b.build_remote_project(project3_id, cx_b).await;
1522 executor.run_until_parked();
1523
1524 let worktree1_id = worktree_a1.read_with(cx_a, |worktree, _| {
1525 assert!(worktree.as_local().unwrap().is_shared());
1526 worktree.id()
1527 });
1528 let (worktree_a2, _) = project_a1
1529 .update(cx_a, |p, cx| {
1530 p.find_or_create_local_worktree("/root-1/dir2", true, cx)
1531 })
1532 .await
1533 .unwrap();
1534 executor.run_until_parked();
1535
1536 let worktree2_id = worktree_a2.read_with(cx_a, |tree, _| {
1537 assert!(tree.as_local().unwrap().is_shared());
1538 tree.id()
1539 });
1540 executor.run_until_parked();
1541
1542 project_b1.read_with(cx_b, |project, cx| {
1543 assert!(project.worktree_for_id(worktree2_id, cx).is_some())
1544 });
1545
1546 let buffer_a1 = project_a1
1547 .update(cx_a, |p, cx| p.open_buffer((worktree1_id, "a.txt"), cx))
1548 .await
1549 .unwrap();
1550 let buffer_b1 = project_b1
1551 .update(cx_b, |p, cx| p.open_buffer((worktree1_id, "a.txt"), cx))
1552 .await
1553 .unwrap();
1554
1555 // Drop client A's connection.
1556 server.forbid_connections();
1557 server.disconnect_client(client_a.peer_id().unwrap());
1558 executor.advance_clock(RECEIVE_TIMEOUT);
1559
1560 project_a1.read_with(cx_a, |project, _| {
1561 assert!(project.is_shared());
1562 assert_eq!(project.collaborators().len(), 1);
1563 });
1564
1565 project_b1.read_with(cx_b, |project, _| {
1566 assert!(!project.is_disconnected());
1567 assert_eq!(project.collaborators().len(), 1);
1568 });
1569
1570 worktree_a1.read_with(cx_a, |tree, _| {
1571 assert!(tree.as_local().unwrap().is_shared())
1572 });
1573
1574 // While client A is disconnected, add and remove files from client A's project.
1575 client_a
1576 .fs()
1577 .insert_tree(
1578 "/root-1/dir1/subdir2",
1579 json!({
1580 "f.txt": "f-contents",
1581 "g.txt": "g-contents",
1582 "h.txt": "h-contents",
1583 "i.txt": "i-contents",
1584 }),
1585 )
1586 .await;
1587 client_a
1588 .fs()
1589 .remove_dir(
1590 "/root-1/dir1/subdir1".as_ref(),
1591 RemoveOptions {
1592 recursive: true,
1593 ..Default::default()
1594 },
1595 )
1596 .await
1597 .unwrap();
1598
1599 // While client A is disconnected, add and remove worktrees from client A's project.
1600 project_a1.update(cx_a, |project, cx| {
1601 project.remove_worktree(worktree2_id, cx)
1602 });
1603 let (worktree_a3, _) = project_a1
1604 .update(cx_a, |p, cx| {
1605 p.find_or_create_local_worktree("/root-1/dir3", true, cx)
1606 })
1607 .await
1608 .unwrap();
1609 worktree_a3
1610 .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1611 .await;
1612
1613 let worktree3_id = worktree_a3.read_with(cx_a, |tree, _| {
1614 assert!(!tree.as_local().unwrap().is_shared());
1615 tree.id()
1616 });
1617 executor.run_until_parked();
1618
1619 // While client A is disconnected, close project 2
1620 cx_a.update(|_| drop(project_a2));
1621
1622 // While client A is disconnected, mutate a buffer on both the host and the guest.
1623 buffer_a1.update(cx_a, |buf, cx| buf.edit([(0..0, "W")], None, cx));
1624 buffer_b1.update(cx_b, |buf, cx| buf.edit([(1..1, "Z")], None, cx));
1625 executor.run_until_parked();
1626
1627 // Client A reconnects. Their project is re-shared, and client B re-joins it.
1628 server.allow_connections();
1629 client_a
1630 .authenticate_and_connect(false, &cx_a.to_async())
1631 .await
1632 .unwrap();
1633 executor.run_until_parked();
1634
1635 project_a1.read_with(cx_a, |project, cx| {
1636 assert!(project.is_shared());
1637 assert!(worktree_a1.read(cx).as_local().unwrap().is_shared());
1638 assert_eq!(
1639 worktree_a1
1640 .read(cx)
1641 .snapshot()
1642 .paths()
1643 .map(|p| p.to_str().unwrap())
1644 .collect::<Vec<_>>(),
1645 vec![
1646 "a.txt",
1647 "b.txt",
1648 "subdir2",
1649 "subdir2/f.txt",
1650 "subdir2/g.txt",
1651 "subdir2/h.txt",
1652 "subdir2/i.txt"
1653 ]
1654 );
1655 assert!(worktree_a3.read(cx).as_local().unwrap().is_shared());
1656 assert_eq!(
1657 worktree_a3
1658 .read(cx)
1659 .snapshot()
1660 .paths()
1661 .map(|p| p.to_str().unwrap())
1662 .collect::<Vec<_>>(),
1663 vec!["w.txt", "x.txt", "y.txt"]
1664 );
1665 });
1666
1667 project_b1.read_with(cx_b, |project, cx| {
1668 assert!(!project.is_disconnected());
1669 assert_eq!(
1670 project
1671 .worktree_for_id(worktree1_id, cx)
1672 .unwrap()
1673 .read(cx)
1674 .snapshot()
1675 .paths()
1676 .map(|p| p.to_str().unwrap())
1677 .collect::<Vec<_>>(),
1678 vec![
1679 "a.txt",
1680 "b.txt",
1681 "subdir2",
1682 "subdir2/f.txt",
1683 "subdir2/g.txt",
1684 "subdir2/h.txt",
1685 "subdir2/i.txt"
1686 ]
1687 );
1688 assert!(project.worktree_for_id(worktree2_id, cx).is_none());
1689 assert_eq!(
1690 project
1691 .worktree_for_id(worktree3_id, cx)
1692 .unwrap()
1693 .read(cx)
1694 .snapshot()
1695 .paths()
1696 .map(|p| p.to_str().unwrap())
1697 .collect::<Vec<_>>(),
1698 vec!["w.txt", "x.txt", "y.txt"]
1699 );
1700 });
1701
1702 project_b2.read_with(cx_b, |project, _| assert!(project.is_disconnected()));
1703
1704 project_b3.read_with(cx_b, |project, _| assert!(!project.is_disconnected()));
1705
1706 buffer_a1.read_with(cx_a, |buffer, _| assert_eq!(buffer.text(), "WaZ"));
1707
1708 buffer_b1.read_with(cx_b, |buffer, _| assert_eq!(buffer.text(), "WaZ"));
1709
1710 // Drop client B's connection.
1711 server.forbid_connections();
1712 server.disconnect_client(client_b.peer_id().unwrap());
1713 executor.advance_clock(RECEIVE_TIMEOUT);
1714
1715 // While client B is disconnected, add and remove files from client A's project
1716 client_a
1717 .fs()
1718 .insert_file("/root-1/dir1/subdir2/j.txt", "j-contents".into())
1719 .await;
1720 client_a
1721 .fs()
1722 .remove_file("/root-1/dir1/subdir2/i.txt".as_ref(), Default::default())
1723 .await
1724 .unwrap();
1725
1726 // While client B is disconnected, add and remove worktrees from client A's project.
1727 let (worktree_a4, _) = project_a1
1728 .update(cx_a, |p, cx| {
1729 p.find_or_create_local_worktree("/root-1/dir4", true, cx)
1730 })
1731 .await
1732 .unwrap();
1733 executor.run_until_parked();
1734
1735 let worktree4_id = worktree_a4.read_with(cx_a, |tree, _| {
1736 assert!(tree.as_local().unwrap().is_shared());
1737 tree.id()
1738 });
1739 project_a1.update(cx_a, |project, cx| {
1740 project.remove_worktree(worktree3_id, cx)
1741 });
1742 executor.run_until_parked();
1743
1744 // While client B is disconnected, mutate a buffer on both the host and the guest.
1745 buffer_a1.update(cx_a, |buf, cx| buf.edit([(1..1, "X")], None, cx));
1746 buffer_b1.update(cx_b, |buf, cx| buf.edit([(2..2, "Y")], None, cx));
1747 executor.run_until_parked();
1748
1749 // While disconnected, close project 3
1750 cx_a.update(|_| drop(project_a3));
1751
1752 // Client B reconnects. They re-join the room and the remaining shared project.
1753 server.allow_connections();
1754 client_b
1755 .authenticate_and_connect(false, &cx_b.to_async())
1756 .await
1757 .unwrap();
1758 executor.run_until_parked();
1759
1760 project_b1.read_with(cx_b, |project, cx| {
1761 assert!(!project.is_disconnected());
1762 assert_eq!(
1763 project
1764 .worktree_for_id(worktree1_id, cx)
1765 .unwrap()
1766 .read(cx)
1767 .snapshot()
1768 .paths()
1769 .map(|p| p.to_str().unwrap())
1770 .collect::<Vec<_>>(),
1771 vec![
1772 "a.txt",
1773 "b.txt",
1774 "subdir2",
1775 "subdir2/f.txt",
1776 "subdir2/g.txt",
1777 "subdir2/h.txt",
1778 "subdir2/j.txt"
1779 ]
1780 );
1781 assert!(project.worktree_for_id(worktree2_id, cx).is_none());
1782 assert_eq!(
1783 project
1784 .worktree_for_id(worktree4_id, cx)
1785 .unwrap()
1786 .read(cx)
1787 .snapshot()
1788 .paths()
1789 .map(|p| p.to_str().unwrap())
1790 .collect::<Vec<_>>(),
1791 vec!["z.txt"]
1792 );
1793 });
1794
1795 project_b3.read_with(cx_b, |project, _| assert!(project.is_disconnected()));
1796
1797 buffer_a1.read_with(cx_a, |buffer, _| assert_eq!(buffer.text(), "WXaYZ"));
1798
1799 buffer_b1.read_with(cx_b, |buffer, _| assert_eq!(buffer.text(), "WXaYZ"));
1800}
1801
1802#[gpui::test(iterations = 10)]
1803async fn test_active_call_events(
1804 executor: BackgroundExecutor,
1805 cx_a: &mut TestAppContext,
1806 cx_b: &mut TestAppContext,
1807) {
1808 let mut server = TestServer::start(executor.clone()).await;
1809 let client_a = server.create_client(cx_a, "user_a").await;
1810 let client_b = server.create_client(cx_b, "user_b").await;
1811 client_a.fs().insert_tree("/a", json!({})).await;
1812 client_b.fs().insert_tree("/b", json!({})).await;
1813
1814 let (project_a, _) = client_a.build_local_project("/a", cx_a).await;
1815 let (project_b, _) = client_b.build_local_project("/b", cx_b).await;
1816
1817 server
1818 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
1819 .await;
1820 let active_call_a = cx_a.read(ActiveCall::global);
1821 let active_call_b = cx_b.read(ActiveCall::global);
1822
1823 let events_a = active_call_events(cx_a);
1824 let events_b = active_call_events(cx_b);
1825
1826 let project_a_id = active_call_a
1827 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
1828 .await
1829 .unwrap();
1830 executor.run_until_parked();
1831 assert_eq!(mem::take(&mut *events_a.borrow_mut()), vec![]);
1832 assert_eq!(
1833 mem::take(&mut *events_b.borrow_mut()),
1834 vec![room::Event::RemoteProjectShared {
1835 owner: Arc::new(User {
1836 id: client_a.user_id().unwrap(),
1837 github_login: "user_a".to_string(),
1838 avatar_uri: "avatar_a".into(),
1839 }),
1840 project_id: project_a_id,
1841 worktree_root_names: vec!["a".to_string()],
1842 }]
1843 );
1844
1845 let project_b_id = active_call_b
1846 .update(cx_b, |call, cx| call.share_project(project_b.clone(), cx))
1847 .await
1848 .unwrap();
1849 executor.run_until_parked();
1850 assert_eq!(
1851 mem::take(&mut *events_a.borrow_mut()),
1852 vec![room::Event::RemoteProjectShared {
1853 owner: Arc::new(User {
1854 id: client_b.user_id().unwrap(),
1855 github_login: "user_b".to_string(),
1856 avatar_uri: "avatar_b".into(),
1857 }),
1858 project_id: project_b_id,
1859 worktree_root_names: vec!["b".to_string()]
1860 }]
1861 );
1862 assert_eq!(mem::take(&mut *events_b.borrow_mut()), vec![]);
1863
1864 // Sharing a project twice is idempotent.
1865 let project_b_id_2 = active_call_b
1866 .update(cx_b, |call, cx| call.share_project(project_b.clone(), cx))
1867 .await
1868 .unwrap();
1869 assert_eq!(project_b_id_2, project_b_id);
1870 executor.run_until_parked();
1871 assert_eq!(mem::take(&mut *events_a.borrow_mut()), vec![]);
1872 assert_eq!(mem::take(&mut *events_b.borrow_mut()), vec![]);
1873
1874 // Unsharing a project should dispatch the RemoteProjectUnshared event.
1875 active_call_a
1876 .update(cx_a, |call, cx| call.hang_up(cx))
1877 .await
1878 .unwrap();
1879 executor.run_until_parked();
1880
1881 assert_eq!(
1882 mem::take(&mut *events_a.borrow_mut()),
1883 vec![room::Event::RoomLeft { channel_id: None }]
1884 );
1885 assert_eq!(
1886 mem::take(&mut *events_b.borrow_mut()),
1887 vec![room::Event::RemoteProjectUnshared {
1888 project_id: project_a_id,
1889 }]
1890 );
1891}
1892
1893fn active_call_events(cx: &mut TestAppContext) -> Rc<RefCell<Vec<room::Event>>> {
1894 let events = Rc::new(RefCell::new(Vec::new()));
1895 let active_call = cx.read(ActiveCall::global);
1896 cx.update({
1897 let events = events.clone();
1898 |cx| {
1899 cx.subscribe(&active_call, move |_, event, _| {
1900 events.borrow_mut().push(event.clone())
1901 })
1902 .detach()
1903 }
1904 });
1905 events
1906}
1907
1908#[gpui::test]
1909async fn test_mute_deafen(
1910 executor: BackgroundExecutor,
1911 cx_a: &mut TestAppContext,
1912 cx_b: &mut TestAppContext,
1913 cx_c: &mut TestAppContext,
1914) {
1915 let mut server = TestServer::start(executor.clone()).await;
1916 let client_a = server.create_client(cx_a, "user_a").await;
1917 let client_b = server.create_client(cx_b, "user_b").await;
1918 let client_c = server.create_client(cx_c, "user_c").await;
1919
1920 server
1921 .make_contacts(&mut [(&client_a, cx_a), (&client_b, cx_b), (&client_c, cx_c)])
1922 .await;
1923
1924 let active_call_a = cx_a.read(ActiveCall::global);
1925 let active_call_b = cx_b.read(ActiveCall::global);
1926 let active_call_c = cx_c.read(ActiveCall::global);
1927
1928 // User A calls user B, B answers.
1929 active_call_a
1930 .update(cx_a, |call, cx| {
1931 call.invite(client_b.user_id().unwrap(), None, cx)
1932 })
1933 .await
1934 .unwrap();
1935 executor.run_until_parked();
1936 active_call_b
1937 .update(cx_b, |call, cx| call.accept_incoming(cx))
1938 .await
1939 .unwrap();
1940 executor.run_until_parked();
1941
1942 let room_a = active_call_a.read_with(cx_a, |call, _| call.room().unwrap().clone());
1943 let room_b = active_call_b.read_with(cx_b, |call, _| call.room().unwrap().clone());
1944
1945 room_a.read_with(cx_a, |room, _| assert!(!room.is_muted()));
1946 room_b.read_with(cx_b, |room, _| assert!(!room.is_muted()));
1947
1948 // Users A and B are both muted.
1949 assert_eq!(
1950 participant_audio_state(&room_a, cx_a),
1951 &[ParticipantAudioState {
1952 user_id: client_b.user_id().unwrap(),
1953 is_muted: false,
1954 audio_tracks_playing: vec![true],
1955 }]
1956 );
1957 assert_eq!(
1958 participant_audio_state(&room_b, cx_b),
1959 &[ParticipantAudioState {
1960 user_id: client_a.user_id().unwrap(),
1961 is_muted: false,
1962 audio_tracks_playing: vec![true],
1963 }]
1964 );
1965
1966 // User A mutes
1967 room_a.update(cx_a, |room, cx| room.toggle_mute(cx));
1968 executor.run_until_parked();
1969
1970 // User A hears user B, but B doesn't hear A.
1971 room_a.read_with(cx_a, |room, _| assert!(room.is_muted()));
1972 room_b.read_with(cx_b, |room, _| assert!(!room.is_muted()));
1973 assert_eq!(
1974 participant_audio_state(&room_a, cx_a),
1975 &[ParticipantAudioState {
1976 user_id: client_b.user_id().unwrap(),
1977 is_muted: false,
1978 audio_tracks_playing: vec![true],
1979 }]
1980 );
1981 assert_eq!(
1982 participant_audio_state(&room_b, cx_b),
1983 &[ParticipantAudioState {
1984 user_id: client_a.user_id().unwrap(),
1985 is_muted: true,
1986 audio_tracks_playing: vec![true],
1987 }]
1988 );
1989
1990 // User A deafens
1991 room_a.update(cx_a, |room, cx| room.toggle_deafen(cx));
1992 executor.run_until_parked();
1993
1994 // User A does not hear user B.
1995 room_a.read_with(cx_a, |room, _| assert!(room.is_muted()));
1996 room_b.read_with(cx_b, |room, _| assert!(!room.is_muted()));
1997 assert_eq!(
1998 participant_audio_state(&room_a, cx_a),
1999 &[ParticipantAudioState {
2000 user_id: client_b.user_id().unwrap(),
2001 is_muted: false,
2002 audio_tracks_playing: vec![false],
2003 }]
2004 );
2005 assert_eq!(
2006 participant_audio_state(&room_b, cx_b),
2007 &[ParticipantAudioState {
2008 user_id: client_a.user_id().unwrap(),
2009 is_muted: true,
2010 audio_tracks_playing: vec![true],
2011 }]
2012 );
2013
2014 // User B calls user C, C joins.
2015 active_call_b
2016 .update(cx_b, |call, cx| {
2017 call.invite(client_c.user_id().unwrap(), None, cx)
2018 })
2019 .await
2020 .unwrap();
2021 executor.run_until_parked();
2022 active_call_c
2023 .update(cx_c, |call, cx| call.accept_incoming(cx))
2024 .await
2025 .unwrap();
2026 executor.run_until_parked();
2027
2028 // User A does not hear users B or C.
2029 assert_eq!(
2030 participant_audio_state(&room_a, cx_a),
2031 &[
2032 ParticipantAudioState {
2033 user_id: client_b.user_id().unwrap(),
2034 is_muted: false,
2035 audio_tracks_playing: vec![false],
2036 },
2037 ParticipantAudioState {
2038 user_id: client_c.user_id().unwrap(),
2039 is_muted: false,
2040 audio_tracks_playing: vec![false],
2041 }
2042 ]
2043 );
2044 assert_eq!(
2045 participant_audio_state(&room_b, cx_b),
2046 &[
2047 ParticipantAudioState {
2048 user_id: client_a.user_id().unwrap(),
2049 is_muted: true,
2050 audio_tracks_playing: vec![true],
2051 },
2052 ParticipantAudioState {
2053 user_id: client_c.user_id().unwrap(),
2054 is_muted: false,
2055 audio_tracks_playing: vec![true],
2056 }
2057 ]
2058 );
2059
2060 #[derive(PartialEq, Eq, Debug)]
2061 struct ParticipantAudioState {
2062 user_id: u64,
2063 is_muted: bool,
2064 audio_tracks_playing: Vec<bool>,
2065 }
2066
2067 fn participant_audio_state(
2068 room: &Model<Room>,
2069 cx: &TestAppContext,
2070 ) -> Vec<ParticipantAudioState> {
2071 room.read_with(cx, |room, _| {
2072 room.remote_participants()
2073 .iter()
2074 .map(|(user_id, participant)| ParticipantAudioState {
2075 user_id: *user_id,
2076 is_muted: participant.muted,
2077 audio_tracks_playing: participant
2078 .audio_tracks
2079 .values()
2080 .map(|track| track.is_playing())
2081 .collect(),
2082 })
2083 .collect::<Vec<_>>()
2084 })
2085 }
2086}
2087
2088#[gpui::test(iterations = 10)]
2089async fn test_room_location(
2090 executor: BackgroundExecutor,
2091 cx_a: &mut TestAppContext,
2092 cx_b: &mut TestAppContext,
2093) {
2094 let mut server = TestServer::start(executor.clone()).await;
2095 let client_a = server.create_client(cx_a, "user_a").await;
2096 let client_b = server.create_client(cx_b, "user_b").await;
2097 client_a.fs().insert_tree("/a", json!({})).await;
2098 client_b.fs().insert_tree("/b", json!({})).await;
2099
2100 let active_call_a = cx_a.read(ActiveCall::global);
2101 let active_call_b = cx_b.read(ActiveCall::global);
2102
2103 let a_notified = Rc::new(Cell::new(false));
2104 cx_a.update({
2105 let notified = a_notified.clone();
2106 |cx| {
2107 cx.observe(&active_call_a, move |_, _| notified.set(true))
2108 .detach()
2109 }
2110 });
2111
2112 let b_notified = Rc::new(Cell::new(false));
2113 cx_b.update({
2114 let b_notified = b_notified.clone();
2115 |cx| {
2116 cx.observe(&active_call_b, move |_, _| b_notified.set(true))
2117 .detach()
2118 }
2119 });
2120
2121 let (project_a, _) = client_a.build_local_project("/a", cx_a).await;
2122 active_call_a
2123 .update(cx_a, |call, cx| call.set_location(Some(&project_a), cx))
2124 .await
2125 .unwrap();
2126 let (project_b, _) = client_b.build_local_project("/b", cx_b).await;
2127
2128 server
2129 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
2130 .await;
2131
2132 let room_a = active_call_a.read_with(cx_a, |call, _| call.room().unwrap().clone());
2133
2134 let room_b = active_call_b.read_with(cx_b, |call, _| call.room().unwrap().clone());
2135 executor.run_until_parked();
2136 assert!(a_notified.take());
2137 assert_eq!(
2138 participant_locations(&room_a, cx_a),
2139 vec![("user_b".to_string(), ParticipantLocation::External)]
2140 );
2141 assert!(b_notified.take());
2142 assert_eq!(
2143 participant_locations(&room_b, cx_b),
2144 vec![("user_a".to_string(), ParticipantLocation::UnsharedProject)]
2145 );
2146
2147 let project_a_id = active_call_a
2148 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
2149 .await
2150 .unwrap();
2151 executor.run_until_parked();
2152 assert!(a_notified.take());
2153 assert_eq!(
2154 participant_locations(&room_a, cx_a),
2155 vec![("user_b".to_string(), ParticipantLocation::External)]
2156 );
2157 assert!(b_notified.take());
2158 assert_eq!(
2159 participant_locations(&room_b, cx_b),
2160 vec![(
2161 "user_a".to_string(),
2162 ParticipantLocation::SharedProject {
2163 project_id: project_a_id
2164 }
2165 )]
2166 );
2167
2168 let project_b_id = active_call_b
2169 .update(cx_b, |call, cx| call.share_project(project_b.clone(), cx))
2170 .await
2171 .unwrap();
2172 executor.run_until_parked();
2173 assert!(a_notified.take());
2174 assert_eq!(
2175 participant_locations(&room_a, cx_a),
2176 vec![("user_b".to_string(), ParticipantLocation::External)]
2177 );
2178 assert!(b_notified.take());
2179 assert_eq!(
2180 participant_locations(&room_b, cx_b),
2181 vec![(
2182 "user_a".to_string(),
2183 ParticipantLocation::SharedProject {
2184 project_id: project_a_id
2185 }
2186 )]
2187 );
2188
2189 active_call_b
2190 .update(cx_b, |call, cx| call.set_location(Some(&project_b), cx))
2191 .await
2192 .unwrap();
2193 executor.run_until_parked();
2194 assert!(a_notified.take());
2195 assert_eq!(
2196 participant_locations(&room_a, cx_a),
2197 vec![(
2198 "user_b".to_string(),
2199 ParticipantLocation::SharedProject {
2200 project_id: project_b_id
2201 }
2202 )]
2203 );
2204 assert!(b_notified.take());
2205 assert_eq!(
2206 participant_locations(&room_b, cx_b),
2207 vec![(
2208 "user_a".to_string(),
2209 ParticipantLocation::SharedProject {
2210 project_id: project_a_id
2211 }
2212 )]
2213 );
2214
2215 active_call_b
2216 .update(cx_b, |call, cx| call.set_location(None, cx))
2217 .await
2218 .unwrap();
2219 executor.run_until_parked();
2220 assert!(a_notified.take());
2221 assert_eq!(
2222 participant_locations(&room_a, cx_a),
2223 vec![("user_b".to_string(), ParticipantLocation::External)]
2224 );
2225 assert!(b_notified.take());
2226 assert_eq!(
2227 participant_locations(&room_b, cx_b),
2228 vec![(
2229 "user_a".to_string(),
2230 ParticipantLocation::SharedProject {
2231 project_id: project_a_id
2232 }
2233 )]
2234 );
2235
2236 fn participant_locations(
2237 room: &Model<Room>,
2238 cx: &TestAppContext,
2239 ) -> Vec<(String, ParticipantLocation)> {
2240 room.read_with(cx, |room, _| {
2241 room.remote_participants()
2242 .values()
2243 .map(|participant| {
2244 (
2245 participant.user.github_login.to_string(),
2246 participant.location,
2247 )
2248 })
2249 .collect()
2250 })
2251 }
2252}
2253
2254#[gpui::test(iterations = 10)]
2255async fn test_propagate_saves_and_fs_changes(
2256 executor: BackgroundExecutor,
2257 cx_a: &mut TestAppContext,
2258 cx_b: &mut TestAppContext,
2259 cx_c: &mut TestAppContext,
2260) {
2261 let mut server = TestServer::start(executor.clone()).await;
2262 let client_a = server.create_client(cx_a, "user_a").await;
2263 let client_b = server.create_client(cx_b, "user_b").await;
2264 let client_c = server.create_client(cx_c, "user_c").await;
2265
2266 server
2267 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b), (&client_c, cx_c)])
2268 .await;
2269 let active_call_a = cx_a.read(ActiveCall::global);
2270
2271 let rust = Arc::new(Language::new(
2272 LanguageConfig {
2273 name: "Rust".into(),
2274 matcher: LanguageMatcher {
2275 path_suffixes: vec!["rs".to_string()],
2276 ..Default::default()
2277 },
2278 ..Default::default()
2279 },
2280 Some(tree_sitter_rust::language()),
2281 ));
2282 let javascript = Arc::new(Language::new(
2283 LanguageConfig {
2284 name: "JavaScript".into(),
2285 matcher: LanguageMatcher {
2286 path_suffixes: vec!["js".to_string()],
2287 ..Default::default()
2288 },
2289 ..Default::default()
2290 },
2291 Some(tree_sitter_rust::language()),
2292 ));
2293 for client in [&client_a, &client_b, &client_c] {
2294 client.language_registry().add(rust.clone());
2295 client.language_registry().add(javascript.clone());
2296 }
2297
2298 client_a
2299 .fs()
2300 .insert_tree(
2301 "/a",
2302 json!({
2303 "file1.rs": "",
2304 "file2": ""
2305 }),
2306 )
2307 .await;
2308 let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
2309
2310 let worktree_a = project_a.read_with(cx_a, |p, _| p.worktrees().next().unwrap());
2311 let project_id = active_call_a
2312 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
2313 .await
2314 .unwrap();
2315
2316 // Join that worktree as clients B and C.
2317 let project_b = client_b.build_remote_project(project_id, cx_b).await;
2318 let project_c = client_c.build_remote_project(project_id, cx_c).await;
2319
2320 let worktree_b = project_b.read_with(cx_b, |p, _| p.worktrees().next().unwrap());
2321
2322 let worktree_c = project_c.read_with(cx_c, |p, _| p.worktrees().next().unwrap());
2323
2324 // Open and edit a buffer as both guests B and C.
2325 let buffer_b = project_b
2326 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "file1.rs"), cx))
2327 .await
2328 .unwrap();
2329 let buffer_c = project_c
2330 .update(cx_c, |p, cx| p.open_buffer((worktree_id, "file1.rs"), cx))
2331 .await
2332 .unwrap();
2333
2334 buffer_b.read_with(cx_b, |buffer, _| {
2335 assert_eq!(&*buffer.language().unwrap().name(), "Rust");
2336 });
2337
2338 buffer_c.read_with(cx_c, |buffer, _| {
2339 assert_eq!(&*buffer.language().unwrap().name(), "Rust");
2340 });
2341 buffer_b.update(cx_b, |buf, cx| buf.edit([(0..0, "i-am-b, ")], None, cx));
2342 buffer_c.update(cx_c, |buf, cx| buf.edit([(0..0, "i-am-c, ")], None, cx));
2343
2344 // Open and edit that buffer as the host.
2345 let buffer_a = project_a
2346 .update(cx_a, |p, cx| p.open_buffer((worktree_id, "file1.rs"), cx))
2347 .await
2348 .unwrap();
2349
2350 executor.run_until_parked();
2351
2352 buffer_a.read_with(cx_a, |buf, _| assert_eq!(buf.text(), "i-am-c, i-am-b, "));
2353 buffer_a.update(cx_a, |buf, cx| {
2354 buf.edit([(buf.len()..buf.len(), "i-am-a")], None, cx)
2355 });
2356
2357 executor.run_until_parked();
2358
2359 buffer_a.read_with(cx_a, |buf, _| {
2360 assert_eq!(buf.text(), "i-am-c, i-am-b, i-am-a");
2361 });
2362
2363 buffer_b.read_with(cx_b, |buf, _| {
2364 assert_eq!(buf.text(), "i-am-c, i-am-b, i-am-a");
2365 });
2366
2367 buffer_c.read_with(cx_c, |buf, _| {
2368 assert_eq!(buf.text(), "i-am-c, i-am-b, i-am-a");
2369 });
2370
2371 // Edit the buffer as the host and concurrently save as guest B.
2372 let save_b = project_b.update(cx_b, |project, cx| {
2373 project.save_buffer(buffer_b.clone(), cx)
2374 });
2375 buffer_a.update(cx_a, |buf, cx| buf.edit([(0..0, "hi-a, ")], None, cx));
2376 save_b.await.unwrap();
2377 assert_eq!(
2378 client_a.fs().load("/a/file1.rs".as_ref()).await.unwrap(),
2379 "hi-a, i-am-c, i-am-b, i-am-a"
2380 );
2381
2382 executor.run_until_parked();
2383
2384 buffer_a.read_with(cx_a, |buf, _| assert!(!buf.is_dirty()));
2385
2386 buffer_b.read_with(cx_b, |buf, _| assert!(!buf.is_dirty()));
2387
2388 buffer_c.read_with(cx_c, |buf, _| assert!(!buf.is_dirty()));
2389
2390 // Make changes on host's file system, see those changes on guest worktrees.
2391 client_a
2392 .fs()
2393 .rename(
2394 "/a/file1.rs".as_ref(),
2395 "/a/file1.js".as_ref(),
2396 Default::default(),
2397 )
2398 .await
2399 .unwrap();
2400 client_a
2401 .fs()
2402 .rename("/a/file2".as_ref(), "/a/file3".as_ref(), Default::default())
2403 .await
2404 .unwrap();
2405 client_a.fs().insert_file("/a/file4", "4".into()).await;
2406 executor.run_until_parked();
2407
2408 worktree_a.read_with(cx_a, |tree, _| {
2409 assert_eq!(
2410 tree.paths()
2411 .map(|p| p.to_string_lossy())
2412 .collect::<Vec<_>>(),
2413 ["file1.js", "file3", "file4"]
2414 )
2415 });
2416
2417 worktree_b.read_with(cx_b, |tree, _| {
2418 assert_eq!(
2419 tree.paths()
2420 .map(|p| p.to_string_lossy())
2421 .collect::<Vec<_>>(),
2422 ["file1.js", "file3", "file4"]
2423 )
2424 });
2425
2426 worktree_c.read_with(cx_c, |tree, _| {
2427 assert_eq!(
2428 tree.paths()
2429 .map(|p| p.to_string_lossy())
2430 .collect::<Vec<_>>(),
2431 ["file1.js", "file3", "file4"]
2432 )
2433 });
2434
2435 // Ensure buffer files are updated as well.
2436
2437 buffer_a.read_with(cx_a, |buffer, _| {
2438 assert_eq!(buffer.file().unwrap().path().to_str(), Some("file1.js"));
2439 assert_eq!(&*buffer.language().unwrap().name(), "JavaScript");
2440 });
2441
2442 buffer_b.read_with(cx_b, |buffer, _| {
2443 assert_eq!(buffer.file().unwrap().path().to_str(), Some("file1.js"));
2444 assert_eq!(&*buffer.language().unwrap().name(), "JavaScript");
2445 });
2446
2447 buffer_c.read_with(cx_c, |buffer, _| {
2448 assert_eq!(buffer.file().unwrap().path().to_str(), Some("file1.js"));
2449 assert_eq!(&*buffer.language().unwrap().name(), "JavaScript");
2450 });
2451
2452 let new_buffer_a = project_a
2453 .update(cx_a, |p, cx| p.create_buffer(cx))
2454 .await
2455 .unwrap();
2456
2457 let new_buffer_id = new_buffer_a.read_with(cx_a, |buffer, _| buffer.remote_id());
2458 let new_buffer_b = project_b
2459 .update(cx_b, |p, cx| p.open_buffer_by_id(new_buffer_id, cx))
2460 .await
2461 .unwrap();
2462
2463 new_buffer_b.read_with(cx_b, |buffer, _| {
2464 assert!(buffer.file().is_none());
2465 });
2466
2467 new_buffer_a.update(cx_a, |buffer, cx| {
2468 buffer.edit([(0..0, "ok")], None, cx);
2469 });
2470 project_a
2471 .update(cx_a, |project, cx| {
2472 let path = ProjectPath {
2473 path: Arc::from(Path::new("file3.rs")),
2474 worktree_id: worktree_a.read(cx).id(),
2475 };
2476
2477 project.save_buffer_as(new_buffer_a.clone(), path, cx)
2478 })
2479 .await
2480 .unwrap();
2481
2482 executor.run_until_parked();
2483
2484 new_buffer_b.read_with(cx_b, |buffer_b, _| {
2485 assert_eq!(
2486 buffer_b.file().unwrap().path().as_ref(),
2487 Path::new("file3.rs")
2488 );
2489
2490 new_buffer_a.read_with(cx_a, |buffer_a, _| {
2491 assert_eq!(buffer_b.saved_mtime(), buffer_a.saved_mtime());
2492 assert_eq!(buffer_b.saved_version(), buffer_a.saved_version());
2493 });
2494 });
2495}
2496
2497#[gpui::test(iterations = 10)]
2498async fn test_git_diff_base_change(
2499 executor: BackgroundExecutor,
2500 cx_a: &mut TestAppContext,
2501 cx_b: &mut TestAppContext,
2502) {
2503 let mut server = TestServer::start(executor.clone()).await;
2504 let client_a = server.create_client(cx_a, "user_a").await;
2505 let client_b = server.create_client(cx_b, "user_b").await;
2506 server
2507 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
2508 .await;
2509 let active_call_a = cx_a.read(ActiveCall::global);
2510
2511 client_a
2512 .fs()
2513 .insert_tree(
2514 "/dir",
2515 json!({
2516 ".git": {},
2517 "sub": {
2518 ".git": {},
2519 "b.txt": "
2520 one
2521 two
2522 three
2523 ".unindent(),
2524 },
2525 "a.txt": "
2526 one
2527 two
2528 three
2529 ".unindent(),
2530 }),
2531 )
2532 .await;
2533
2534 let (project_local, worktree_id) = client_a.build_local_project("/dir", cx_a).await;
2535 let project_id = active_call_a
2536 .update(cx_a, |call, cx| {
2537 call.share_project(project_local.clone(), cx)
2538 })
2539 .await
2540 .unwrap();
2541
2542 let project_remote = client_b.build_remote_project(project_id, cx_b).await;
2543
2544 let diff_base = "
2545 one
2546 three
2547 "
2548 .unindent();
2549
2550 let new_diff_base = "
2551 one
2552 two
2553 "
2554 .unindent();
2555
2556 client_a.fs().set_index_for_repo(
2557 Path::new("/dir/.git"),
2558 &[(Path::new("a.txt"), diff_base.clone())],
2559 );
2560
2561 // Create the buffer
2562 let buffer_local_a = project_local
2563 .update(cx_a, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
2564 .await
2565 .unwrap();
2566
2567 // Wait for it to catch up to the new diff
2568 executor.run_until_parked();
2569
2570 // Smoke test diffing
2571
2572 buffer_local_a.read_with(cx_a, |buffer, _| {
2573 assert_eq!(buffer.diff_base(), Some(diff_base.as_ref()));
2574 git::diff::assert_hunks(
2575 buffer.snapshot().git_diff_hunks_in_row_range(0..4),
2576 &buffer,
2577 &diff_base,
2578 &[(1..2, "", "two\n")],
2579 );
2580 });
2581
2582 // Create remote buffer
2583 let buffer_remote_a = project_remote
2584 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
2585 .await
2586 .unwrap();
2587
2588 // Wait remote buffer to catch up to the new diff
2589 executor.run_until_parked();
2590
2591 // Smoke test diffing
2592
2593 buffer_remote_a.read_with(cx_b, |buffer, _| {
2594 assert_eq!(buffer.diff_base(), Some(diff_base.as_ref()));
2595 git::diff::assert_hunks(
2596 buffer.snapshot().git_diff_hunks_in_row_range(0..4),
2597 &buffer,
2598 &diff_base,
2599 &[(1..2, "", "two\n")],
2600 );
2601 });
2602
2603 client_a.fs().set_index_for_repo(
2604 Path::new("/dir/.git"),
2605 &[(Path::new("a.txt"), new_diff_base.clone())],
2606 );
2607
2608 // Wait for buffer_local_a to receive it
2609 executor.run_until_parked();
2610
2611 // Smoke test new diffing
2612
2613 buffer_local_a.read_with(cx_a, |buffer, _| {
2614 assert_eq!(buffer.diff_base(), Some(new_diff_base.as_ref()));
2615
2616 git::diff::assert_hunks(
2617 buffer.snapshot().git_diff_hunks_in_row_range(0..4),
2618 &buffer,
2619 &diff_base,
2620 &[(2..3, "", "three\n")],
2621 );
2622 });
2623
2624 // Smoke test B
2625
2626 buffer_remote_a.read_with(cx_b, |buffer, _| {
2627 assert_eq!(buffer.diff_base(), Some(new_diff_base.as_ref()));
2628 git::diff::assert_hunks(
2629 buffer.snapshot().git_diff_hunks_in_row_range(0..4),
2630 &buffer,
2631 &diff_base,
2632 &[(2..3, "", "three\n")],
2633 );
2634 });
2635
2636 //Nested git dir
2637
2638 let diff_base = "
2639 one
2640 three
2641 "
2642 .unindent();
2643
2644 let new_diff_base = "
2645 one
2646 two
2647 "
2648 .unindent();
2649
2650 client_a.fs().set_index_for_repo(
2651 Path::new("/dir/sub/.git"),
2652 &[(Path::new("b.txt"), diff_base.clone())],
2653 );
2654
2655 // Create the buffer
2656 let buffer_local_b = project_local
2657 .update(cx_a, |p, cx| p.open_buffer((worktree_id, "sub/b.txt"), cx))
2658 .await
2659 .unwrap();
2660
2661 // Wait for it to catch up to the new diff
2662 executor.run_until_parked();
2663
2664 // Smoke test diffing
2665
2666 buffer_local_b.read_with(cx_a, |buffer, _| {
2667 assert_eq!(buffer.diff_base(), Some(diff_base.as_ref()));
2668 git::diff::assert_hunks(
2669 buffer.snapshot().git_diff_hunks_in_row_range(0..4),
2670 &buffer,
2671 &diff_base,
2672 &[(1..2, "", "two\n")],
2673 );
2674 });
2675
2676 // Create remote buffer
2677 let buffer_remote_b = project_remote
2678 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "sub/b.txt"), cx))
2679 .await
2680 .unwrap();
2681
2682 // Wait remote buffer to catch up to the new diff
2683 executor.run_until_parked();
2684
2685 // Smoke test diffing
2686
2687 buffer_remote_b.read_with(cx_b, |buffer, _| {
2688 assert_eq!(buffer.diff_base(), Some(diff_base.as_ref()));
2689 git::diff::assert_hunks(
2690 buffer.snapshot().git_diff_hunks_in_row_range(0..4),
2691 &buffer,
2692 &diff_base,
2693 &[(1..2, "", "two\n")],
2694 );
2695 });
2696
2697 client_a.fs().set_index_for_repo(
2698 Path::new("/dir/sub/.git"),
2699 &[(Path::new("b.txt"), new_diff_base.clone())],
2700 );
2701
2702 // Wait for buffer_local_b to receive it
2703 executor.run_until_parked();
2704
2705 // Smoke test new diffing
2706
2707 buffer_local_b.read_with(cx_a, |buffer, _| {
2708 assert_eq!(buffer.diff_base(), Some(new_diff_base.as_ref()));
2709 println!("{:?}", buffer.as_rope().to_string());
2710 println!("{:?}", buffer.diff_base());
2711 println!(
2712 "{:?}",
2713 buffer
2714 .snapshot()
2715 .git_diff_hunks_in_row_range(0..4)
2716 .collect::<Vec<_>>()
2717 );
2718
2719 git::diff::assert_hunks(
2720 buffer.snapshot().git_diff_hunks_in_row_range(0..4),
2721 &buffer,
2722 &diff_base,
2723 &[(2..3, "", "three\n")],
2724 );
2725 });
2726
2727 // Smoke test B
2728
2729 buffer_remote_b.read_with(cx_b, |buffer, _| {
2730 assert_eq!(buffer.diff_base(), Some(new_diff_base.as_ref()));
2731 git::diff::assert_hunks(
2732 buffer.snapshot().git_diff_hunks_in_row_range(0..4),
2733 &buffer,
2734 &diff_base,
2735 &[(2..3, "", "three\n")],
2736 );
2737 });
2738}
2739
2740#[gpui::test]
2741async fn test_git_branch_name(
2742 executor: BackgroundExecutor,
2743 cx_a: &mut TestAppContext,
2744 cx_b: &mut TestAppContext,
2745 cx_c: &mut TestAppContext,
2746) {
2747 let mut server = TestServer::start(executor.clone()).await;
2748 let client_a = server.create_client(cx_a, "user_a").await;
2749 let client_b = server.create_client(cx_b, "user_b").await;
2750 let client_c = server.create_client(cx_c, "user_c").await;
2751 server
2752 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b), (&client_c, cx_c)])
2753 .await;
2754 let active_call_a = cx_a.read(ActiveCall::global);
2755
2756 client_a
2757 .fs()
2758 .insert_tree(
2759 "/dir",
2760 json!({
2761 ".git": {},
2762 }),
2763 )
2764 .await;
2765
2766 let (project_local, _worktree_id) = client_a.build_local_project("/dir", cx_a).await;
2767 let project_id = active_call_a
2768 .update(cx_a, |call, cx| {
2769 call.share_project(project_local.clone(), cx)
2770 })
2771 .await
2772 .unwrap();
2773
2774 let project_remote = client_b.build_remote_project(project_id, cx_b).await;
2775 client_a
2776 .fs()
2777 .set_branch_name(Path::new("/dir/.git"), Some("branch-1"));
2778
2779 // Wait for it to catch up to the new branch
2780 executor.run_until_parked();
2781
2782 #[track_caller]
2783 fn assert_branch(branch_name: Option<impl Into<String>>, project: &Project, cx: &AppContext) {
2784 let branch_name = branch_name.map(Into::into);
2785 let worktrees = project.visible_worktrees(cx).collect::<Vec<_>>();
2786 assert_eq!(worktrees.len(), 1);
2787 let worktree = worktrees[0].clone();
2788 let root_entry = worktree.read(cx).snapshot().root_git_entry().unwrap();
2789 assert_eq!(root_entry.branch(), branch_name.map(Into::into));
2790 }
2791
2792 // Smoke test branch reading
2793
2794 project_local.read_with(cx_a, |project, cx| {
2795 assert_branch(Some("branch-1"), project, cx)
2796 });
2797
2798 project_remote.read_with(cx_b, |project, cx| {
2799 assert_branch(Some("branch-1"), project, cx)
2800 });
2801
2802 client_a
2803 .fs()
2804 .set_branch_name(Path::new("/dir/.git"), Some("branch-2"));
2805
2806 // Wait for buffer_local_a to receive it
2807 executor.run_until_parked();
2808
2809 // Smoke test branch reading
2810
2811 project_local.read_with(cx_a, |project, cx| {
2812 assert_branch(Some("branch-2"), project, cx)
2813 });
2814
2815 project_remote.read_with(cx_b, |project, cx| {
2816 assert_branch(Some("branch-2"), project, cx)
2817 });
2818
2819 let project_remote_c = client_c.build_remote_project(project_id, cx_c).await;
2820 executor.run_until_parked();
2821
2822 project_remote_c.read_with(cx_c, |project, cx| {
2823 assert_branch(Some("branch-2"), project, cx)
2824 });
2825}
2826
2827#[gpui::test]
2828async fn test_git_status_sync(
2829 executor: BackgroundExecutor,
2830 cx_a: &mut TestAppContext,
2831 cx_b: &mut TestAppContext,
2832 cx_c: &mut TestAppContext,
2833) {
2834 let mut server = TestServer::start(executor.clone()).await;
2835 let client_a = server.create_client(cx_a, "user_a").await;
2836 let client_b = server.create_client(cx_b, "user_b").await;
2837 let client_c = server.create_client(cx_c, "user_c").await;
2838 server
2839 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b), (&client_c, cx_c)])
2840 .await;
2841 let active_call_a = cx_a.read(ActiveCall::global);
2842
2843 client_a
2844 .fs()
2845 .insert_tree(
2846 "/dir",
2847 json!({
2848 ".git": {},
2849 "a.txt": "a",
2850 "b.txt": "b",
2851 }),
2852 )
2853 .await;
2854
2855 const A_TXT: &str = "a.txt";
2856 const B_TXT: &str = "b.txt";
2857
2858 client_a.fs().set_status_for_repo_via_git_operation(
2859 Path::new("/dir/.git"),
2860 &[
2861 (&Path::new(A_TXT), GitFileStatus::Added),
2862 (&Path::new(B_TXT), GitFileStatus::Added),
2863 ],
2864 );
2865
2866 let (project_local, _worktree_id) = client_a.build_local_project("/dir", cx_a).await;
2867 let project_id = active_call_a
2868 .update(cx_a, |call, cx| {
2869 call.share_project(project_local.clone(), cx)
2870 })
2871 .await
2872 .unwrap();
2873
2874 let project_remote = client_b.build_remote_project(project_id, cx_b).await;
2875
2876 // Wait for it to catch up to the new status
2877 executor.run_until_parked();
2878
2879 #[track_caller]
2880 fn assert_status(
2881 file: &impl AsRef<Path>,
2882 status: Option<GitFileStatus>,
2883 project: &Project,
2884 cx: &AppContext,
2885 ) {
2886 let file = file.as_ref();
2887 let worktrees = project.visible_worktrees(cx).collect::<Vec<_>>();
2888 assert_eq!(worktrees.len(), 1);
2889 let worktree = worktrees[0].clone();
2890 let snapshot = worktree.read(cx).snapshot();
2891 assert_eq!(snapshot.status_for_file(file), status);
2892 }
2893
2894 // Smoke test status reading
2895
2896 project_local.read_with(cx_a, |project, cx| {
2897 assert_status(&Path::new(A_TXT), Some(GitFileStatus::Added), project, cx);
2898 assert_status(&Path::new(B_TXT), Some(GitFileStatus::Added), project, cx);
2899 });
2900
2901 project_remote.read_with(cx_b, |project, cx| {
2902 assert_status(&Path::new(A_TXT), Some(GitFileStatus::Added), project, cx);
2903 assert_status(&Path::new(B_TXT), Some(GitFileStatus::Added), project, cx);
2904 });
2905
2906 client_a.fs().set_status_for_repo_via_working_copy_change(
2907 Path::new("/dir/.git"),
2908 &[
2909 (&Path::new(A_TXT), GitFileStatus::Modified),
2910 (&Path::new(B_TXT), GitFileStatus::Modified),
2911 ],
2912 );
2913
2914 // Wait for buffer_local_a to receive it
2915 executor.run_until_parked();
2916
2917 // Smoke test status reading
2918
2919 project_local.read_with(cx_a, |project, cx| {
2920 assert_status(
2921 &Path::new(A_TXT),
2922 Some(GitFileStatus::Modified),
2923 project,
2924 cx,
2925 );
2926 assert_status(
2927 &Path::new(B_TXT),
2928 Some(GitFileStatus::Modified),
2929 project,
2930 cx,
2931 );
2932 });
2933
2934 project_remote.read_with(cx_b, |project, cx| {
2935 assert_status(
2936 &Path::new(A_TXT),
2937 Some(GitFileStatus::Modified),
2938 project,
2939 cx,
2940 );
2941 assert_status(
2942 &Path::new(B_TXT),
2943 Some(GitFileStatus::Modified),
2944 project,
2945 cx,
2946 );
2947 });
2948
2949 // And synchronization while joining
2950 let project_remote_c = client_c.build_remote_project(project_id, cx_c).await;
2951 executor.run_until_parked();
2952
2953 project_remote_c.read_with(cx_c, |project, cx| {
2954 assert_status(
2955 &Path::new(A_TXT),
2956 Some(GitFileStatus::Modified),
2957 project,
2958 cx,
2959 );
2960 assert_status(
2961 &Path::new(B_TXT),
2962 Some(GitFileStatus::Modified),
2963 project,
2964 cx,
2965 );
2966 });
2967}
2968
2969#[gpui::test(iterations = 10)]
2970async fn test_fs_operations(
2971 executor: BackgroundExecutor,
2972 cx_a: &mut TestAppContext,
2973 cx_b: &mut TestAppContext,
2974) {
2975 let mut server = TestServer::start(executor.clone()).await;
2976 let client_a = server.create_client(cx_a, "user_a").await;
2977 let client_b = server.create_client(cx_b, "user_b").await;
2978 server
2979 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
2980 .await;
2981 let active_call_a = cx_a.read(ActiveCall::global);
2982
2983 client_a
2984 .fs()
2985 .insert_tree(
2986 "/dir",
2987 json!({
2988 "a.txt": "a-contents",
2989 "b.txt": "b-contents",
2990 }),
2991 )
2992 .await;
2993 let (project_a, worktree_id) = client_a.build_local_project("/dir", cx_a).await;
2994 let project_id = active_call_a
2995 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
2996 .await
2997 .unwrap();
2998 let project_b = client_b.build_remote_project(project_id, cx_b).await;
2999
3000 let worktree_a = project_a.read_with(cx_a, |project, _| project.worktrees().next().unwrap());
3001
3002 let worktree_b = project_b.read_with(cx_b, |project, _| project.worktrees().next().unwrap());
3003
3004 let entry = project_b
3005 .update(cx_b, |project, cx| {
3006 project.create_entry((worktree_id, "c.txt"), false, cx)
3007 })
3008 .await
3009 .unwrap()
3010 .unwrap();
3011
3012 worktree_a.read_with(cx_a, |worktree, _| {
3013 assert_eq!(
3014 worktree
3015 .paths()
3016 .map(|p| p.to_string_lossy())
3017 .collect::<Vec<_>>(),
3018 ["a.txt", "b.txt", "c.txt"]
3019 );
3020 });
3021
3022 worktree_b.read_with(cx_b, |worktree, _| {
3023 assert_eq!(
3024 worktree
3025 .paths()
3026 .map(|p| p.to_string_lossy())
3027 .collect::<Vec<_>>(),
3028 ["a.txt", "b.txt", "c.txt"]
3029 );
3030 });
3031
3032 project_b
3033 .update(cx_b, |project, cx| {
3034 project.rename_entry(entry.id, Path::new("d.txt"), cx)
3035 })
3036 .await
3037 .unwrap()
3038 .unwrap();
3039
3040 worktree_a.read_with(cx_a, |worktree, _| {
3041 assert_eq!(
3042 worktree
3043 .paths()
3044 .map(|p| p.to_string_lossy())
3045 .collect::<Vec<_>>(),
3046 ["a.txt", "b.txt", "d.txt"]
3047 );
3048 });
3049
3050 worktree_b.read_with(cx_b, |worktree, _| {
3051 assert_eq!(
3052 worktree
3053 .paths()
3054 .map(|p| p.to_string_lossy())
3055 .collect::<Vec<_>>(),
3056 ["a.txt", "b.txt", "d.txt"]
3057 );
3058 });
3059
3060 let dir_entry = project_b
3061 .update(cx_b, |project, cx| {
3062 project.create_entry((worktree_id, "DIR"), true, cx)
3063 })
3064 .await
3065 .unwrap()
3066 .unwrap();
3067
3068 worktree_a.read_with(cx_a, |worktree, _| {
3069 assert_eq!(
3070 worktree
3071 .paths()
3072 .map(|p| p.to_string_lossy())
3073 .collect::<Vec<_>>(),
3074 ["DIR", "a.txt", "b.txt", "d.txt"]
3075 );
3076 });
3077
3078 worktree_b.read_with(cx_b, |worktree, _| {
3079 assert_eq!(
3080 worktree
3081 .paths()
3082 .map(|p| p.to_string_lossy())
3083 .collect::<Vec<_>>(),
3084 ["DIR", "a.txt", "b.txt", "d.txt"]
3085 );
3086 });
3087
3088 project_b
3089 .update(cx_b, |project, cx| {
3090 project.create_entry((worktree_id, "DIR/e.txt"), false, cx)
3091 })
3092 .await
3093 .unwrap()
3094 .unwrap();
3095 project_b
3096 .update(cx_b, |project, cx| {
3097 project.create_entry((worktree_id, "DIR/SUBDIR"), true, cx)
3098 })
3099 .await
3100 .unwrap()
3101 .unwrap();
3102 project_b
3103 .update(cx_b, |project, cx| {
3104 project.create_entry((worktree_id, "DIR/SUBDIR/f.txt"), false, cx)
3105 })
3106 .await
3107 .unwrap()
3108 .unwrap();
3109
3110 worktree_a.read_with(cx_a, |worktree, _| {
3111 assert_eq!(
3112 worktree
3113 .paths()
3114 .map(|p| p.to_string_lossy())
3115 .collect::<Vec<_>>(),
3116 [
3117 "DIR",
3118 "DIR/SUBDIR",
3119 "DIR/SUBDIR/f.txt",
3120 "DIR/e.txt",
3121 "a.txt",
3122 "b.txt",
3123 "d.txt"
3124 ]
3125 );
3126 });
3127
3128 worktree_b.read_with(cx_b, |worktree, _| {
3129 assert_eq!(
3130 worktree
3131 .paths()
3132 .map(|p| p.to_string_lossy())
3133 .collect::<Vec<_>>(),
3134 [
3135 "DIR",
3136 "DIR/SUBDIR",
3137 "DIR/SUBDIR/f.txt",
3138 "DIR/e.txt",
3139 "a.txt",
3140 "b.txt",
3141 "d.txt"
3142 ]
3143 );
3144 });
3145
3146 project_b
3147 .update(cx_b, |project, cx| {
3148 project.copy_entry(entry.id, Path::new("f.txt"), cx)
3149 })
3150 .await
3151 .unwrap()
3152 .unwrap();
3153
3154 worktree_a.read_with(cx_a, |worktree, _| {
3155 assert_eq!(
3156 worktree
3157 .paths()
3158 .map(|p| p.to_string_lossy())
3159 .collect::<Vec<_>>(),
3160 [
3161 "DIR",
3162 "DIR/SUBDIR",
3163 "DIR/SUBDIR/f.txt",
3164 "DIR/e.txt",
3165 "a.txt",
3166 "b.txt",
3167 "d.txt",
3168 "f.txt"
3169 ]
3170 );
3171 });
3172
3173 worktree_b.read_with(cx_b, |worktree, _| {
3174 assert_eq!(
3175 worktree
3176 .paths()
3177 .map(|p| p.to_string_lossy())
3178 .collect::<Vec<_>>(),
3179 [
3180 "DIR",
3181 "DIR/SUBDIR",
3182 "DIR/SUBDIR/f.txt",
3183 "DIR/e.txt",
3184 "a.txt",
3185 "b.txt",
3186 "d.txt",
3187 "f.txt"
3188 ]
3189 );
3190 });
3191
3192 project_b
3193 .update(cx_b, |project, cx| {
3194 project.delete_entry(dir_entry.id, false, cx).unwrap()
3195 })
3196 .await
3197 .unwrap();
3198 executor.run_until_parked();
3199
3200 worktree_a.read_with(cx_a, |worktree, _| {
3201 assert_eq!(
3202 worktree
3203 .paths()
3204 .map(|p| p.to_string_lossy())
3205 .collect::<Vec<_>>(),
3206 ["a.txt", "b.txt", "d.txt", "f.txt"]
3207 );
3208 });
3209
3210 worktree_b.read_with(cx_b, |worktree, _| {
3211 assert_eq!(
3212 worktree
3213 .paths()
3214 .map(|p| p.to_string_lossy())
3215 .collect::<Vec<_>>(),
3216 ["a.txt", "b.txt", "d.txt", "f.txt"]
3217 );
3218 });
3219
3220 project_b
3221 .update(cx_b, |project, cx| {
3222 project.delete_entry(entry.id, false, cx).unwrap()
3223 })
3224 .await
3225 .unwrap();
3226
3227 worktree_a.read_with(cx_a, |worktree, _| {
3228 assert_eq!(
3229 worktree
3230 .paths()
3231 .map(|p| p.to_string_lossy())
3232 .collect::<Vec<_>>(),
3233 ["a.txt", "b.txt", "f.txt"]
3234 );
3235 });
3236
3237 worktree_b.read_with(cx_b, |worktree, _| {
3238 assert_eq!(
3239 worktree
3240 .paths()
3241 .map(|p| p.to_string_lossy())
3242 .collect::<Vec<_>>(),
3243 ["a.txt", "b.txt", "f.txt"]
3244 );
3245 });
3246}
3247
3248#[gpui::test(iterations = 10)]
3249async fn test_local_settings(
3250 executor: BackgroundExecutor,
3251 cx_a: &mut TestAppContext,
3252 cx_b: &mut TestAppContext,
3253) {
3254 let mut server = TestServer::start(executor.clone()).await;
3255 let client_a = server.create_client(cx_a, "user_a").await;
3256 let client_b = server.create_client(cx_b, "user_b").await;
3257 server
3258 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
3259 .await;
3260 let active_call_a = cx_a.read(ActiveCall::global);
3261
3262 // As client A, open a project that contains some local settings files
3263 client_a
3264 .fs()
3265 .insert_tree(
3266 "/dir",
3267 json!({
3268 ".zed": {
3269 "settings.json": r#"{ "tab_size": 2 }"#
3270 },
3271 "a": {
3272 ".zed": {
3273 "settings.json": r#"{ "tab_size": 8 }"#
3274 },
3275 "a.txt": "a-contents",
3276 },
3277 "b": {
3278 "b.txt": "b-contents",
3279 }
3280 }),
3281 )
3282 .await;
3283 let (project_a, _) = client_a.build_local_project("/dir", cx_a).await;
3284 executor.run_until_parked();
3285 let project_id = active_call_a
3286 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
3287 .await
3288 .unwrap();
3289 executor.run_until_parked();
3290
3291 // As client B, join that project and observe the local settings.
3292 let project_b = client_b.build_remote_project(project_id, cx_b).await;
3293
3294 let worktree_b = project_b.read_with(cx_b, |project, _| project.worktrees().next().unwrap());
3295 executor.run_until_parked();
3296 cx_b.read(|cx| {
3297 let store = cx.global::<SettingsStore>();
3298 assert_eq!(
3299 store
3300 .local_settings(worktree_b.read(cx).id().to_usize())
3301 .collect::<Vec<_>>(),
3302 &[
3303 (Path::new("").into(), r#"{"tab_size":2}"#.to_string()),
3304 (Path::new("a").into(), r#"{"tab_size":8}"#.to_string()),
3305 ]
3306 )
3307 });
3308
3309 // As client A, update a settings file. As Client B, see the changed settings.
3310 client_a
3311 .fs()
3312 .insert_file("/dir/.zed/settings.json", r#"{}"#.into())
3313 .await;
3314 executor.run_until_parked();
3315 cx_b.read(|cx| {
3316 let store = cx.global::<SettingsStore>();
3317 assert_eq!(
3318 store
3319 .local_settings(worktree_b.read(cx).id().to_usize())
3320 .collect::<Vec<_>>(),
3321 &[
3322 (Path::new("").into(), r#"{}"#.to_string()),
3323 (Path::new("a").into(), r#"{"tab_size":8}"#.to_string()),
3324 ]
3325 )
3326 });
3327
3328 // As client A, create and remove some settings files. As client B, see the changed settings.
3329 client_a
3330 .fs()
3331 .remove_file("/dir/.zed/settings.json".as_ref(), Default::default())
3332 .await
3333 .unwrap();
3334 client_a
3335 .fs()
3336 .create_dir("/dir/b/.zed".as_ref())
3337 .await
3338 .unwrap();
3339 client_a
3340 .fs()
3341 .insert_file("/dir/b/.zed/settings.json", r#"{"tab_size": 4}"#.into())
3342 .await;
3343 executor.run_until_parked();
3344 cx_b.read(|cx| {
3345 let store = cx.global::<SettingsStore>();
3346 assert_eq!(
3347 store
3348 .local_settings(worktree_b.read(cx).id().to_usize())
3349 .collect::<Vec<_>>(),
3350 &[
3351 (Path::new("a").into(), r#"{"tab_size":8}"#.to_string()),
3352 (Path::new("b").into(), r#"{"tab_size":4}"#.to_string()),
3353 ]
3354 )
3355 });
3356
3357 // As client B, disconnect.
3358 server.forbid_connections();
3359 server.disconnect_client(client_b.peer_id().unwrap());
3360
3361 // As client A, change and remove settings files while client B is disconnected.
3362 client_a
3363 .fs()
3364 .insert_file("/dir/a/.zed/settings.json", r#"{"hard_tabs":true}"#.into())
3365 .await;
3366 client_a
3367 .fs()
3368 .remove_file("/dir/b/.zed/settings.json".as_ref(), Default::default())
3369 .await
3370 .unwrap();
3371 executor.run_until_parked();
3372
3373 // As client B, reconnect and see the changed settings.
3374 server.allow_connections();
3375 executor.advance_clock(RECEIVE_TIMEOUT);
3376 cx_b.read(|cx| {
3377 let store = cx.global::<SettingsStore>();
3378 assert_eq!(
3379 store
3380 .local_settings(worktree_b.read(cx).id().to_usize())
3381 .collect::<Vec<_>>(),
3382 &[(Path::new("a").into(), r#"{"hard_tabs":true}"#.to_string()),]
3383 )
3384 });
3385}
3386
3387#[gpui::test(iterations = 10)]
3388async fn test_buffer_conflict_after_save(
3389 executor: BackgroundExecutor,
3390 cx_a: &mut TestAppContext,
3391 cx_b: &mut TestAppContext,
3392) {
3393 let mut server = TestServer::start(executor.clone()).await;
3394 let client_a = server.create_client(cx_a, "user_a").await;
3395 let client_b = server.create_client(cx_b, "user_b").await;
3396 server
3397 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
3398 .await;
3399 let active_call_a = cx_a.read(ActiveCall::global);
3400
3401 client_a
3402 .fs()
3403 .insert_tree(
3404 "/dir",
3405 json!({
3406 "a.txt": "a-contents",
3407 }),
3408 )
3409 .await;
3410 let (project_a, worktree_id) = client_a.build_local_project("/dir", cx_a).await;
3411 let project_id = active_call_a
3412 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
3413 .await
3414 .unwrap();
3415 let project_b = client_b.build_remote_project(project_id, cx_b).await;
3416
3417 // Open a buffer as client B
3418 let buffer_b = project_b
3419 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
3420 .await
3421 .unwrap();
3422
3423 buffer_b.update(cx_b, |buf, cx| buf.edit([(0..0, "world ")], None, cx));
3424
3425 buffer_b.read_with(cx_b, |buf, _| {
3426 assert!(buf.is_dirty());
3427 assert!(!buf.has_conflict());
3428 });
3429
3430 project_b
3431 .update(cx_b, |project, cx| {
3432 project.save_buffer(buffer_b.clone(), cx)
3433 })
3434 .await
3435 .unwrap();
3436
3437 buffer_b.read_with(cx_b, |buffer_b, _| assert!(!buffer_b.is_dirty()));
3438
3439 buffer_b.read_with(cx_b, |buf, _| {
3440 assert!(!buf.has_conflict());
3441 });
3442
3443 buffer_b.update(cx_b, |buf, cx| buf.edit([(0..0, "hello ")], None, cx));
3444
3445 buffer_b.read_with(cx_b, |buf, _| {
3446 assert!(buf.is_dirty());
3447 assert!(!buf.has_conflict());
3448 });
3449}
3450
3451#[gpui::test(iterations = 10)]
3452async fn test_buffer_reloading(
3453 executor: BackgroundExecutor,
3454 cx_a: &mut TestAppContext,
3455 cx_b: &mut TestAppContext,
3456) {
3457 let mut server = TestServer::start(executor.clone()).await;
3458 let client_a = server.create_client(cx_a, "user_a").await;
3459 let client_b = server.create_client(cx_b, "user_b").await;
3460 server
3461 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
3462 .await;
3463 let active_call_a = cx_a.read(ActiveCall::global);
3464
3465 client_a
3466 .fs()
3467 .insert_tree(
3468 "/dir",
3469 json!({
3470 "a.txt": "a\nb\nc",
3471 }),
3472 )
3473 .await;
3474 let (project_a, worktree_id) = client_a.build_local_project("/dir", cx_a).await;
3475 let project_id = active_call_a
3476 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
3477 .await
3478 .unwrap();
3479 let project_b = client_b.build_remote_project(project_id, cx_b).await;
3480
3481 // Open a buffer as client B
3482 let buffer_b = project_b
3483 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
3484 .await
3485 .unwrap();
3486
3487 buffer_b.read_with(cx_b, |buf, _| {
3488 assert!(!buf.is_dirty());
3489 assert!(!buf.has_conflict());
3490 assert_eq!(buf.line_ending(), LineEnding::Unix);
3491 });
3492
3493 let new_contents = Rope::from("d\ne\nf");
3494 client_a
3495 .fs()
3496 .save("/dir/a.txt".as_ref(), &new_contents, LineEnding::Windows)
3497 .await
3498 .unwrap();
3499
3500 executor.run_until_parked();
3501
3502 buffer_b.read_with(cx_b, |buf, _| {
3503 assert_eq!(buf.text(), new_contents.to_string());
3504 assert!(!buf.is_dirty());
3505 assert!(!buf.has_conflict());
3506 assert_eq!(buf.line_ending(), LineEnding::Windows);
3507 });
3508}
3509
3510#[gpui::test(iterations = 10)]
3511async fn test_editing_while_guest_opens_buffer(
3512 executor: BackgroundExecutor,
3513 cx_a: &mut TestAppContext,
3514 cx_b: &mut TestAppContext,
3515) {
3516 let mut server = TestServer::start(executor.clone()).await;
3517 let client_a = server.create_client(cx_a, "user_a").await;
3518 let client_b = server.create_client(cx_b, "user_b").await;
3519 server
3520 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
3521 .await;
3522 let active_call_a = cx_a.read(ActiveCall::global);
3523
3524 client_a
3525 .fs()
3526 .insert_tree("/dir", json!({ "a.txt": "a-contents" }))
3527 .await;
3528 let (project_a, worktree_id) = client_a.build_local_project("/dir", cx_a).await;
3529 let project_id = active_call_a
3530 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
3531 .await
3532 .unwrap();
3533 let project_b = client_b.build_remote_project(project_id, cx_b).await;
3534
3535 // Open a buffer as client A
3536 let buffer_a = project_a
3537 .update(cx_a, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
3538 .await
3539 .unwrap();
3540
3541 // Start opening the same buffer as client B
3542 let open_buffer = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx));
3543 let buffer_b = cx_b.executor().spawn(open_buffer);
3544
3545 // Edit the buffer as client A while client B is still opening it.
3546 cx_b.executor().simulate_random_delay().await;
3547 buffer_a.update(cx_a, |buf, cx| buf.edit([(0..0, "X")], None, cx));
3548 cx_b.executor().simulate_random_delay().await;
3549 buffer_a.update(cx_a, |buf, cx| buf.edit([(1..1, "Y")], None, cx));
3550
3551 let text = buffer_a.read_with(cx_a, |buf, _| buf.text());
3552 let buffer_b = buffer_b.await.unwrap();
3553 executor.run_until_parked();
3554
3555 buffer_b.read_with(cx_b, |buf, _| assert_eq!(buf.text(), text));
3556}
3557
3558#[gpui::test(iterations = 10)]
3559async fn test_leaving_worktree_while_opening_buffer(
3560 executor: BackgroundExecutor,
3561 cx_a: &mut TestAppContext,
3562 cx_b: &mut TestAppContext,
3563) {
3564 let mut server = TestServer::start(executor.clone()).await;
3565 let client_a = server.create_client(cx_a, "user_a").await;
3566 let client_b = server.create_client(cx_b, "user_b").await;
3567 server
3568 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
3569 .await;
3570 let active_call_a = cx_a.read(ActiveCall::global);
3571
3572 client_a
3573 .fs()
3574 .insert_tree("/dir", json!({ "a.txt": "a-contents" }))
3575 .await;
3576 let (project_a, worktree_id) = client_a.build_local_project("/dir", cx_a).await;
3577 let project_id = active_call_a
3578 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
3579 .await
3580 .unwrap();
3581 let project_b = client_b.build_remote_project(project_id, cx_b).await;
3582
3583 // See that a guest has joined as client A.
3584 executor.run_until_parked();
3585
3586 project_a.read_with(cx_a, |p, _| assert_eq!(p.collaborators().len(), 1));
3587
3588 // Begin opening a buffer as client B, but leave the project before the open completes.
3589 let open_buffer = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx));
3590 let buffer_b = cx_b.executor().spawn(open_buffer);
3591 cx_b.update(|_| drop(project_b));
3592 drop(buffer_b);
3593
3594 // See that the guest has left.
3595 executor.run_until_parked();
3596
3597 project_a.read_with(cx_a, |p, _| assert!(p.collaborators().is_empty()));
3598}
3599
3600#[gpui::test(iterations = 10)]
3601async fn test_canceling_buffer_opening(
3602 executor: BackgroundExecutor,
3603 cx_a: &mut TestAppContext,
3604 cx_b: &mut TestAppContext,
3605) {
3606 let mut server = TestServer::start(executor.clone()).await;
3607 let client_a = server.create_client(cx_a, "user_a").await;
3608 let client_b = server.create_client(cx_b, "user_b").await;
3609 server
3610 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
3611 .await;
3612 let active_call_a = cx_a.read(ActiveCall::global);
3613
3614 client_a
3615 .fs()
3616 .insert_tree(
3617 "/dir",
3618 json!({
3619 "a.txt": "abc",
3620 }),
3621 )
3622 .await;
3623 let (project_a, worktree_id) = client_a.build_local_project("/dir", cx_a).await;
3624 let project_id = active_call_a
3625 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
3626 .await
3627 .unwrap();
3628 let project_b = client_b.build_remote_project(project_id, cx_b).await;
3629
3630 let buffer_a = project_a
3631 .update(cx_a, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
3632 .await
3633 .unwrap();
3634
3635 // Open a buffer as client B but cancel after a random amount of time.
3636 let buffer_b = project_b.update(cx_b, |p, cx| {
3637 p.open_buffer_by_id(buffer_a.read_with(cx_a, |a, _| a.remote_id()), cx)
3638 });
3639 executor.simulate_random_delay().await;
3640 drop(buffer_b);
3641
3642 // Try opening the same buffer again as client B, and ensure we can
3643 // still do it despite the cancellation above.
3644 let buffer_b = project_b
3645 .update(cx_b, |p, cx| {
3646 p.open_buffer_by_id(buffer_a.read_with(cx_a, |a, _| a.remote_id()), cx)
3647 })
3648 .await
3649 .unwrap();
3650
3651 buffer_b.read_with(cx_b, |buf, _| assert_eq!(buf.text(), "abc"));
3652}
3653
3654#[gpui::test(iterations = 10)]
3655async fn test_leaving_project(
3656 executor: BackgroundExecutor,
3657 cx_a: &mut TestAppContext,
3658 cx_b: &mut TestAppContext,
3659 cx_c: &mut TestAppContext,
3660) {
3661 let mut server = TestServer::start(executor.clone()).await;
3662 let client_a = server.create_client(cx_a, "user_a").await;
3663 let client_b = server.create_client(cx_b, "user_b").await;
3664 let client_c = server.create_client(cx_c, "user_c").await;
3665 server
3666 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b), (&client_c, cx_c)])
3667 .await;
3668 let active_call_a = cx_a.read(ActiveCall::global);
3669
3670 client_a
3671 .fs()
3672 .insert_tree(
3673 "/a",
3674 json!({
3675 "a.txt": "a-contents",
3676 "b.txt": "b-contents",
3677 }),
3678 )
3679 .await;
3680 let (project_a, _) = client_a.build_local_project("/a", cx_a).await;
3681 let project_id = active_call_a
3682 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
3683 .await
3684 .unwrap();
3685 let project_b1 = client_b.build_remote_project(project_id, cx_b).await;
3686 let project_c = client_c.build_remote_project(project_id, cx_c).await;
3687
3688 // Client A sees that a guest has joined.
3689 executor.run_until_parked();
3690
3691 project_a.read_with(cx_a, |project, _| {
3692 assert_eq!(project.collaborators().len(), 2);
3693 });
3694
3695 project_b1.read_with(cx_b, |project, _| {
3696 assert_eq!(project.collaborators().len(), 2);
3697 });
3698
3699 project_c.read_with(cx_c, |project, _| {
3700 assert_eq!(project.collaborators().len(), 2);
3701 });
3702
3703 // Client B opens a buffer.
3704 let buffer_b1 = project_b1
3705 .update(cx_b, |project, cx| {
3706 let worktree_id = project.worktrees().next().unwrap().read(cx).id();
3707 project.open_buffer((worktree_id, "a.txt"), cx)
3708 })
3709 .await
3710 .unwrap();
3711
3712 buffer_b1.read_with(cx_b, |buffer, _| assert_eq!(buffer.text(), "a-contents"));
3713
3714 // Drop client B's project and ensure client A and client C observe client B leaving.
3715 cx_b.update(|_| drop(project_b1));
3716 executor.run_until_parked();
3717
3718 project_a.read_with(cx_a, |project, _| {
3719 assert_eq!(project.collaborators().len(), 1);
3720 });
3721
3722 project_c.read_with(cx_c, |project, _| {
3723 assert_eq!(project.collaborators().len(), 1);
3724 });
3725
3726 // Client B re-joins the project and can open buffers as before.
3727 let project_b2 = client_b.build_remote_project(project_id, cx_b).await;
3728 executor.run_until_parked();
3729
3730 project_a.read_with(cx_a, |project, _| {
3731 assert_eq!(project.collaborators().len(), 2);
3732 });
3733
3734 project_b2.read_with(cx_b, |project, _| {
3735 assert_eq!(project.collaborators().len(), 2);
3736 });
3737
3738 project_c.read_with(cx_c, |project, _| {
3739 assert_eq!(project.collaborators().len(), 2);
3740 });
3741
3742 let buffer_b2 = project_b2
3743 .update(cx_b, |project, cx| {
3744 let worktree_id = project.worktrees().next().unwrap().read(cx).id();
3745 project.open_buffer((worktree_id, "a.txt"), cx)
3746 })
3747 .await
3748 .unwrap();
3749
3750 buffer_b2.read_with(cx_b, |buffer, _| assert_eq!(buffer.text(), "a-contents"));
3751
3752 project_a.read_with(cx_a, |project, _| {
3753 assert_eq!(project.collaborators().len(), 2);
3754 });
3755
3756 // Drop client B's connection and ensure client A and client C observe client B leaving.
3757 client_b.disconnect(&cx_b.to_async());
3758 executor.advance_clock(RECONNECT_TIMEOUT);
3759
3760 project_a.read_with(cx_a, |project, _| {
3761 assert_eq!(project.collaborators().len(), 1);
3762 });
3763
3764 project_b2.read_with(cx_b, |project, _| {
3765 assert!(project.is_disconnected());
3766 });
3767
3768 project_c.read_with(cx_c, |project, _| {
3769 assert_eq!(project.collaborators().len(), 1);
3770 });
3771
3772 // Client B can't join the project, unless they re-join the room.
3773 cx_b.spawn(|cx| {
3774 Project::in_room(
3775 project_id,
3776 client_b.app_state.client.clone(),
3777 client_b.user_store().clone(),
3778 client_b.language_registry().clone(),
3779 FakeFs::new(cx.background_executor().clone()),
3780 cx,
3781 )
3782 })
3783 .await
3784 .unwrap_err();
3785
3786 // Simulate connection loss for client C and ensure client A observes client C leaving the project.
3787 client_c.wait_for_current_user(cx_c).await;
3788 server.forbid_connections();
3789 server.disconnect_client(client_c.peer_id().unwrap());
3790 executor.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
3791 executor.run_until_parked();
3792
3793 project_a.read_with(cx_a, |project, _| {
3794 assert_eq!(project.collaborators().len(), 0);
3795 });
3796
3797 project_b2.read_with(cx_b, |project, _| {
3798 assert!(project.is_disconnected());
3799 });
3800
3801 project_c.read_with(cx_c, |project, _| {
3802 assert!(project.is_disconnected());
3803 });
3804}
3805
3806#[gpui::test(iterations = 10)]
3807async fn test_collaborating_with_diagnostics(
3808 executor: BackgroundExecutor,
3809 cx_a: &mut TestAppContext,
3810 cx_b: &mut TestAppContext,
3811 cx_c: &mut TestAppContext,
3812) {
3813 let mut server = TestServer::start(executor.clone()).await;
3814 let client_a = server.create_client(cx_a, "user_a").await;
3815 let client_b = server.create_client(cx_b, "user_b").await;
3816 let client_c = server.create_client(cx_c, "user_c").await;
3817 server
3818 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b), (&client_c, cx_c)])
3819 .await;
3820 let active_call_a = cx_a.read(ActiveCall::global);
3821
3822 client_a.language_registry().add(Arc::new(Language::new(
3823 LanguageConfig {
3824 name: "Rust".into(),
3825 matcher: LanguageMatcher {
3826 path_suffixes: vec!["rs".to_string()],
3827 ..Default::default()
3828 },
3829 ..Default::default()
3830 },
3831 Some(tree_sitter_rust::language()),
3832 )));
3833 let mut fake_language_servers = client_a
3834 .language_registry()
3835 .register_fake_lsp_adapter("Rust", Default::default());
3836
3837 // Share a project as client A
3838 client_a
3839 .fs()
3840 .insert_tree(
3841 "/a",
3842 json!({
3843 "a.rs": "let one = two",
3844 "other.rs": "",
3845 }),
3846 )
3847 .await;
3848 let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
3849
3850 // Cause the language server to start.
3851 let _buffer = project_a
3852 .update(cx_a, |project, cx| {
3853 project.open_buffer(
3854 ProjectPath {
3855 worktree_id,
3856 path: Path::new("other.rs").into(),
3857 },
3858 cx,
3859 )
3860 })
3861 .await
3862 .unwrap();
3863
3864 // Simulate a language server reporting errors for a file.
3865 let mut fake_language_server = fake_language_servers.next().await.unwrap();
3866 fake_language_server
3867 .receive_notification::<lsp::notification::DidOpenTextDocument>()
3868 .await;
3869 fake_language_server.notify::<lsp::notification::PublishDiagnostics>(
3870 lsp::PublishDiagnosticsParams {
3871 uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
3872 version: None,
3873 diagnostics: vec![lsp::Diagnostic {
3874 severity: Some(lsp::DiagnosticSeverity::WARNING),
3875 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
3876 message: "message 0".to_string(),
3877 ..Default::default()
3878 }],
3879 },
3880 );
3881
3882 // Client A shares the project and, simultaneously, the language server
3883 // publishes a diagnostic. This is done to ensure that the server always
3884 // observes the latest diagnostics for a worktree.
3885 let project_id = active_call_a
3886 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
3887 .await
3888 .unwrap();
3889 fake_language_server.notify::<lsp::notification::PublishDiagnostics>(
3890 lsp::PublishDiagnosticsParams {
3891 uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
3892 version: None,
3893 diagnostics: vec![lsp::Diagnostic {
3894 severity: Some(lsp::DiagnosticSeverity::ERROR),
3895 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
3896 message: "message 1".to_string(),
3897 ..Default::default()
3898 }],
3899 },
3900 );
3901
3902 // Join the worktree as client B.
3903 let project_b = client_b.build_remote_project(project_id, cx_b).await;
3904
3905 // Wait for server to see the diagnostics update.
3906 executor.run_until_parked();
3907
3908 // Ensure client B observes the new diagnostics.
3909
3910 project_b.read_with(cx_b, |project, cx| {
3911 assert_eq!(
3912 project.diagnostic_summaries(false, cx).collect::<Vec<_>>(),
3913 &[(
3914 ProjectPath {
3915 worktree_id,
3916 path: Arc::from(Path::new("a.rs")),
3917 },
3918 LanguageServerId(0),
3919 DiagnosticSummary {
3920 error_count: 1,
3921 warning_count: 0,
3922 },
3923 )]
3924 )
3925 });
3926
3927 // Join project as client C and observe the diagnostics.
3928 let project_c = client_c.build_remote_project(project_id, cx_c).await;
3929 executor.run_until_parked();
3930 let project_c_diagnostic_summaries =
3931 Rc::new(RefCell::new(project_c.read_with(cx_c, |project, cx| {
3932 project.diagnostic_summaries(false, cx).collect::<Vec<_>>()
3933 })));
3934 project_c.update(cx_c, |_, cx| {
3935 let summaries = project_c_diagnostic_summaries.clone();
3936 cx.subscribe(&project_c, {
3937 move |p, _, event, cx| {
3938 if let project::Event::DiskBasedDiagnosticsFinished { .. } = event {
3939 *summaries.borrow_mut() = p.diagnostic_summaries(false, cx).collect();
3940 }
3941 }
3942 })
3943 .detach();
3944 });
3945
3946 executor.run_until_parked();
3947 assert_eq!(
3948 project_c_diagnostic_summaries.borrow().as_slice(),
3949 &[(
3950 ProjectPath {
3951 worktree_id,
3952 path: Arc::from(Path::new("a.rs")),
3953 },
3954 LanguageServerId(0),
3955 DiagnosticSummary {
3956 error_count: 1,
3957 warning_count: 0,
3958 },
3959 )]
3960 );
3961
3962 // Simulate a language server reporting more errors for a file.
3963 fake_language_server.notify::<lsp::notification::PublishDiagnostics>(
3964 lsp::PublishDiagnosticsParams {
3965 uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
3966 version: None,
3967 diagnostics: vec![
3968 lsp::Diagnostic {
3969 severity: Some(lsp::DiagnosticSeverity::ERROR),
3970 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
3971 message: "message 1".to_string(),
3972 ..Default::default()
3973 },
3974 lsp::Diagnostic {
3975 severity: Some(lsp::DiagnosticSeverity::WARNING),
3976 range: lsp::Range::new(lsp::Position::new(0, 10), lsp::Position::new(0, 13)),
3977 message: "message 2".to_string(),
3978 ..Default::default()
3979 },
3980 ],
3981 },
3982 );
3983
3984 // Clients B and C get the updated summaries
3985 executor.run_until_parked();
3986
3987 project_b.read_with(cx_b, |project, cx| {
3988 assert_eq!(
3989 project.diagnostic_summaries(false, cx).collect::<Vec<_>>(),
3990 [(
3991 ProjectPath {
3992 worktree_id,
3993 path: Arc::from(Path::new("a.rs")),
3994 },
3995 LanguageServerId(0),
3996 DiagnosticSummary {
3997 error_count: 1,
3998 warning_count: 1,
3999 },
4000 )]
4001 );
4002 });
4003
4004 project_c.read_with(cx_c, |project, cx| {
4005 assert_eq!(
4006 project.diagnostic_summaries(false, cx).collect::<Vec<_>>(),
4007 [(
4008 ProjectPath {
4009 worktree_id,
4010 path: Arc::from(Path::new("a.rs")),
4011 },
4012 LanguageServerId(0),
4013 DiagnosticSummary {
4014 error_count: 1,
4015 warning_count: 1,
4016 },
4017 )]
4018 );
4019 });
4020
4021 // Open the file with the errors on client B. They should be present.
4022 let open_buffer = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx));
4023 let buffer_b = cx_b.executor().spawn(open_buffer).await.unwrap();
4024
4025 buffer_b.read_with(cx_b, |buffer, _| {
4026 assert_eq!(
4027 buffer
4028 .snapshot()
4029 .diagnostics_in_range::<_, Point>(0..buffer.len(), false)
4030 .collect::<Vec<_>>(),
4031 &[
4032 DiagnosticEntry {
4033 range: Point::new(0, 4)..Point::new(0, 7),
4034 diagnostic: Diagnostic {
4035 group_id: 2,
4036 message: "message 1".to_string(),
4037 severity: lsp::DiagnosticSeverity::ERROR,
4038 is_primary: true,
4039 ..Default::default()
4040 }
4041 },
4042 DiagnosticEntry {
4043 range: Point::new(0, 10)..Point::new(0, 13),
4044 diagnostic: Diagnostic {
4045 group_id: 3,
4046 severity: lsp::DiagnosticSeverity::WARNING,
4047 message: "message 2".to_string(),
4048 is_primary: true,
4049 ..Default::default()
4050 }
4051 }
4052 ]
4053 );
4054 });
4055
4056 // Simulate a language server reporting no errors for a file.
4057 fake_language_server.notify::<lsp::notification::PublishDiagnostics>(
4058 lsp::PublishDiagnosticsParams {
4059 uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
4060 version: None,
4061 diagnostics: vec![],
4062 },
4063 );
4064 executor.run_until_parked();
4065
4066 project_a.read_with(cx_a, |project, cx| {
4067 assert_eq!(
4068 project.diagnostic_summaries(false, cx).collect::<Vec<_>>(),
4069 []
4070 )
4071 });
4072
4073 project_b.read_with(cx_b, |project, cx| {
4074 assert_eq!(
4075 project.diagnostic_summaries(false, cx).collect::<Vec<_>>(),
4076 []
4077 )
4078 });
4079
4080 project_c.read_with(cx_c, |project, cx| {
4081 assert_eq!(
4082 project.diagnostic_summaries(false, cx).collect::<Vec<_>>(),
4083 []
4084 )
4085 });
4086}
4087
4088#[gpui::test(iterations = 10)]
4089async fn test_collaborating_with_lsp_progress_updates_and_diagnostics_ordering(
4090 executor: BackgroundExecutor,
4091 cx_a: &mut TestAppContext,
4092 cx_b: &mut TestAppContext,
4093) {
4094 let mut server = TestServer::start(executor.clone()).await;
4095 let client_a = server.create_client(cx_a, "user_a").await;
4096 let client_b = server.create_client(cx_b, "user_b").await;
4097 server
4098 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
4099 .await;
4100
4101 client_a.language_registry().add(rust_lang());
4102 let mut fake_language_servers = client_a.language_registry().register_fake_lsp_adapter(
4103 "Rust",
4104 FakeLspAdapter {
4105 disk_based_diagnostics_progress_token: Some("the-disk-based-token".into()),
4106 disk_based_diagnostics_sources: vec!["the-disk-based-diagnostics-source".into()],
4107 ..Default::default()
4108 },
4109 );
4110
4111 let file_names = &["one.rs", "two.rs", "three.rs", "four.rs", "five.rs"];
4112 client_a
4113 .fs()
4114 .insert_tree(
4115 "/test",
4116 json!({
4117 "one.rs": "const ONE: usize = 1;",
4118 "two.rs": "const TWO: usize = 2;",
4119 "three.rs": "const THREE: usize = 3;",
4120 "four.rs": "const FOUR: usize = 3;",
4121 "five.rs": "const FIVE: usize = 3;",
4122 }),
4123 )
4124 .await;
4125
4126 let (project_a, worktree_id) = client_a.build_local_project("/test", cx_a).await;
4127
4128 // Share a project as client A
4129 let active_call_a = cx_a.read(ActiveCall::global);
4130 let project_id = active_call_a
4131 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
4132 .await
4133 .unwrap();
4134
4135 // Join the project as client B and open all three files.
4136 let project_b = client_b.build_remote_project(project_id, cx_b).await;
4137 let guest_buffers = futures::future::try_join_all(file_names.iter().map(|file_name| {
4138 project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, file_name), cx))
4139 }))
4140 .await
4141 .unwrap();
4142
4143 // Simulate a language server reporting errors for a file.
4144 let fake_language_server = fake_language_servers.next().await.unwrap();
4145 fake_language_server
4146 .request::<lsp::request::WorkDoneProgressCreate>(lsp::WorkDoneProgressCreateParams {
4147 token: lsp::NumberOrString::String("the-disk-based-token".to_string()),
4148 })
4149 .await
4150 .unwrap();
4151 fake_language_server.notify::<lsp::notification::Progress>(lsp::ProgressParams {
4152 token: lsp::NumberOrString::String("the-disk-based-token".to_string()),
4153 value: lsp::ProgressParamsValue::WorkDone(lsp::WorkDoneProgress::Begin(
4154 lsp::WorkDoneProgressBegin {
4155 title: "Progress Began".into(),
4156 ..Default::default()
4157 },
4158 )),
4159 });
4160 for file_name in file_names {
4161 fake_language_server.notify::<lsp::notification::PublishDiagnostics>(
4162 lsp::PublishDiagnosticsParams {
4163 uri: lsp::Url::from_file_path(Path::new("/test").join(file_name)).unwrap(),
4164 version: None,
4165 diagnostics: vec![lsp::Diagnostic {
4166 severity: Some(lsp::DiagnosticSeverity::WARNING),
4167 source: Some("the-disk-based-diagnostics-source".into()),
4168 range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
4169 message: "message one".to_string(),
4170 ..Default::default()
4171 }],
4172 },
4173 );
4174 }
4175 fake_language_server.notify::<lsp::notification::Progress>(lsp::ProgressParams {
4176 token: lsp::NumberOrString::String("the-disk-based-token".to_string()),
4177 value: lsp::ProgressParamsValue::WorkDone(lsp::WorkDoneProgress::End(
4178 lsp::WorkDoneProgressEnd { message: None },
4179 )),
4180 });
4181
4182 // When the "disk base diagnostics finished" message is received, the buffers'
4183 // diagnostics are expected to be present.
4184 let disk_based_diagnostics_finished = Arc::new(AtomicBool::new(false));
4185 project_b.update(cx_b, {
4186 let project_b = project_b.clone();
4187 let disk_based_diagnostics_finished = disk_based_diagnostics_finished.clone();
4188 move |_, cx| {
4189 cx.subscribe(&project_b, move |_, _, event, cx| {
4190 if let project::Event::DiskBasedDiagnosticsFinished { .. } = event {
4191 disk_based_diagnostics_finished.store(true, SeqCst);
4192 for buffer in &guest_buffers {
4193 assert_eq!(
4194 buffer
4195 .read(cx)
4196 .snapshot()
4197 .diagnostics_in_range::<_, usize>(0..5, false)
4198 .count(),
4199 1,
4200 "expected a diagnostic for buffer {:?}",
4201 buffer.read(cx).file().unwrap().path(),
4202 );
4203 }
4204 }
4205 })
4206 .detach();
4207 }
4208 });
4209
4210 executor.run_until_parked();
4211 assert!(disk_based_diagnostics_finished.load(SeqCst));
4212}
4213
4214#[gpui::test(iterations = 10)]
4215async fn test_reloading_buffer_manually(
4216 executor: BackgroundExecutor,
4217 cx_a: &mut TestAppContext,
4218 cx_b: &mut TestAppContext,
4219) {
4220 let mut server = TestServer::start(executor.clone()).await;
4221 let client_a = server.create_client(cx_a, "user_a").await;
4222 let client_b = server.create_client(cx_b, "user_b").await;
4223 server
4224 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
4225 .await;
4226 let active_call_a = cx_a.read(ActiveCall::global);
4227
4228 client_a
4229 .fs()
4230 .insert_tree("/a", json!({ "a.rs": "let one = 1;" }))
4231 .await;
4232 let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
4233 let buffer_a = project_a
4234 .update(cx_a, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
4235 .await
4236 .unwrap();
4237 let project_id = active_call_a
4238 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
4239 .await
4240 .unwrap();
4241
4242 let project_b = client_b.build_remote_project(project_id, cx_b).await;
4243
4244 let open_buffer = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx));
4245 let buffer_b = cx_b.executor().spawn(open_buffer).await.unwrap();
4246 buffer_b.update(cx_b, |buffer, cx| {
4247 buffer.edit([(4..7, "six")], None, cx);
4248 buffer.edit([(10..11, "6")], None, cx);
4249 assert_eq!(buffer.text(), "let six = 6;");
4250 assert!(buffer.is_dirty());
4251 assert!(!buffer.has_conflict());
4252 });
4253 executor.run_until_parked();
4254
4255 buffer_a.read_with(cx_a, |buffer, _| assert_eq!(buffer.text(), "let six = 6;"));
4256
4257 client_a
4258 .fs()
4259 .save(
4260 "/a/a.rs".as_ref(),
4261 &Rope::from("let seven = 7;"),
4262 LineEnding::Unix,
4263 )
4264 .await
4265 .unwrap();
4266 executor.run_until_parked();
4267
4268 buffer_a.read_with(cx_a, |buffer, _| assert!(buffer.has_conflict()));
4269
4270 buffer_b.read_with(cx_b, |buffer, _| assert!(buffer.has_conflict()));
4271
4272 project_b
4273 .update(cx_b, |project, cx| {
4274 project.reload_buffers(HashSet::from_iter([buffer_b.clone()]), true, cx)
4275 })
4276 .await
4277 .unwrap();
4278
4279 buffer_a.read_with(cx_a, |buffer, _| {
4280 assert_eq!(buffer.text(), "let seven = 7;");
4281 assert!(!buffer.is_dirty());
4282 assert!(!buffer.has_conflict());
4283 });
4284
4285 buffer_b.read_with(cx_b, |buffer, _| {
4286 assert_eq!(buffer.text(), "let seven = 7;");
4287 assert!(!buffer.is_dirty());
4288 assert!(!buffer.has_conflict());
4289 });
4290
4291 buffer_a.update(cx_a, |buffer, cx| {
4292 // Undoing on the host is a no-op when the reload was initiated by the guest.
4293 buffer.undo(cx);
4294 assert_eq!(buffer.text(), "let seven = 7;");
4295 assert!(!buffer.is_dirty());
4296 assert!(!buffer.has_conflict());
4297 });
4298 buffer_b.update(cx_b, |buffer, cx| {
4299 // Undoing on the guest rolls back the buffer to before it was reloaded but the conflict gets cleared.
4300 buffer.undo(cx);
4301 assert_eq!(buffer.text(), "let six = 6;");
4302 assert!(buffer.is_dirty());
4303 assert!(!buffer.has_conflict());
4304 });
4305}
4306
4307#[gpui::test(iterations = 10)]
4308async fn test_formatting_buffer(
4309 executor: BackgroundExecutor,
4310 cx_a: &mut TestAppContext,
4311 cx_b: &mut TestAppContext,
4312) {
4313 executor.allow_parking();
4314 let mut server = TestServer::start(executor.clone()).await;
4315 let client_a = server.create_client(cx_a, "user_a").await;
4316 let client_b = server.create_client(cx_b, "user_b").await;
4317 server
4318 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
4319 .await;
4320 let active_call_a = cx_a.read(ActiveCall::global);
4321
4322 client_a.language_registry().add(rust_lang());
4323 let mut fake_language_servers = client_a
4324 .language_registry()
4325 .register_fake_lsp_adapter("Rust", FakeLspAdapter::default());
4326
4327 // Here we insert a fake tree with a directory that exists on disk. This is needed
4328 // because later we'll invoke a command, which requires passing a working directory
4329 // that points to a valid location on disk.
4330 let directory = env::current_dir().unwrap();
4331 client_a
4332 .fs()
4333 .insert_tree(&directory, json!({ "a.rs": "let one = \"two\"" }))
4334 .await;
4335 let (project_a, worktree_id) = client_a.build_local_project(&directory, cx_a).await;
4336 let project_id = active_call_a
4337 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
4338 .await
4339 .unwrap();
4340 let project_b = client_b.build_remote_project(project_id, cx_b).await;
4341
4342 let open_buffer = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx));
4343 let buffer_b = cx_b.executor().spawn(open_buffer).await.unwrap();
4344
4345 let fake_language_server = fake_language_servers.next().await.unwrap();
4346 fake_language_server.handle_request::<lsp::request::Formatting, _, _>(|_, _| async move {
4347 Ok(Some(vec![
4348 lsp::TextEdit {
4349 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 4)),
4350 new_text: "h".to_string(),
4351 },
4352 lsp::TextEdit {
4353 range: lsp::Range::new(lsp::Position::new(0, 7), lsp::Position::new(0, 7)),
4354 new_text: "y".to_string(),
4355 },
4356 ]))
4357 });
4358
4359 project_b
4360 .update(cx_b, |project, cx| {
4361 project.format(
4362 HashSet::from_iter([buffer_b.clone()]),
4363 true,
4364 FormatTrigger::Save,
4365 cx,
4366 )
4367 })
4368 .await
4369 .unwrap();
4370
4371 // The edits from the LSP are applied, and a final newline is added.
4372 assert_eq!(
4373 buffer_b.read_with(cx_b, |buffer, _| buffer.text()),
4374 "let honey = \"two\"\n"
4375 );
4376
4377 // Ensure buffer can be formatted using an external command. Notice how the
4378 // host's configuration is honored as opposed to using the guest's settings.
4379 cx_a.update(|cx| {
4380 cx.update_global(|store: &mut SettingsStore, cx| {
4381 store.update_user_settings::<AllLanguageSettings>(cx, |file| {
4382 file.defaults.formatter = Some(Formatter::External {
4383 command: "awk".into(),
4384 arguments: vec!["{sub(/two/,\"{buffer_path}\")}1".to_string()].into(),
4385 });
4386 });
4387 });
4388 });
4389 project_b
4390 .update(cx_b, |project, cx| {
4391 project.format(
4392 HashSet::from_iter([buffer_b.clone()]),
4393 true,
4394 FormatTrigger::Save,
4395 cx,
4396 )
4397 })
4398 .await
4399 .unwrap();
4400 assert_eq!(
4401 buffer_b.read_with(cx_b, |buffer, _| buffer.text()),
4402 format!("let honey = \"{}/a.rs\"\n", directory.to_str().unwrap())
4403 );
4404}
4405
4406#[gpui::test(iterations = 10)]
4407async fn test_prettier_formatting_buffer(
4408 executor: BackgroundExecutor,
4409 cx_a: &mut TestAppContext,
4410 cx_b: &mut TestAppContext,
4411) {
4412 let mut server = TestServer::start(executor.clone()).await;
4413 let client_a = server.create_client(cx_a, "user_a").await;
4414 let client_b = server.create_client(cx_b, "user_b").await;
4415 server
4416 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
4417 .await;
4418 let active_call_a = cx_a.read(ActiveCall::global);
4419
4420 let test_plugin = "test_plugin";
4421
4422 client_a.language_registry().add(Arc::new(Language::new(
4423 LanguageConfig {
4424 name: "Rust".into(),
4425 matcher: LanguageMatcher {
4426 path_suffixes: vec!["rs".to_string()],
4427 ..Default::default()
4428 },
4429 prettier_parser_name: Some("test_parser".to_string()),
4430 ..Default::default()
4431 },
4432 Some(tree_sitter_rust::language()),
4433 )));
4434 let mut fake_language_servers = client_a.language_registry().register_fake_lsp_adapter(
4435 "Rust",
4436 FakeLspAdapter {
4437 prettier_plugins: vec![test_plugin],
4438 ..Default::default()
4439 },
4440 );
4441
4442 // Here we insert a fake tree with a directory that exists on disk. This is needed
4443 // because later we'll invoke a command, which requires passing a working directory
4444 // that points to a valid location on disk.
4445 let directory = env::current_dir().unwrap();
4446 let buffer_text = "let one = \"two\"";
4447 client_a
4448 .fs()
4449 .insert_tree(&directory, json!({ "a.rs": buffer_text }))
4450 .await;
4451 let (project_a, worktree_id) = client_a.build_local_project(&directory, cx_a).await;
4452 let prettier_format_suffix = project::TEST_PRETTIER_FORMAT_SUFFIX;
4453 let open_buffer = project_a.update(cx_a, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx));
4454 let buffer_a = cx_a.executor().spawn(open_buffer).await.unwrap();
4455
4456 let project_id = active_call_a
4457 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
4458 .await
4459 .unwrap();
4460 let project_b = client_b.build_remote_project(project_id, cx_b).await;
4461 let open_buffer = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx));
4462 let buffer_b = cx_b.executor().spawn(open_buffer).await.unwrap();
4463
4464 cx_a.update(|cx| {
4465 cx.update_global(|store: &mut SettingsStore, cx| {
4466 store.update_user_settings::<AllLanguageSettings>(cx, |file| {
4467 file.defaults.formatter = Some(Formatter::Auto);
4468 });
4469 });
4470 });
4471 cx_b.update(|cx| {
4472 cx.update_global(|store: &mut SettingsStore, cx| {
4473 store.update_user_settings::<AllLanguageSettings>(cx, |file| {
4474 file.defaults.formatter = Some(Formatter::LanguageServer);
4475 });
4476 });
4477 });
4478 let fake_language_server = fake_language_servers.next().await.unwrap();
4479 fake_language_server.handle_request::<lsp::request::Formatting, _, _>(|_, _| async move {
4480 panic!(
4481 "Unexpected: prettier should be preferred since it's enabled and language supports it"
4482 )
4483 });
4484
4485 project_b
4486 .update(cx_b, |project, cx| {
4487 project.format(
4488 HashSet::from_iter([buffer_b.clone()]),
4489 true,
4490 FormatTrigger::Save,
4491 cx,
4492 )
4493 })
4494 .await
4495 .unwrap();
4496
4497 executor.run_until_parked();
4498 assert_eq!(
4499 buffer_b.read_with(cx_b, |buffer, _| buffer.text()),
4500 buffer_text.to_string() + "\n" + prettier_format_suffix,
4501 "Prettier formatting was not applied to client buffer after client's request"
4502 );
4503
4504 project_a
4505 .update(cx_a, |project, cx| {
4506 project.format(
4507 HashSet::from_iter([buffer_a.clone()]),
4508 true,
4509 FormatTrigger::Manual,
4510 cx,
4511 )
4512 })
4513 .await
4514 .unwrap();
4515
4516 executor.run_until_parked();
4517 assert_eq!(
4518 buffer_b.read_with(cx_b, |buffer, _| buffer.text()),
4519 buffer_text.to_string() + "\n" + prettier_format_suffix + "\n" + prettier_format_suffix,
4520 "Prettier formatting was not applied to client buffer after host's request"
4521 );
4522}
4523
4524#[gpui::test(iterations = 10)]
4525async fn test_definition(
4526 executor: BackgroundExecutor,
4527 cx_a: &mut TestAppContext,
4528 cx_b: &mut TestAppContext,
4529) {
4530 let mut server = TestServer::start(executor.clone()).await;
4531 let client_a = server.create_client(cx_a, "user_a").await;
4532 let client_b = server.create_client(cx_b, "user_b").await;
4533 server
4534 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
4535 .await;
4536 let active_call_a = cx_a.read(ActiveCall::global);
4537
4538 let mut fake_language_servers = client_a
4539 .language_registry()
4540 .register_fake_lsp_adapter("Rust", Default::default());
4541 client_a.language_registry().add(rust_lang());
4542
4543 client_a
4544 .fs()
4545 .insert_tree(
4546 "/root",
4547 json!({
4548 "dir-1": {
4549 "a.rs": "const ONE: usize = b::TWO + b::THREE;",
4550 },
4551 "dir-2": {
4552 "b.rs": "const TWO: c::T2 = 2;\nconst THREE: usize = 3;",
4553 "c.rs": "type T2 = usize;",
4554 }
4555 }),
4556 )
4557 .await;
4558 let (project_a, worktree_id) = client_a.build_local_project("/root/dir-1", cx_a).await;
4559 let project_id = active_call_a
4560 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
4561 .await
4562 .unwrap();
4563 let project_b = client_b.build_remote_project(project_id, cx_b).await;
4564
4565 // Open the file on client B.
4566 let open_buffer = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx));
4567 let buffer_b = cx_b.executor().spawn(open_buffer).await.unwrap();
4568
4569 // Request the definition of a symbol as the guest.
4570 let fake_language_server = fake_language_servers.next().await.unwrap();
4571 fake_language_server.handle_request::<lsp::request::GotoDefinition, _, _>(|_, _| async move {
4572 Ok(Some(lsp::GotoDefinitionResponse::Scalar(
4573 lsp::Location::new(
4574 lsp::Url::from_file_path("/root/dir-2/b.rs").unwrap(),
4575 lsp::Range::new(lsp::Position::new(0, 6), lsp::Position::new(0, 9)),
4576 ),
4577 )))
4578 });
4579
4580 let definitions_1 = project_b
4581 .update(cx_b, |p, cx| p.definition(&buffer_b, 23, cx))
4582 .await
4583 .unwrap();
4584 cx_b.read(|cx| {
4585 assert_eq!(definitions_1.len(), 1);
4586 assert_eq!(project_b.read(cx).worktrees().count(), 2);
4587 let target_buffer = definitions_1[0].target.buffer.read(cx);
4588 assert_eq!(
4589 target_buffer.text(),
4590 "const TWO: c::T2 = 2;\nconst THREE: usize = 3;"
4591 );
4592 assert_eq!(
4593 definitions_1[0].target.range.to_point(target_buffer),
4594 Point::new(0, 6)..Point::new(0, 9)
4595 );
4596 });
4597
4598 // Try getting more definitions for the same buffer, ensuring the buffer gets reused from
4599 // the previous call to `definition`.
4600 fake_language_server.handle_request::<lsp::request::GotoDefinition, _, _>(|_, _| async move {
4601 Ok(Some(lsp::GotoDefinitionResponse::Scalar(
4602 lsp::Location::new(
4603 lsp::Url::from_file_path("/root/dir-2/b.rs").unwrap(),
4604 lsp::Range::new(lsp::Position::new(1, 6), lsp::Position::new(1, 11)),
4605 ),
4606 )))
4607 });
4608
4609 let definitions_2 = project_b
4610 .update(cx_b, |p, cx| p.definition(&buffer_b, 33, cx))
4611 .await
4612 .unwrap();
4613 cx_b.read(|cx| {
4614 assert_eq!(definitions_2.len(), 1);
4615 assert_eq!(project_b.read(cx).worktrees().count(), 2);
4616 let target_buffer = definitions_2[0].target.buffer.read(cx);
4617 assert_eq!(
4618 target_buffer.text(),
4619 "const TWO: c::T2 = 2;\nconst THREE: usize = 3;"
4620 );
4621 assert_eq!(
4622 definitions_2[0].target.range.to_point(target_buffer),
4623 Point::new(1, 6)..Point::new(1, 11)
4624 );
4625 });
4626 assert_eq!(
4627 definitions_1[0].target.buffer,
4628 definitions_2[0].target.buffer
4629 );
4630
4631 fake_language_server.handle_request::<lsp::request::GotoTypeDefinition, _, _>(
4632 |req, _| async move {
4633 assert_eq!(
4634 req.text_document_position_params.position,
4635 lsp::Position::new(0, 7)
4636 );
4637 Ok(Some(lsp::GotoDefinitionResponse::Scalar(
4638 lsp::Location::new(
4639 lsp::Url::from_file_path("/root/dir-2/c.rs").unwrap(),
4640 lsp::Range::new(lsp::Position::new(0, 5), lsp::Position::new(0, 7)),
4641 ),
4642 )))
4643 },
4644 );
4645
4646 let type_definitions = project_b
4647 .update(cx_b, |p, cx| p.type_definition(&buffer_b, 7, cx))
4648 .await
4649 .unwrap();
4650 cx_b.read(|cx| {
4651 assert_eq!(type_definitions.len(), 1);
4652 let target_buffer = type_definitions[0].target.buffer.read(cx);
4653 assert_eq!(target_buffer.text(), "type T2 = usize;");
4654 assert_eq!(
4655 type_definitions[0].target.range.to_point(target_buffer),
4656 Point::new(0, 5)..Point::new(0, 7)
4657 );
4658 });
4659}
4660
4661#[gpui::test(iterations = 10)]
4662async fn test_references(
4663 executor: BackgroundExecutor,
4664 cx_a: &mut TestAppContext,
4665 cx_b: &mut TestAppContext,
4666) {
4667 let mut server = TestServer::start(executor.clone()).await;
4668 let client_a = server.create_client(cx_a, "user_a").await;
4669 let client_b = server.create_client(cx_b, "user_b").await;
4670 server
4671 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
4672 .await;
4673 let active_call_a = cx_a.read(ActiveCall::global);
4674
4675 client_a.language_registry().add(rust_lang());
4676 let mut fake_language_servers = client_a.language_registry().register_fake_lsp_adapter(
4677 "Rust",
4678 FakeLspAdapter {
4679 name: "my-fake-lsp-adapter",
4680 capabilities: lsp::ServerCapabilities {
4681 references_provider: Some(lsp::OneOf::Left(true)),
4682 ..Default::default()
4683 },
4684 ..Default::default()
4685 },
4686 );
4687
4688 client_a
4689 .fs()
4690 .insert_tree(
4691 "/root",
4692 json!({
4693 "dir-1": {
4694 "one.rs": "const ONE: usize = 1;",
4695 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
4696 },
4697 "dir-2": {
4698 "three.rs": "const THREE: usize = two::TWO + one::ONE;",
4699 }
4700 }),
4701 )
4702 .await;
4703 let (project_a, worktree_id) = client_a.build_local_project("/root/dir-1", cx_a).await;
4704 let project_id = active_call_a
4705 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
4706 .await
4707 .unwrap();
4708 let project_b = client_b.build_remote_project(project_id, cx_b).await;
4709
4710 // Open the file on client B.
4711 let open_buffer = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "one.rs"), cx));
4712 let buffer_b = cx_b.executor().spawn(open_buffer).await.unwrap();
4713
4714 // Request references to a symbol as the guest.
4715 let fake_language_server = fake_language_servers.next().await.unwrap();
4716 let (lsp_response_tx, rx) = mpsc::unbounded::<Result<Option<Vec<lsp::Location>>>>();
4717 fake_language_server.handle_request::<lsp::request::References, _, _>({
4718 let rx = Arc::new(Mutex::new(Some(rx)));
4719 move |params, _| {
4720 assert_eq!(
4721 params.text_document_position.text_document.uri.as_str(),
4722 "file:///root/dir-1/one.rs"
4723 );
4724 let rx = rx.clone();
4725 async move {
4726 let mut response_rx = rx.lock().take().unwrap();
4727 let result = response_rx.next().await.unwrap();
4728 *rx.lock() = Some(response_rx);
4729 result
4730 }
4731 }
4732 });
4733
4734 let references = project_b.update(cx_b, |p, cx| p.references(&buffer_b, 7, cx));
4735
4736 // User is informed that a request is pending.
4737 executor.run_until_parked();
4738 project_b.read_with(cx_b, |project, _| {
4739 let status = project.language_server_statuses().next().cloned().unwrap();
4740 assert_eq!(status.name, "my-fake-lsp-adapter");
4741 assert_eq!(
4742 status.pending_work.values().next().unwrap().message,
4743 Some("Finding references...".into())
4744 );
4745 });
4746
4747 // Cause the language server to respond.
4748 lsp_response_tx
4749 .unbounded_send(Ok(Some(vec![
4750 lsp::Location {
4751 uri: lsp::Url::from_file_path("/root/dir-1/two.rs").unwrap(),
4752 range: lsp::Range::new(lsp::Position::new(0, 24), lsp::Position::new(0, 27)),
4753 },
4754 lsp::Location {
4755 uri: lsp::Url::from_file_path("/root/dir-1/two.rs").unwrap(),
4756 range: lsp::Range::new(lsp::Position::new(0, 35), lsp::Position::new(0, 38)),
4757 },
4758 lsp::Location {
4759 uri: lsp::Url::from_file_path("/root/dir-2/three.rs").unwrap(),
4760 range: lsp::Range::new(lsp::Position::new(0, 37), lsp::Position::new(0, 40)),
4761 },
4762 ])))
4763 .unwrap();
4764
4765 let references = references.await.unwrap();
4766 executor.run_until_parked();
4767 project_b.read_with(cx_b, |project, cx| {
4768 // User is informed that a request is no longer pending.
4769 let status = project.language_server_statuses().next().unwrap();
4770 assert!(status.pending_work.is_empty());
4771
4772 assert_eq!(references.len(), 3);
4773 assert_eq!(project.worktrees().count(), 2);
4774
4775 let two_buffer = references[0].buffer.read(cx);
4776 let three_buffer = references[2].buffer.read(cx);
4777 assert_eq!(
4778 two_buffer.file().unwrap().path().as_ref(),
4779 Path::new("two.rs")
4780 );
4781 assert_eq!(references[1].buffer, references[0].buffer);
4782 assert_eq!(
4783 three_buffer.file().unwrap().full_path(cx),
4784 Path::new("/root/dir-2/three.rs")
4785 );
4786
4787 assert_eq!(references[0].range.to_offset(two_buffer), 24..27);
4788 assert_eq!(references[1].range.to_offset(two_buffer), 35..38);
4789 assert_eq!(references[2].range.to_offset(three_buffer), 37..40);
4790 });
4791
4792 let references = project_b.update(cx_b, |p, cx| p.references(&buffer_b, 7, cx));
4793
4794 // User is informed that a request is pending.
4795 executor.run_until_parked();
4796 project_b.read_with(cx_b, |project, _| {
4797 let status = project.language_server_statuses().next().cloned().unwrap();
4798 assert_eq!(status.name, "my-fake-lsp-adapter");
4799 assert_eq!(
4800 status.pending_work.values().next().unwrap().message,
4801 Some("Finding references...".into())
4802 );
4803 });
4804
4805 // Cause the LSP request to fail.
4806 lsp_response_tx
4807 .unbounded_send(Err(anyhow!("can't find references")))
4808 .unwrap();
4809 references.await.unwrap_err();
4810
4811 // User is informed that the request is no longer pending.
4812 executor.run_until_parked();
4813 project_b.read_with(cx_b, |project, _| {
4814 let status = project.language_server_statuses().next().unwrap();
4815 assert!(status.pending_work.is_empty());
4816 });
4817}
4818
4819#[gpui::test(iterations = 10)]
4820async fn test_project_search(
4821 executor: BackgroundExecutor,
4822 cx_a: &mut TestAppContext,
4823 cx_b: &mut TestAppContext,
4824) {
4825 let mut server = TestServer::start(executor.clone()).await;
4826 let client_a = server.create_client(cx_a, "user_a").await;
4827 let client_b = server.create_client(cx_b, "user_b").await;
4828 server
4829 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
4830 .await;
4831 let active_call_a = cx_a.read(ActiveCall::global);
4832
4833 client_a
4834 .fs()
4835 .insert_tree(
4836 "/root",
4837 json!({
4838 "dir-1": {
4839 "a": "hello world",
4840 "b": "goodnight moon",
4841 "c": "a world of goo",
4842 "d": "world champion of clown world",
4843 },
4844 "dir-2": {
4845 "e": "disney world is fun",
4846 }
4847 }),
4848 )
4849 .await;
4850 let (project_a, _) = client_a.build_local_project("/root/dir-1", cx_a).await;
4851 let (worktree_2, _) = project_a
4852 .update(cx_a, |p, cx| {
4853 p.find_or_create_local_worktree("/root/dir-2", true, cx)
4854 })
4855 .await
4856 .unwrap();
4857 worktree_2
4858 .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
4859 .await;
4860 let project_id = active_call_a
4861 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
4862 .await
4863 .unwrap();
4864
4865 let project_b = client_b.build_remote_project(project_id, cx_b).await;
4866
4867 // Perform a search as the guest.
4868 let mut results = HashMap::default();
4869 let mut search_rx = project_b.update(cx_b, |project, cx| {
4870 project.search(
4871 SearchQuery::text("world", false, false, false, Vec::new(), Vec::new()).unwrap(),
4872 cx,
4873 )
4874 });
4875 while let Some(result) = search_rx.next().await {
4876 match result {
4877 SearchResult::Buffer { buffer, ranges } => {
4878 results.entry(buffer).or_insert(ranges);
4879 }
4880 SearchResult::LimitReached => {
4881 panic!("Unexpectedly reached search limit in tests. If you do want to assert limit-reached, change this panic call.")
4882 }
4883 };
4884 }
4885
4886 let mut ranges_by_path = results
4887 .into_iter()
4888 .map(|(buffer, ranges)| {
4889 buffer.read_with(cx_b, |buffer, cx| {
4890 let path = buffer.file().unwrap().full_path(cx);
4891 let offset_ranges = ranges
4892 .into_iter()
4893 .map(|range| range.to_offset(buffer))
4894 .collect::<Vec<_>>();
4895 (path, offset_ranges)
4896 })
4897 })
4898 .collect::<Vec<_>>();
4899 ranges_by_path.sort_by_key(|(path, _)| path.clone());
4900
4901 assert_eq!(
4902 ranges_by_path,
4903 &[
4904 (PathBuf::from("dir-1/a"), vec![6..11]),
4905 (PathBuf::from("dir-1/c"), vec![2..7]),
4906 (PathBuf::from("dir-1/d"), vec![0..5, 24..29]),
4907 (PathBuf::from("dir-2/e"), vec![7..12]),
4908 ]
4909 );
4910}
4911
4912#[gpui::test(iterations = 10)]
4913async fn test_document_highlights(
4914 executor: BackgroundExecutor,
4915 cx_a: &mut TestAppContext,
4916 cx_b: &mut TestAppContext,
4917) {
4918 let mut server = TestServer::start(executor.clone()).await;
4919 let client_a = server.create_client(cx_a, "user_a").await;
4920 let client_b = server.create_client(cx_b, "user_b").await;
4921 server
4922 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
4923 .await;
4924 let active_call_a = cx_a.read(ActiveCall::global);
4925
4926 client_a
4927 .fs()
4928 .insert_tree(
4929 "/root-1",
4930 json!({
4931 "main.rs": "fn double(number: i32) -> i32 { number + number }",
4932 }),
4933 )
4934 .await;
4935
4936 let mut fake_language_servers = client_a
4937 .language_registry()
4938 .register_fake_lsp_adapter("Rust", Default::default());
4939 client_a.language_registry().add(rust_lang());
4940
4941 let (project_a, worktree_id) = client_a.build_local_project("/root-1", cx_a).await;
4942 let project_id = active_call_a
4943 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
4944 .await
4945 .unwrap();
4946 let project_b = client_b.build_remote_project(project_id, cx_b).await;
4947
4948 // Open the file on client B.
4949 let open_b = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "main.rs"), cx));
4950 let buffer_b = cx_b.executor().spawn(open_b).await.unwrap();
4951
4952 // Request document highlights as the guest.
4953 let fake_language_server = fake_language_servers.next().await.unwrap();
4954 fake_language_server.handle_request::<lsp::request::DocumentHighlightRequest, _, _>(
4955 |params, _| async move {
4956 assert_eq!(
4957 params
4958 .text_document_position_params
4959 .text_document
4960 .uri
4961 .as_str(),
4962 "file:///root-1/main.rs"
4963 );
4964 assert_eq!(
4965 params.text_document_position_params.position,
4966 lsp::Position::new(0, 34)
4967 );
4968 Ok(Some(vec![
4969 lsp::DocumentHighlight {
4970 kind: Some(lsp::DocumentHighlightKind::WRITE),
4971 range: lsp::Range::new(lsp::Position::new(0, 10), lsp::Position::new(0, 16)),
4972 },
4973 lsp::DocumentHighlight {
4974 kind: Some(lsp::DocumentHighlightKind::READ),
4975 range: lsp::Range::new(lsp::Position::new(0, 32), lsp::Position::new(0, 38)),
4976 },
4977 lsp::DocumentHighlight {
4978 kind: Some(lsp::DocumentHighlightKind::READ),
4979 range: lsp::Range::new(lsp::Position::new(0, 41), lsp::Position::new(0, 47)),
4980 },
4981 ]))
4982 },
4983 );
4984
4985 let highlights = project_b
4986 .update(cx_b, |p, cx| p.document_highlights(&buffer_b, 34, cx))
4987 .await
4988 .unwrap();
4989
4990 buffer_b.read_with(cx_b, |buffer, _| {
4991 let snapshot = buffer.snapshot();
4992
4993 let highlights = highlights
4994 .into_iter()
4995 .map(|highlight| (highlight.kind, highlight.range.to_offset(&snapshot)))
4996 .collect::<Vec<_>>();
4997 assert_eq!(
4998 highlights,
4999 &[
5000 (lsp::DocumentHighlightKind::WRITE, 10..16),
5001 (lsp::DocumentHighlightKind::READ, 32..38),
5002 (lsp::DocumentHighlightKind::READ, 41..47)
5003 ]
5004 )
5005 });
5006}
5007
5008#[gpui::test(iterations = 10)]
5009async fn test_lsp_hover(
5010 executor: BackgroundExecutor,
5011 cx_a: &mut TestAppContext,
5012 cx_b: &mut TestAppContext,
5013) {
5014 let mut server = TestServer::start(executor.clone()).await;
5015 let client_a = server.create_client(cx_a, "user_a").await;
5016 let client_b = server.create_client(cx_b, "user_b").await;
5017 server
5018 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
5019 .await;
5020 let active_call_a = cx_a.read(ActiveCall::global);
5021
5022 client_a
5023 .fs()
5024 .insert_tree(
5025 "/root-1",
5026 json!({
5027 "main.rs": "use std::collections::HashMap;",
5028 }),
5029 )
5030 .await;
5031
5032 client_a.language_registry().add(rust_lang());
5033 let language_server_names = ["rust-analyzer", "CrabLang-ls"];
5034 let mut fake_language_servers = client_a
5035 .language_registry()
5036 .register_specific_fake_lsp_adapter(
5037 "Rust",
5038 true,
5039 FakeLspAdapter {
5040 name: "rust-analyzer",
5041 capabilities: lsp::ServerCapabilities {
5042 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
5043 ..lsp::ServerCapabilities::default()
5044 },
5045 ..FakeLspAdapter::default()
5046 },
5047 );
5048 let _other_server = client_a
5049 .language_registry()
5050 .register_specific_fake_lsp_adapter(
5051 "Rust",
5052 false,
5053 FakeLspAdapter {
5054 name: "CrabLang-ls",
5055 capabilities: lsp::ServerCapabilities {
5056 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
5057 ..lsp::ServerCapabilities::default()
5058 },
5059 ..FakeLspAdapter::default()
5060 },
5061 );
5062
5063 let (project_a, worktree_id) = client_a.build_local_project("/root-1", cx_a).await;
5064 let project_id = active_call_a
5065 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
5066 .await
5067 .unwrap();
5068 let project_b = client_b.build_remote_project(project_id, cx_b).await;
5069
5070 // Open the file as the guest
5071 let open_buffer = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "main.rs"), cx));
5072 let buffer_b = cx_b.executor().spawn(open_buffer).await.unwrap();
5073
5074 let mut servers_with_hover_requests = HashMap::default();
5075 for i in 0..language_server_names.len() {
5076 let new_server = fake_language_servers.next().await.unwrap_or_else(|| {
5077 panic!(
5078 "Failed to get language server #{i} with name {}",
5079 &language_server_names[i]
5080 )
5081 });
5082 let new_server_name = new_server.server.name();
5083 assert!(
5084 !servers_with_hover_requests.contains_key(new_server_name),
5085 "Unexpected: initialized server with the same name twice. Name: `{new_server_name}`"
5086 );
5087 let new_server_name = new_server_name.to_string();
5088 match new_server_name.as_str() {
5089 "CrabLang-ls" => {
5090 servers_with_hover_requests.insert(
5091 new_server_name.clone(),
5092 new_server.handle_request::<lsp::request::HoverRequest, _, _>(
5093 move |params, _| {
5094 assert_eq!(
5095 params
5096 .text_document_position_params
5097 .text_document
5098 .uri
5099 .as_str(),
5100 "file:///root-1/main.rs"
5101 );
5102 let name = new_server_name.clone();
5103 async move {
5104 Ok(Some(lsp::Hover {
5105 contents: lsp::HoverContents::Scalar(
5106 lsp::MarkedString::String(format!("{name} hover")),
5107 ),
5108 range: None,
5109 }))
5110 }
5111 },
5112 ),
5113 );
5114 }
5115 "rust-analyzer" => {
5116 servers_with_hover_requests.insert(
5117 new_server_name.clone(),
5118 new_server.handle_request::<lsp::request::HoverRequest, _, _>(
5119 |params, _| async move {
5120 assert_eq!(
5121 params
5122 .text_document_position_params
5123 .text_document
5124 .uri
5125 .as_str(),
5126 "file:///root-1/main.rs"
5127 );
5128 assert_eq!(
5129 params.text_document_position_params.position,
5130 lsp::Position::new(0, 22)
5131 );
5132 Ok(Some(lsp::Hover {
5133 contents: lsp::HoverContents::Array(vec![
5134 lsp::MarkedString::String("Test hover content.".to_string()),
5135 lsp::MarkedString::LanguageString(lsp::LanguageString {
5136 language: "Rust".to_string(),
5137 value: "let foo = 42;".to_string(),
5138 }),
5139 ]),
5140 range: Some(lsp::Range::new(
5141 lsp::Position::new(0, 22),
5142 lsp::Position::new(0, 29),
5143 )),
5144 }))
5145 },
5146 ),
5147 );
5148 }
5149 unexpected => panic!("Unexpected server name: {unexpected}"),
5150 }
5151 }
5152
5153 // Request hover information as the guest.
5154 let mut hovers = project_b
5155 .update(cx_b, |p, cx| p.hover(&buffer_b, 22, cx))
5156 .await;
5157 assert_eq!(
5158 hovers.len(),
5159 2,
5160 "Expected two hovers from both language servers, but got: {hovers:?}"
5161 );
5162
5163 let _: Vec<()> = futures::future::join_all(servers_with_hover_requests.into_values().map(
5164 |mut hover_request| async move {
5165 hover_request
5166 .next()
5167 .await
5168 .expect("All hover requests should have been triggered")
5169 },
5170 ))
5171 .await;
5172
5173 hovers.sort_by_key(|hover| hover.contents.len());
5174 let first_hover = hovers.first().cloned().unwrap();
5175 assert_eq!(
5176 first_hover.contents,
5177 vec![project::HoverBlock {
5178 text: "CrabLang-ls hover".to_string(),
5179 kind: HoverBlockKind::Markdown,
5180 },]
5181 );
5182 let second_hover = hovers.last().cloned().unwrap();
5183 assert_eq!(
5184 second_hover.contents,
5185 vec![
5186 project::HoverBlock {
5187 text: "Test hover content.".to_string(),
5188 kind: HoverBlockKind::Markdown,
5189 },
5190 project::HoverBlock {
5191 text: "let foo = 42;".to_string(),
5192 kind: HoverBlockKind::Code {
5193 language: "Rust".to_string()
5194 },
5195 }
5196 ]
5197 );
5198 buffer_b.read_with(cx_b, |buffer, _| {
5199 let snapshot = buffer.snapshot();
5200 assert_eq!(second_hover.range.unwrap().to_offset(&snapshot), 22..29);
5201 });
5202}
5203
5204#[gpui::test(iterations = 10)]
5205async fn test_project_symbols(
5206 executor: BackgroundExecutor,
5207 cx_a: &mut TestAppContext,
5208 cx_b: &mut TestAppContext,
5209) {
5210 let mut server = TestServer::start(executor.clone()).await;
5211 let client_a = server.create_client(cx_a, "user_a").await;
5212 let client_b = server.create_client(cx_b, "user_b").await;
5213 server
5214 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
5215 .await;
5216 let active_call_a = cx_a.read(ActiveCall::global);
5217
5218 client_a.language_registry().add(rust_lang());
5219 let mut fake_language_servers = client_a
5220 .language_registry()
5221 .register_fake_lsp_adapter("Rust", Default::default());
5222
5223 client_a
5224 .fs()
5225 .insert_tree(
5226 "/code",
5227 json!({
5228 "crate-1": {
5229 "one.rs": "const ONE: usize = 1;",
5230 },
5231 "crate-2": {
5232 "two.rs": "const TWO: usize = 2; const THREE: usize = 3;",
5233 },
5234 "private": {
5235 "passwords.txt": "the-password",
5236 }
5237 }),
5238 )
5239 .await;
5240 let (project_a, worktree_id) = client_a.build_local_project("/code/crate-1", cx_a).await;
5241 let project_id = active_call_a
5242 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
5243 .await
5244 .unwrap();
5245 let project_b = client_b.build_remote_project(project_id, cx_b).await;
5246
5247 // Cause the language server to start.
5248 let open_buffer_task =
5249 project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "one.rs"), cx));
5250 let _buffer = cx_b.executor().spawn(open_buffer_task).await.unwrap();
5251
5252 let fake_language_server = fake_language_servers.next().await.unwrap();
5253 fake_language_server.handle_request::<lsp::WorkspaceSymbolRequest, _, _>(|_, _| async move {
5254 Ok(Some(lsp::WorkspaceSymbolResponse::Flat(vec![
5255 #[allow(deprecated)]
5256 lsp::SymbolInformation {
5257 name: "TWO".into(),
5258 location: lsp::Location {
5259 uri: lsp::Url::from_file_path("/code/crate-2/two.rs").unwrap(),
5260 range: lsp::Range::new(lsp::Position::new(0, 6), lsp::Position::new(0, 9)),
5261 },
5262 kind: lsp::SymbolKind::CONSTANT,
5263 tags: None,
5264 container_name: None,
5265 deprecated: None,
5266 },
5267 ])))
5268 });
5269
5270 // Request the definition of a symbol as the guest.
5271 let symbols = project_b
5272 .update(cx_b, |p, cx| p.symbols("two", cx))
5273 .await
5274 .unwrap();
5275 assert_eq!(symbols.len(), 1);
5276 assert_eq!(symbols[0].name, "TWO");
5277
5278 // Open one of the returned symbols.
5279 let buffer_b_2 = project_b
5280 .update(cx_b, |project, cx| {
5281 project.open_buffer_for_symbol(&symbols[0], cx)
5282 })
5283 .await
5284 .unwrap();
5285
5286 buffer_b_2.read_with(cx_b, |buffer, cx| {
5287 assert_eq!(
5288 buffer.file().unwrap().full_path(cx),
5289 Path::new("/code/crate-2/two.rs")
5290 );
5291 });
5292
5293 // Attempt to craft a symbol and violate host's privacy by opening an arbitrary file.
5294 let mut fake_symbol = symbols[0].clone();
5295 fake_symbol.path.path = Path::new("/code/secrets").into();
5296 let error = project_b
5297 .update(cx_b, |project, cx| {
5298 project.open_buffer_for_symbol(&fake_symbol, cx)
5299 })
5300 .await
5301 .unwrap_err();
5302 assert!(error.to_string().contains("invalid symbol signature"));
5303}
5304
5305#[gpui::test(iterations = 10)]
5306async fn test_open_buffer_while_getting_definition_pointing_to_it(
5307 executor: BackgroundExecutor,
5308 cx_a: &mut TestAppContext,
5309 cx_b: &mut TestAppContext,
5310 mut rng: StdRng,
5311) {
5312 let mut server = TestServer::start(executor.clone()).await;
5313 let client_a = server.create_client(cx_a, "user_a").await;
5314 let client_b = server.create_client(cx_b, "user_b").await;
5315 server
5316 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
5317 .await;
5318 let active_call_a = cx_a.read(ActiveCall::global);
5319
5320 client_a.language_registry().add(rust_lang());
5321 let mut fake_language_servers = client_a
5322 .language_registry()
5323 .register_fake_lsp_adapter("Rust", Default::default());
5324
5325 client_a
5326 .fs()
5327 .insert_tree(
5328 "/root",
5329 json!({
5330 "a.rs": "const ONE: usize = b::TWO;",
5331 "b.rs": "const TWO: usize = 2",
5332 }),
5333 )
5334 .await;
5335 let (project_a, worktree_id) = client_a.build_local_project("/root", cx_a).await;
5336 let project_id = active_call_a
5337 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
5338 .await
5339 .unwrap();
5340 let project_b = client_b.build_remote_project(project_id, cx_b).await;
5341
5342 let open_buffer_task = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx));
5343 let buffer_b1 = cx_b.executor().spawn(open_buffer_task).await.unwrap();
5344
5345 let fake_language_server = fake_language_servers.next().await.unwrap();
5346 fake_language_server.handle_request::<lsp::request::GotoDefinition, _, _>(|_, _| async move {
5347 Ok(Some(lsp::GotoDefinitionResponse::Scalar(
5348 lsp::Location::new(
5349 lsp::Url::from_file_path("/root/b.rs").unwrap(),
5350 lsp::Range::new(lsp::Position::new(0, 6), lsp::Position::new(0, 9)),
5351 ),
5352 )))
5353 });
5354
5355 let definitions;
5356 let buffer_b2;
5357 if rng.gen() {
5358 definitions = project_b.update(cx_b, |p, cx| p.definition(&buffer_b1, 23, cx));
5359 buffer_b2 = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "b.rs"), cx));
5360 } else {
5361 buffer_b2 = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "b.rs"), cx));
5362 definitions = project_b.update(cx_b, |p, cx| p.definition(&buffer_b1, 23, cx));
5363 }
5364
5365 let buffer_b2 = buffer_b2.await.unwrap();
5366 let definitions = definitions.await.unwrap();
5367 assert_eq!(definitions.len(), 1);
5368 assert_eq!(definitions[0].target.buffer, buffer_b2);
5369}
5370
5371#[gpui::test(iterations = 10)]
5372async fn test_contacts(
5373 executor: BackgroundExecutor,
5374 cx_a: &mut TestAppContext,
5375 cx_b: &mut TestAppContext,
5376 cx_c: &mut TestAppContext,
5377 cx_d: &mut TestAppContext,
5378) {
5379 let mut server = TestServer::start(executor.clone()).await;
5380 let client_a = server.create_client(cx_a, "user_a").await;
5381 let client_b = server.create_client(cx_b, "user_b").await;
5382 let client_c = server.create_client(cx_c, "user_c").await;
5383 let client_d = server.create_client(cx_d, "user_d").await;
5384 server
5385 .make_contacts(&mut [(&client_a, cx_a), (&client_b, cx_b), (&client_c, cx_c)])
5386 .await;
5387 let active_call_a = cx_a.read(ActiveCall::global);
5388 let active_call_b = cx_b.read(ActiveCall::global);
5389 let active_call_c = cx_c.read(ActiveCall::global);
5390 let _active_call_d = cx_d.read(ActiveCall::global);
5391
5392 executor.run_until_parked();
5393 assert_eq!(
5394 contacts(&client_a, cx_a),
5395 [
5396 ("user_b".to_string(), "online", "free"),
5397 ("user_c".to_string(), "online", "free")
5398 ]
5399 );
5400 assert_eq!(
5401 contacts(&client_b, cx_b),
5402 [
5403 ("user_a".to_string(), "online", "free"),
5404 ("user_c".to_string(), "online", "free")
5405 ]
5406 );
5407 assert_eq!(
5408 contacts(&client_c, cx_c),
5409 [
5410 ("user_a".to_string(), "online", "free"),
5411 ("user_b".to_string(), "online", "free")
5412 ]
5413 );
5414 assert_eq!(contacts(&client_d, cx_d), []);
5415
5416 server.disconnect_client(client_c.peer_id().unwrap());
5417 server.forbid_connections();
5418 executor.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
5419 assert_eq!(
5420 contacts(&client_a, cx_a),
5421 [
5422 ("user_b".to_string(), "online", "free"),
5423 ("user_c".to_string(), "offline", "free")
5424 ]
5425 );
5426 assert_eq!(
5427 contacts(&client_b, cx_b),
5428 [
5429 ("user_a".to_string(), "online", "free"),
5430 ("user_c".to_string(), "offline", "free")
5431 ]
5432 );
5433 assert_eq!(contacts(&client_c, cx_c), []);
5434 assert_eq!(contacts(&client_d, cx_d), []);
5435
5436 server.allow_connections();
5437 client_c
5438 .authenticate_and_connect(false, &cx_c.to_async())
5439 .await
5440 .unwrap();
5441
5442 executor.run_until_parked();
5443 assert_eq!(
5444 contacts(&client_a, cx_a),
5445 [
5446 ("user_b".to_string(), "online", "free"),
5447 ("user_c".to_string(), "online", "free")
5448 ]
5449 );
5450 assert_eq!(
5451 contacts(&client_b, cx_b),
5452 [
5453 ("user_a".to_string(), "online", "free"),
5454 ("user_c".to_string(), "online", "free")
5455 ]
5456 );
5457 assert_eq!(
5458 contacts(&client_c, cx_c),
5459 [
5460 ("user_a".to_string(), "online", "free"),
5461 ("user_b".to_string(), "online", "free")
5462 ]
5463 );
5464 assert_eq!(contacts(&client_d, cx_d), []);
5465
5466 active_call_a
5467 .update(cx_a, |call, cx| {
5468 call.invite(client_b.user_id().unwrap(), None, cx)
5469 })
5470 .await
5471 .unwrap();
5472 executor.run_until_parked();
5473 assert_eq!(
5474 contacts(&client_a, cx_a),
5475 [
5476 ("user_b".to_string(), "online", "busy"),
5477 ("user_c".to_string(), "online", "free")
5478 ]
5479 );
5480 assert_eq!(
5481 contacts(&client_b, cx_b),
5482 [
5483 ("user_a".to_string(), "online", "busy"),
5484 ("user_c".to_string(), "online", "free")
5485 ]
5486 );
5487 assert_eq!(
5488 contacts(&client_c, cx_c),
5489 [
5490 ("user_a".to_string(), "online", "busy"),
5491 ("user_b".to_string(), "online", "busy")
5492 ]
5493 );
5494 assert_eq!(contacts(&client_d, cx_d), []);
5495
5496 // Client B and client D become contacts while client B is being called.
5497 server
5498 .make_contacts(&mut [(&client_b, cx_b), (&client_d, cx_d)])
5499 .await;
5500 executor.run_until_parked();
5501 assert_eq!(
5502 contacts(&client_a, cx_a),
5503 [
5504 ("user_b".to_string(), "online", "busy"),
5505 ("user_c".to_string(), "online", "free")
5506 ]
5507 );
5508 assert_eq!(
5509 contacts(&client_b, cx_b),
5510 [
5511 ("user_a".to_string(), "online", "busy"),
5512 ("user_c".to_string(), "online", "free"),
5513 ("user_d".to_string(), "online", "free"),
5514 ]
5515 );
5516 assert_eq!(
5517 contacts(&client_c, cx_c),
5518 [
5519 ("user_a".to_string(), "online", "busy"),
5520 ("user_b".to_string(), "online", "busy")
5521 ]
5522 );
5523 assert_eq!(
5524 contacts(&client_d, cx_d),
5525 [("user_b".to_string(), "online", "busy")]
5526 );
5527
5528 active_call_b.update(cx_b, |call, cx| call.decline_incoming(cx).unwrap());
5529 executor.run_until_parked();
5530 assert_eq!(
5531 contacts(&client_a, cx_a),
5532 [
5533 ("user_b".to_string(), "online", "free"),
5534 ("user_c".to_string(), "online", "free")
5535 ]
5536 );
5537 assert_eq!(
5538 contacts(&client_b, cx_b),
5539 [
5540 ("user_a".to_string(), "online", "free"),
5541 ("user_c".to_string(), "online", "free"),
5542 ("user_d".to_string(), "online", "free")
5543 ]
5544 );
5545 assert_eq!(
5546 contacts(&client_c, cx_c),
5547 [
5548 ("user_a".to_string(), "online", "free"),
5549 ("user_b".to_string(), "online", "free")
5550 ]
5551 );
5552 assert_eq!(
5553 contacts(&client_d, cx_d),
5554 [("user_b".to_string(), "online", "free")]
5555 );
5556
5557 active_call_c
5558 .update(cx_c, |call, cx| {
5559 call.invite(client_a.user_id().unwrap(), None, cx)
5560 })
5561 .await
5562 .unwrap();
5563 executor.run_until_parked();
5564 assert_eq!(
5565 contacts(&client_a, cx_a),
5566 [
5567 ("user_b".to_string(), "online", "free"),
5568 ("user_c".to_string(), "online", "busy")
5569 ]
5570 );
5571 assert_eq!(
5572 contacts(&client_b, cx_b),
5573 [
5574 ("user_a".to_string(), "online", "busy"),
5575 ("user_c".to_string(), "online", "busy"),
5576 ("user_d".to_string(), "online", "free")
5577 ]
5578 );
5579 assert_eq!(
5580 contacts(&client_c, cx_c),
5581 [
5582 ("user_a".to_string(), "online", "busy"),
5583 ("user_b".to_string(), "online", "free")
5584 ]
5585 );
5586 assert_eq!(
5587 contacts(&client_d, cx_d),
5588 [("user_b".to_string(), "online", "free")]
5589 );
5590
5591 active_call_a
5592 .update(cx_a, |call, cx| call.accept_incoming(cx))
5593 .await
5594 .unwrap();
5595 executor.run_until_parked();
5596 assert_eq!(
5597 contacts(&client_a, cx_a),
5598 [
5599 ("user_b".to_string(), "online", "free"),
5600 ("user_c".to_string(), "online", "busy")
5601 ]
5602 );
5603 assert_eq!(
5604 contacts(&client_b, cx_b),
5605 [
5606 ("user_a".to_string(), "online", "busy"),
5607 ("user_c".to_string(), "online", "busy"),
5608 ("user_d".to_string(), "online", "free")
5609 ]
5610 );
5611 assert_eq!(
5612 contacts(&client_c, cx_c),
5613 [
5614 ("user_a".to_string(), "online", "busy"),
5615 ("user_b".to_string(), "online", "free")
5616 ]
5617 );
5618 assert_eq!(
5619 contacts(&client_d, cx_d),
5620 [("user_b".to_string(), "online", "free")]
5621 );
5622
5623 active_call_a
5624 .update(cx_a, |call, cx| {
5625 call.invite(client_b.user_id().unwrap(), None, cx)
5626 })
5627 .await
5628 .unwrap();
5629 executor.run_until_parked();
5630 assert_eq!(
5631 contacts(&client_a, cx_a),
5632 [
5633 ("user_b".to_string(), "online", "busy"),
5634 ("user_c".to_string(), "online", "busy")
5635 ]
5636 );
5637 assert_eq!(
5638 contacts(&client_b, cx_b),
5639 [
5640 ("user_a".to_string(), "online", "busy"),
5641 ("user_c".to_string(), "online", "busy"),
5642 ("user_d".to_string(), "online", "free")
5643 ]
5644 );
5645 assert_eq!(
5646 contacts(&client_c, cx_c),
5647 [
5648 ("user_a".to_string(), "online", "busy"),
5649 ("user_b".to_string(), "online", "busy")
5650 ]
5651 );
5652 assert_eq!(
5653 contacts(&client_d, cx_d),
5654 [("user_b".to_string(), "online", "busy")]
5655 );
5656
5657 active_call_a
5658 .update(cx_a, |call, cx| call.hang_up(cx))
5659 .await
5660 .unwrap();
5661 executor.run_until_parked();
5662 assert_eq!(
5663 contacts(&client_a, cx_a),
5664 [
5665 ("user_b".to_string(), "online", "free"),
5666 ("user_c".to_string(), "online", "free")
5667 ]
5668 );
5669 assert_eq!(
5670 contacts(&client_b, cx_b),
5671 [
5672 ("user_a".to_string(), "online", "free"),
5673 ("user_c".to_string(), "online", "free"),
5674 ("user_d".to_string(), "online", "free")
5675 ]
5676 );
5677 assert_eq!(
5678 contacts(&client_c, cx_c),
5679 [
5680 ("user_a".to_string(), "online", "free"),
5681 ("user_b".to_string(), "online", "free")
5682 ]
5683 );
5684 assert_eq!(
5685 contacts(&client_d, cx_d),
5686 [("user_b".to_string(), "online", "free")]
5687 );
5688
5689 active_call_a
5690 .update(cx_a, |call, cx| {
5691 call.invite(client_b.user_id().unwrap(), None, cx)
5692 })
5693 .await
5694 .unwrap();
5695 executor.run_until_parked();
5696 assert_eq!(
5697 contacts(&client_a, cx_a),
5698 [
5699 ("user_b".to_string(), "online", "busy"),
5700 ("user_c".to_string(), "online", "free")
5701 ]
5702 );
5703 assert_eq!(
5704 contacts(&client_b, cx_b),
5705 [
5706 ("user_a".to_string(), "online", "busy"),
5707 ("user_c".to_string(), "online", "free"),
5708 ("user_d".to_string(), "online", "free")
5709 ]
5710 );
5711 assert_eq!(
5712 contacts(&client_c, cx_c),
5713 [
5714 ("user_a".to_string(), "online", "busy"),
5715 ("user_b".to_string(), "online", "busy")
5716 ]
5717 );
5718 assert_eq!(
5719 contacts(&client_d, cx_d),
5720 [("user_b".to_string(), "online", "busy")]
5721 );
5722
5723 server.forbid_connections();
5724 server.disconnect_client(client_a.peer_id().unwrap());
5725 executor.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
5726 assert_eq!(contacts(&client_a, cx_a), []);
5727 assert_eq!(
5728 contacts(&client_b, cx_b),
5729 [
5730 ("user_a".to_string(), "offline", "free"),
5731 ("user_c".to_string(), "online", "free"),
5732 ("user_d".to_string(), "online", "free")
5733 ]
5734 );
5735 assert_eq!(
5736 contacts(&client_c, cx_c),
5737 [
5738 ("user_a".to_string(), "offline", "free"),
5739 ("user_b".to_string(), "online", "free")
5740 ]
5741 );
5742 assert_eq!(
5743 contacts(&client_d, cx_d),
5744 [("user_b".to_string(), "online", "free")]
5745 );
5746
5747 // Test removing a contact
5748 client_b
5749 .user_store()
5750 .update(cx_b, |store, cx| {
5751 store.remove_contact(client_c.user_id().unwrap(), cx)
5752 })
5753 .await
5754 .unwrap();
5755 executor.run_until_parked();
5756 assert_eq!(
5757 contacts(&client_b, cx_b),
5758 [
5759 ("user_a".to_string(), "offline", "free"),
5760 ("user_d".to_string(), "online", "free")
5761 ]
5762 );
5763 assert_eq!(
5764 contacts(&client_c, cx_c),
5765 [("user_a".to_string(), "offline", "free"),]
5766 );
5767
5768 fn contacts(
5769 client: &TestClient,
5770 cx: &TestAppContext,
5771 ) -> Vec<(String, &'static str, &'static str)> {
5772 client.user_store().read_with(cx, |store, _| {
5773 store
5774 .contacts()
5775 .iter()
5776 .map(|contact| {
5777 (
5778 contact.user.github_login.clone(),
5779 if contact.online { "online" } else { "offline" },
5780 if contact.busy { "busy" } else { "free" },
5781 )
5782 })
5783 .collect()
5784 })
5785 }
5786}
5787
5788#[gpui::test(iterations = 10)]
5789async fn test_contact_requests(
5790 executor: BackgroundExecutor,
5791 cx_a: &mut TestAppContext,
5792 cx_a2: &mut TestAppContext,
5793 cx_b: &mut TestAppContext,
5794 cx_b2: &mut TestAppContext,
5795 cx_c: &mut TestAppContext,
5796 cx_c2: &mut TestAppContext,
5797) {
5798 // Connect to a server as 3 clients.
5799 let mut server = TestServer::start(executor.clone()).await;
5800 let client_a = server.create_client(cx_a, "user_a").await;
5801 let client_a2 = server.create_client(cx_a2, "user_a").await;
5802 let client_b = server.create_client(cx_b, "user_b").await;
5803 let client_b2 = server.create_client(cx_b2, "user_b").await;
5804 let client_c = server.create_client(cx_c, "user_c").await;
5805 let client_c2 = server.create_client(cx_c2, "user_c").await;
5806
5807 assert_eq!(client_a.user_id().unwrap(), client_a2.user_id().unwrap());
5808 assert_eq!(client_b.user_id().unwrap(), client_b2.user_id().unwrap());
5809 assert_eq!(client_c.user_id().unwrap(), client_c2.user_id().unwrap());
5810
5811 // User A and User C request that user B become their contact.
5812 client_a
5813 .user_store()
5814 .update(cx_a, |store, cx| {
5815 store.request_contact(client_b.user_id().unwrap(), cx)
5816 })
5817 .await
5818 .unwrap();
5819 client_c
5820 .user_store()
5821 .update(cx_c, |store, cx| {
5822 store.request_contact(client_b.user_id().unwrap(), cx)
5823 })
5824 .await
5825 .unwrap();
5826 executor.run_until_parked();
5827
5828 // All users see the pending request appear in all their clients.
5829 assert_eq!(
5830 client_a.summarize_contacts(cx_a).outgoing_requests,
5831 &["user_b"]
5832 );
5833 assert_eq!(
5834 client_a2.summarize_contacts(cx_a2).outgoing_requests,
5835 &["user_b"]
5836 );
5837 assert_eq!(
5838 client_b.summarize_contacts(cx_b).incoming_requests,
5839 &["user_a", "user_c"]
5840 );
5841 assert_eq!(
5842 client_b2.summarize_contacts(cx_b2).incoming_requests,
5843 &["user_a", "user_c"]
5844 );
5845 assert_eq!(
5846 client_c.summarize_contacts(cx_c).outgoing_requests,
5847 &["user_b"]
5848 );
5849 assert_eq!(
5850 client_c2.summarize_contacts(cx_c2).outgoing_requests,
5851 &["user_b"]
5852 );
5853
5854 // Contact requests are present upon connecting (tested here via disconnect/reconnect)
5855 disconnect_and_reconnect(&client_a, cx_a).await;
5856 disconnect_and_reconnect(&client_b, cx_b).await;
5857 disconnect_and_reconnect(&client_c, cx_c).await;
5858 executor.run_until_parked();
5859 assert_eq!(
5860 client_a.summarize_contacts(cx_a).outgoing_requests,
5861 &["user_b"]
5862 );
5863 assert_eq!(
5864 client_b.summarize_contacts(cx_b).incoming_requests,
5865 &["user_a", "user_c"]
5866 );
5867 assert_eq!(
5868 client_c.summarize_contacts(cx_c).outgoing_requests,
5869 &["user_b"]
5870 );
5871
5872 // User B accepts the request from user A.
5873 client_b
5874 .user_store()
5875 .update(cx_b, |store, cx| {
5876 store.respond_to_contact_request(client_a.user_id().unwrap(), true, cx)
5877 })
5878 .await
5879 .unwrap();
5880
5881 executor.run_until_parked();
5882
5883 // User B sees user A as their contact now in all client, and the incoming request from them is removed.
5884 let contacts_b = client_b.summarize_contacts(cx_b);
5885 assert_eq!(contacts_b.current, &["user_a"]);
5886 assert_eq!(contacts_b.incoming_requests, &["user_c"]);
5887 let contacts_b2 = client_b2.summarize_contacts(cx_b2);
5888 assert_eq!(contacts_b2.current, &["user_a"]);
5889 assert_eq!(contacts_b2.incoming_requests, &["user_c"]);
5890
5891 // User A sees user B as their contact now in all clients, and the outgoing request to them is removed.
5892 let contacts_a = client_a.summarize_contacts(cx_a);
5893 assert_eq!(contacts_a.current, &["user_b"]);
5894 assert!(contacts_a.outgoing_requests.is_empty());
5895 let contacts_a2 = client_a2.summarize_contacts(cx_a2);
5896 assert_eq!(contacts_a2.current, &["user_b"]);
5897 assert!(contacts_a2.outgoing_requests.is_empty());
5898
5899 // Contacts are present upon connecting (tested here via disconnect/reconnect)
5900 disconnect_and_reconnect(&client_a, cx_a).await;
5901 disconnect_and_reconnect(&client_b, cx_b).await;
5902 disconnect_and_reconnect(&client_c, cx_c).await;
5903 executor.run_until_parked();
5904 assert_eq!(client_a.summarize_contacts(cx_a).current, &["user_b"]);
5905 assert_eq!(client_b.summarize_contacts(cx_b).current, &["user_a"]);
5906 assert_eq!(
5907 client_b.summarize_contacts(cx_b).incoming_requests,
5908 &["user_c"]
5909 );
5910 assert!(client_c.summarize_contacts(cx_c).current.is_empty());
5911 assert_eq!(
5912 client_c.summarize_contacts(cx_c).outgoing_requests,
5913 &["user_b"]
5914 );
5915
5916 // User B rejects the request from user C.
5917 client_b
5918 .user_store()
5919 .update(cx_b, |store, cx| {
5920 store.respond_to_contact_request(client_c.user_id().unwrap(), false, cx)
5921 })
5922 .await
5923 .unwrap();
5924
5925 executor.run_until_parked();
5926
5927 // User B doesn't see user C as their contact, and the incoming request from them is removed.
5928 let contacts_b = client_b.summarize_contacts(cx_b);
5929 assert_eq!(contacts_b.current, &["user_a"]);
5930 assert!(contacts_b.incoming_requests.is_empty());
5931 let contacts_b2 = client_b2.summarize_contacts(cx_b2);
5932 assert_eq!(contacts_b2.current, &["user_a"]);
5933 assert!(contacts_b2.incoming_requests.is_empty());
5934
5935 // User C doesn't see user B as their contact, and the outgoing request to them is removed.
5936 let contacts_c = client_c.summarize_contacts(cx_c);
5937 assert!(contacts_c.current.is_empty());
5938 assert!(contacts_c.outgoing_requests.is_empty());
5939 let contacts_c2 = client_c2.summarize_contacts(cx_c2);
5940 assert!(contacts_c2.current.is_empty());
5941 assert!(contacts_c2.outgoing_requests.is_empty());
5942
5943 // Incoming/outgoing requests are not present upon connecting (tested here via disconnect/reconnect)
5944 disconnect_and_reconnect(&client_a, cx_a).await;
5945 disconnect_and_reconnect(&client_b, cx_b).await;
5946 disconnect_and_reconnect(&client_c, cx_c).await;
5947 executor.run_until_parked();
5948 assert_eq!(client_a.summarize_contacts(cx_a).current, &["user_b"]);
5949 assert_eq!(client_b.summarize_contacts(cx_b).current, &["user_a"]);
5950 assert!(client_b
5951 .summarize_contacts(cx_b)
5952 .incoming_requests
5953 .is_empty());
5954 assert!(client_c.summarize_contacts(cx_c).current.is_empty());
5955 assert!(client_c
5956 .summarize_contacts(cx_c)
5957 .outgoing_requests
5958 .is_empty());
5959
5960 async fn disconnect_and_reconnect(client: &TestClient, cx: &mut TestAppContext) {
5961 client.disconnect(&cx.to_async());
5962 client.clear_contacts(cx).await;
5963 client
5964 .authenticate_and_connect(false, &cx.to_async())
5965 .await
5966 .unwrap();
5967 }
5968}
5969
5970#[gpui::test(iterations = 10)]
5971async fn test_join_call_after_screen_was_shared(
5972 executor: BackgroundExecutor,
5973 cx_a: &mut TestAppContext,
5974 cx_b: &mut TestAppContext,
5975) {
5976 let mut server = TestServer::start(executor.clone()).await;
5977
5978 let client_a = server.create_client(cx_a, "user_a").await;
5979 let client_b = server.create_client(cx_b, "user_b").await;
5980 server
5981 .make_contacts(&mut [(&client_a, cx_a), (&client_b, cx_b)])
5982 .await;
5983
5984 let active_call_a = cx_a.read(ActiveCall::global);
5985 let active_call_b = cx_b.read(ActiveCall::global);
5986
5987 // Call users B and C from client A.
5988 active_call_a
5989 .update(cx_a, |call, cx| {
5990 call.invite(client_b.user_id().unwrap(), None, cx)
5991 })
5992 .await
5993 .unwrap();
5994
5995 let room_a = active_call_a.read_with(cx_a, |call, _| call.room().unwrap().clone());
5996 executor.run_until_parked();
5997 assert_eq!(
5998 room_participants(&room_a, cx_a),
5999 RoomParticipants {
6000 remote: Default::default(),
6001 pending: vec!["user_b".to_string()]
6002 }
6003 );
6004
6005 // User B receives the call.
6006
6007 let mut incoming_call_b = active_call_b.read_with(cx_b, |call, _| call.incoming());
6008 let call_b = incoming_call_b.next().await.unwrap().unwrap();
6009 assert_eq!(call_b.calling_user.github_login, "user_a");
6010
6011 // User A shares their screen
6012 let display = MacOSDisplay::new();
6013 active_call_a
6014 .update(cx_a, |call, cx| {
6015 call.room().unwrap().update(cx, |room, cx| {
6016 room.set_display_sources(vec![display.clone()]);
6017 room.share_screen(cx)
6018 })
6019 })
6020 .await
6021 .unwrap();
6022
6023 client_b.user_store().update(cx_b, |user_store, _| {
6024 user_store.clear_cache();
6025 });
6026
6027 // User B joins the room
6028 active_call_b
6029 .update(cx_b, |call, cx| call.accept_incoming(cx))
6030 .await
6031 .unwrap();
6032
6033 let room_b = active_call_b.read_with(cx_b, |call, _| call.room().unwrap().clone());
6034 assert!(incoming_call_b.next().await.unwrap().is_none());
6035
6036 executor.run_until_parked();
6037 assert_eq!(
6038 room_participants(&room_a, cx_a),
6039 RoomParticipants {
6040 remote: vec!["user_b".to_string()],
6041 pending: vec![],
6042 }
6043 );
6044 assert_eq!(
6045 room_participants(&room_b, cx_b),
6046 RoomParticipants {
6047 remote: vec!["user_a".to_string()],
6048 pending: vec![],
6049 }
6050 );
6051
6052 // Ensure User B sees User A's screenshare.
6053
6054 room_b.read_with(cx_b, |room, _| {
6055 assert_eq!(
6056 room.remote_participants()
6057 .get(&client_a.user_id().unwrap())
6058 .unwrap()
6059 .video_tracks
6060 .len(),
6061 1
6062 );
6063 });
6064}
6065
6066#[gpui::test]
6067async fn test_right_click_menu_behind_collab_panel(cx: &mut TestAppContext) {
6068 let mut server = TestServer::start(cx.executor().clone()).await;
6069 let client_a = server.create_client(cx, "user_a").await;
6070 let (_workspace_a, cx) = client_a.build_test_workspace(cx).await;
6071
6072 cx.simulate_resize(size(px(300.), px(300.)));
6073
6074 cx.simulate_keystrokes("cmd-n cmd-n cmd-n");
6075 cx.update(|cx| cx.refresh());
6076
6077 let tab_bounds = cx.debug_bounds("TAB-2").unwrap();
6078 let new_tab_button_bounds = cx.debug_bounds("ICON-Plus").unwrap();
6079
6080 assert!(
6081 tab_bounds.intersects(&new_tab_button_bounds),
6082 "Tab should overlap with the new tab button, if this is failing check if there's been a redesign!"
6083 );
6084
6085 cx.simulate_event(MouseDownEvent {
6086 button: MouseButton::Right,
6087 position: new_tab_button_bounds.center(),
6088 modifiers: Modifiers::default(),
6089 click_count: 1,
6090 first_mouse: false,
6091 });
6092
6093 // regression test that the right click menu for tabs does not open.
6094 assert!(cx.debug_bounds("MENU_ITEM-Close").is_none());
6095
6096 let tab_bounds = cx.debug_bounds("TAB-1").unwrap();
6097 cx.simulate_event(MouseDownEvent {
6098 button: MouseButton::Right,
6099 position: tab_bounds.center(),
6100 modifiers: Modifiers::default(),
6101 click_count: 1,
6102 first_mouse: false,
6103 });
6104 assert!(cx.debug_bounds("MENU_ITEM-Close").is_some());
6105}
6106
6107#[gpui::test]
6108async fn test_cmd_k_left(cx: &mut TestAppContext) {
6109 let (_, client) = TestServer::start1(cx).await;
6110 let (workspace, cx) = client.build_test_workspace(cx).await;
6111
6112 cx.simulate_keystrokes("cmd-n");
6113 workspace.update(cx, |workspace, cx| {
6114 assert!(workspace.items(cx).collect::<Vec<_>>().len() == 1);
6115 });
6116 cx.simulate_keystrokes("cmd-k left");
6117 workspace.update(cx, |workspace, cx| {
6118 assert!(workspace.items(cx).collect::<Vec<_>>().len() == 2);
6119 });
6120 cx.simulate_keystrokes("cmd-k");
6121 // sleep for longer than the timeout in keyboard shortcut handling
6122 // to verify that it doesn't fire in this case.
6123 cx.executor().advance_clock(Duration::from_secs(2));
6124 cx.simulate_keystrokes("left");
6125 workspace.update(cx, |workspace, cx| {
6126 assert!(workspace.items(cx).collect::<Vec<_>>().len() == 2);
6127 });
6128}
6129
6130#[gpui::test]
6131async fn test_join_after_restart(cx1: &mut TestAppContext, cx2: &mut TestAppContext) {
6132 let (mut server, client) = TestServer::start1(cx1).await;
6133 let channel1 = server.make_public_channel("channel1", &client, cx1).await;
6134 let channel2 = server.make_public_channel("channel2", &client, cx1).await;
6135
6136 join_channel(channel1, &client, cx1).await.unwrap();
6137 drop(client);
6138
6139 let client2 = server.create_client(cx2, "user_a").await;
6140 join_channel(channel2, &client2, cx2).await.unwrap();
6141}
6142
6143#[gpui::test]
6144async fn test_preview_tabs(cx: &mut TestAppContext) {
6145 let (_server, client) = TestServer::start1(cx).await;
6146 let (workspace, cx) = client.build_test_workspace(cx).await;
6147 let project = workspace.update(cx, |workspace, _| workspace.project().clone());
6148
6149 let worktree_id = project.update(cx, |project, cx| {
6150 project.worktrees().next().unwrap().read(cx).id()
6151 });
6152
6153 let path_1 = ProjectPath {
6154 worktree_id,
6155 path: Path::new("1.txt").into(),
6156 };
6157 let path_2 = ProjectPath {
6158 worktree_id,
6159 path: Path::new("2.js").into(),
6160 };
6161 let path_3 = ProjectPath {
6162 worktree_id,
6163 path: Path::new("3.rs").into(),
6164 };
6165
6166 let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
6167
6168 let get_path = |pane: &Pane, idx: usize, cx: &AppContext| {
6169 pane.item_for_index(idx).unwrap().project_path(cx).unwrap()
6170 };
6171
6172 // Opening item 3 as a "permanent" tab
6173 workspace
6174 .update(cx, |workspace, cx| {
6175 workspace.open_path(path_3.clone(), None, false, cx)
6176 })
6177 .await
6178 .unwrap();
6179
6180 pane.update(cx, |pane, cx| {
6181 assert_eq!(pane.items_len(), 1);
6182 assert_eq!(get_path(pane, 0, cx), path_3.clone());
6183 assert_eq!(pane.preview_item_id(), None);
6184
6185 assert!(!pane.can_navigate_backward());
6186 assert!(!pane.can_navigate_forward());
6187 });
6188
6189 // Open item 1 as preview
6190 workspace
6191 .update(cx, |workspace, cx| {
6192 workspace.open_path_preview(path_1.clone(), None, true, true, cx)
6193 })
6194 .await
6195 .unwrap();
6196
6197 pane.update(cx, |pane, cx| {
6198 assert_eq!(pane.items_len(), 2);
6199 assert_eq!(get_path(pane, 0, cx), path_3.clone());
6200 assert_eq!(get_path(pane, 1, cx), path_1.clone());
6201 assert_eq!(
6202 pane.preview_item_id(),
6203 Some(pane.items().nth(1).unwrap().item_id())
6204 );
6205
6206 assert!(pane.can_navigate_backward());
6207 assert!(!pane.can_navigate_forward());
6208 });
6209
6210 // Open item 2 as preview
6211 workspace
6212 .update(cx, |workspace, cx| {
6213 workspace.open_path_preview(path_2.clone(), None, true, true, cx)
6214 })
6215 .await
6216 .unwrap();
6217
6218 pane.update(cx, |pane, cx| {
6219 assert_eq!(pane.items_len(), 2);
6220 assert_eq!(get_path(pane, 0, cx), path_3.clone());
6221 assert_eq!(get_path(pane, 1, cx), path_2.clone());
6222 assert_eq!(
6223 pane.preview_item_id(),
6224 Some(pane.items().nth(1).unwrap().item_id())
6225 );
6226
6227 assert!(pane.can_navigate_backward());
6228 assert!(!pane.can_navigate_forward());
6229 });
6230
6231 // Going back should show item 1 as preview
6232 workspace
6233 .update(cx, |workspace, cx| workspace.go_back(pane.downgrade(), cx))
6234 .await
6235 .unwrap();
6236
6237 pane.update(cx, |pane, cx| {
6238 assert_eq!(pane.items_len(), 2);
6239 assert_eq!(get_path(pane, 0, cx), path_3.clone());
6240 assert_eq!(get_path(pane, 1, cx), path_1.clone());
6241 assert_eq!(
6242 pane.preview_item_id(),
6243 Some(pane.items().nth(1).unwrap().item_id())
6244 );
6245
6246 assert!(pane.can_navigate_backward());
6247 assert!(pane.can_navigate_forward());
6248 });
6249
6250 // Closing item 1
6251 pane.update(cx, |pane, cx| {
6252 pane.close_item_by_id(
6253 pane.active_item().unwrap().item_id(),
6254 workspace::SaveIntent::Skip,
6255 cx,
6256 )
6257 })
6258 .await
6259 .unwrap();
6260
6261 pane.update(cx, |pane, cx| {
6262 assert_eq!(pane.items_len(), 1);
6263 assert_eq!(get_path(pane, 0, cx), path_3.clone());
6264 assert_eq!(pane.preview_item_id(), None);
6265
6266 assert!(pane.can_navigate_backward());
6267 assert!(!pane.can_navigate_forward());
6268 });
6269
6270 // Going back should show item 1 as preview
6271 workspace
6272 .update(cx, |workspace, cx| workspace.go_back(pane.downgrade(), cx))
6273 .await
6274 .unwrap();
6275
6276 pane.update(cx, |pane, cx| {
6277 assert_eq!(pane.items_len(), 2);
6278 assert_eq!(get_path(pane, 0, cx), path_3.clone());
6279 assert_eq!(get_path(pane, 1, cx), path_1.clone());
6280 assert_eq!(
6281 pane.preview_item_id(),
6282 Some(pane.items().nth(1).unwrap().item_id())
6283 );
6284
6285 assert!(pane.can_navigate_backward());
6286 assert!(pane.can_navigate_forward());
6287 });
6288
6289 // Close permanent tab
6290 pane.update(cx, |pane, cx| {
6291 let id = pane.items().nth(0).unwrap().item_id();
6292 pane.close_item_by_id(id, workspace::SaveIntent::Skip, cx)
6293 })
6294 .await
6295 .unwrap();
6296
6297 pane.update(cx, |pane, cx| {
6298 assert_eq!(pane.items_len(), 1);
6299 assert_eq!(get_path(pane, 0, cx), path_1.clone());
6300 assert_eq!(
6301 pane.preview_item_id(),
6302 Some(pane.items().nth(0).unwrap().item_id())
6303 );
6304
6305 assert!(pane.can_navigate_backward());
6306 assert!(pane.can_navigate_forward());
6307 });
6308
6309 // Split pane to the right
6310 pane.update(cx, |pane, cx| {
6311 pane.split(workspace::SplitDirection::Right, cx);
6312 });
6313
6314 let right_pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
6315
6316 pane.update(cx, |pane, cx| {
6317 assert_eq!(pane.items_len(), 1);
6318 assert_eq!(get_path(pane, 0, cx), path_1.clone());
6319 assert_eq!(
6320 pane.preview_item_id(),
6321 Some(pane.items().nth(0).unwrap().item_id())
6322 );
6323
6324 assert!(pane.can_navigate_backward());
6325 assert!(pane.can_navigate_forward());
6326 });
6327
6328 right_pane.update(cx, |pane, cx| {
6329 assert_eq!(pane.items_len(), 1);
6330 assert_eq!(get_path(pane, 0, cx), path_1.clone());
6331 assert_eq!(pane.preview_item_id(), None);
6332
6333 assert!(!pane.can_navigate_backward());
6334 assert!(!pane.can_navigate_forward());
6335 });
6336
6337 // Open item 2 as preview in right pane
6338 workspace
6339 .update(cx, |workspace, cx| {
6340 workspace.open_path_preview(path_2.clone(), None, true, true, cx)
6341 })
6342 .await
6343 .unwrap();
6344
6345 pane.update(cx, |pane, cx| {
6346 assert_eq!(pane.items_len(), 1);
6347 assert_eq!(get_path(pane, 0, cx), path_1.clone());
6348 assert_eq!(
6349 pane.preview_item_id(),
6350 Some(pane.items().nth(0).unwrap().item_id())
6351 );
6352
6353 assert!(pane.can_navigate_backward());
6354 assert!(pane.can_navigate_forward());
6355 });
6356
6357 right_pane.update(cx, |pane, cx| {
6358 assert_eq!(pane.items_len(), 2);
6359 assert_eq!(get_path(pane, 0, cx), path_1.clone());
6360 assert_eq!(get_path(pane, 1, cx), path_2.clone());
6361 assert_eq!(
6362 pane.preview_item_id(),
6363 Some(pane.items().nth(1).unwrap().item_id())
6364 );
6365
6366 assert!(pane.can_navigate_backward());
6367 assert!(!pane.can_navigate_forward());
6368 });
6369
6370 // Focus left pane
6371 workspace.update(cx, |workspace, cx| {
6372 workspace.activate_pane_in_direction(workspace::SplitDirection::Left, cx)
6373 });
6374
6375 // Open item 2 as preview in left pane
6376 workspace
6377 .update(cx, |workspace, cx| {
6378 workspace.open_path_preview(path_2.clone(), None, true, true, cx)
6379 })
6380 .await
6381 .unwrap();
6382
6383 pane.update(cx, |pane, cx| {
6384 assert_eq!(pane.items_len(), 1);
6385 assert_eq!(get_path(pane, 0, cx), path_2.clone());
6386 assert_eq!(
6387 pane.preview_item_id(),
6388 Some(pane.items().nth(0).unwrap().item_id())
6389 );
6390
6391 assert!(pane.can_navigate_backward());
6392 assert!(!pane.can_navigate_forward());
6393 });
6394
6395 right_pane.update(cx, |pane, cx| {
6396 assert_eq!(pane.items_len(), 2);
6397 assert_eq!(get_path(pane, 0, cx), path_1.clone());
6398 assert_eq!(get_path(pane, 1, cx), path_2.clone());
6399 assert_eq!(
6400 pane.preview_item_id(),
6401 Some(pane.items().nth(1).unwrap().item_id())
6402 );
6403
6404 assert!(pane.can_navigate_backward());
6405 assert!(!pane.can_navigate_forward());
6406 });
6407}