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("", None, cx))
2454 .unwrap();
2455
2456 let new_buffer_id = new_buffer_a.read_with(cx_a, |buffer, _| buffer.remote_id());
2457 let new_buffer_b = project_b
2458 .update(cx_b, |p, cx| p.open_buffer_by_id(new_buffer_id, cx))
2459 .await
2460 .unwrap();
2461
2462 new_buffer_b.read_with(cx_b, |buffer, _| {
2463 assert!(buffer.file().is_none());
2464 });
2465
2466 new_buffer_a.update(cx_a, |buffer, cx| {
2467 buffer.edit([(0..0, "ok")], None, cx);
2468 });
2469 project_a
2470 .update(cx_a, |project, cx| {
2471 project.save_buffer_as(new_buffer_a.clone(), "/a/file3.rs".into(), cx)
2472 })
2473 .await
2474 .unwrap();
2475
2476 executor.run_until_parked();
2477
2478 new_buffer_b.read_with(cx_b, |buffer_b, _| {
2479 assert_eq!(
2480 buffer_b.file().unwrap().path().as_ref(),
2481 Path::new("file3.rs")
2482 );
2483
2484 new_buffer_a.read_with(cx_a, |buffer_a, _| {
2485 assert_eq!(buffer_b.saved_mtime(), buffer_a.saved_mtime());
2486 assert_eq!(buffer_b.saved_version(), buffer_a.saved_version());
2487 });
2488 });
2489}
2490
2491#[gpui::test(iterations = 10)]
2492async fn test_git_diff_base_change(
2493 executor: BackgroundExecutor,
2494 cx_a: &mut TestAppContext,
2495 cx_b: &mut TestAppContext,
2496) {
2497 let mut server = TestServer::start(executor.clone()).await;
2498 let client_a = server.create_client(cx_a, "user_a").await;
2499 let client_b = server.create_client(cx_b, "user_b").await;
2500 server
2501 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
2502 .await;
2503 let active_call_a = cx_a.read(ActiveCall::global);
2504
2505 client_a
2506 .fs()
2507 .insert_tree(
2508 "/dir",
2509 json!({
2510 ".git": {},
2511 "sub": {
2512 ".git": {},
2513 "b.txt": "
2514 one
2515 two
2516 three
2517 ".unindent(),
2518 },
2519 "a.txt": "
2520 one
2521 two
2522 three
2523 ".unindent(),
2524 }),
2525 )
2526 .await;
2527
2528 let (project_local, worktree_id) = client_a.build_local_project("/dir", cx_a).await;
2529 let project_id = active_call_a
2530 .update(cx_a, |call, cx| {
2531 call.share_project(project_local.clone(), cx)
2532 })
2533 .await
2534 .unwrap();
2535
2536 let project_remote = client_b.build_remote_project(project_id, cx_b).await;
2537
2538 let diff_base = "
2539 one
2540 three
2541 "
2542 .unindent();
2543
2544 let new_diff_base = "
2545 one
2546 two
2547 "
2548 .unindent();
2549
2550 client_a.fs().set_index_for_repo(
2551 Path::new("/dir/.git"),
2552 &[(Path::new("a.txt"), diff_base.clone())],
2553 );
2554
2555 // Create the buffer
2556 let buffer_local_a = project_local
2557 .update(cx_a, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
2558 .await
2559 .unwrap();
2560
2561 // Wait for it to catch up to the new diff
2562 executor.run_until_parked();
2563
2564 // Smoke test diffing
2565
2566 buffer_local_a.read_with(cx_a, |buffer, _| {
2567 assert_eq!(buffer.diff_base(), Some(diff_base.as_ref()));
2568 git::diff::assert_hunks(
2569 buffer.snapshot().git_diff_hunks_in_row_range(0..4),
2570 &buffer,
2571 &diff_base,
2572 &[(1..2, "", "two\n")],
2573 );
2574 });
2575
2576 // Create remote buffer
2577 let buffer_remote_a = project_remote
2578 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
2579 .await
2580 .unwrap();
2581
2582 // Wait remote buffer to catch up to the new diff
2583 executor.run_until_parked();
2584
2585 // Smoke test diffing
2586
2587 buffer_remote_a.read_with(cx_b, |buffer, _| {
2588 assert_eq!(buffer.diff_base(), Some(diff_base.as_ref()));
2589 git::diff::assert_hunks(
2590 buffer.snapshot().git_diff_hunks_in_row_range(0..4),
2591 &buffer,
2592 &diff_base,
2593 &[(1..2, "", "two\n")],
2594 );
2595 });
2596
2597 client_a.fs().set_index_for_repo(
2598 Path::new("/dir/.git"),
2599 &[(Path::new("a.txt"), new_diff_base.clone())],
2600 );
2601
2602 // Wait for buffer_local_a to receive it
2603 executor.run_until_parked();
2604
2605 // Smoke test new diffing
2606
2607 buffer_local_a.read_with(cx_a, |buffer, _| {
2608 assert_eq!(buffer.diff_base(), Some(new_diff_base.as_ref()));
2609
2610 git::diff::assert_hunks(
2611 buffer.snapshot().git_diff_hunks_in_row_range(0..4),
2612 &buffer,
2613 &diff_base,
2614 &[(2..3, "", "three\n")],
2615 );
2616 });
2617
2618 // Smoke test B
2619
2620 buffer_remote_a.read_with(cx_b, |buffer, _| {
2621 assert_eq!(buffer.diff_base(), Some(new_diff_base.as_ref()));
2622 git::diff::assert_hunks(
2623 buffer.snapshot().git_diff_hunks_in_row_range(0..4),
2624 &buffer,
2625 &diff_base,
2626 &[(2..3, "", "three\n")],
2627 );
2628 });
2629
2630 //Nested git dir
2631
2632 let diff_base = "
2633 one
2634 three
2635 "
2636 .unindent();
2637
2638 let new_diff_base = "
2639 one
2640 two
2641 "
2642 .unindent();
2643
2644 client_a.fs().set_index_for_repo(
2645 Path::new("/dir/sub/.git"),
2646 &[(Path::new("b.txt"), diff_base.clone())],
2647 );
2648
2649 // Create the buffer
2650 let buffer_local_b = project_local
2651 .update(cx_a, |p, cx| p.open_buffer((worktree_id, "sub/b.txt"), cx))
2652 .await
2653 .unwrap();
2654
2655 // Wait for it to catch up to the new diff
2656 executor.run_until_parked();
2657
2658 // Smoke test diffing
2659
2660 buffer_local_b.read_with(cx_a, |buffer, _| {
2661 assert_eq!(buffer.diff_base(), Some(diff_base.as_ref()));
2662 git::diff::assert_hunks(
2663 buffer.snapshot().git_diff_hunks_in_row_range(0..4),
2664 &buffer,
2665 &diff_base,
2666 &[(1..2, "", "two\n")],
2667 );
2668 });
2669
2670 // Create remote buffer
2671 let buffer_remote_b = project_remote
2672 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "sub/b.txt"), cx))
2673 .await
2674 .unwrap();
2675
2676 // Wait remote buffer to catch up to the new diff
2677 executor.run_until_parked();
2678
2679 // Smoke test diffing
2680
2681 buffer_remote_b.read_with(cx_b, |buffer, _| {
2682 assert_eq!(buffer.diff_base(), Some(diff_base.as_ref()));
2683 git::diff::assert_hunks(
2684 buffer.snapshot().git_diff_hunks_in_row_range(0..4),
2685 &buffer,
2686 &diff_base,
2687 &[(1..2, "", "two\n")],
2688 );
2689 });
2690
2691 client_a.fs().set_index_for_repo(
2692 Path::new("/dir/sub/.git"),
2693 &[(Path::new("b.txt"), new_diff_base.clone())],
2694 );
2695
2696 // Wait for buffer_local_b to receive it
2697 executor.run_until_parked();
2698
2699 // Smoke test new diffing
2700
2701 buffer_local_b.read_with(cx_a, |buffer, _| {
2702 assert_eq!(buffer.diff_base(), Some(new_diff_base.as_ref()));
2703 println!("{:?}", buffer.as_rope().to_string());
2704 println!("{:?}", buffer.diff_base());
2705 println!(
2706 "{:?}",
2707 buffer
2708 .snapshot()
2709 .git_diff_hunks_in_row_range(0..4)
2710 .collect::<Vec<_>>()
2711 );
2712
2713 git::diff::assert_hunks(
2714 buffer.snapshot().git_diff_hunks_in_row_range(0..4),
2715 &buffer,
2716 &diff_base,
2717 &[(2..3, "", "three\n")],
2718 );
2719 });
2720
2721 // Smoke test B
2722
2723 buffer_remote_b.read_with(cx_b, |buffer, _| {
2724 assert_eq!(buffer.diff_base(), Some(new_diff_base.as_ref()));
2725 git::diff::assert_hunks(
2726 buffer.snapshot().git_diff_hunks_in_row_range(0..4),
2727 &buffer,
2728 &diff_base,
2729 &[(2..3, "", "three\n")],
2730 );
2731 });
2732}
2733
2734#[gpui::test]
2735async fn test_git_branch_name(
2736 executor: BackgroundExecutor,
2737 cx_a: &mut TestAppContext,
2738 cx_b: &mut TestAppContext,
2739 cx_c: &mut TestAppContext,
2740) {
2741 let mut server = TestServer::start(executor.clone()).await;
2742 let client_a = server.create_client(cx_a, "user_a").await;
2743 let client_b = server.create_client(cx_b, "user_b").await;
2744 let client_c = server.create_client(cx_c, "user_c").await;
2745 server
2746 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b), (&client_c, cx_c)])
2747 .await;
2748 let active_call_a = cx_a.read(ActiveCall::global);
2749
2750 client_a
2751 .fs()
2752 .insert_tree(
2753 "/dir",
2754 json!({
2755 ".git": {},
2756 }),
2757 )
2758 .await;
2759
2760 let (project_local, _worktree_id) = client_a.build_local_project("/dir", cx_a).await;
2761 let project_id = active_call_a
2762 .update(cx_a, |call, cx| {
2763 call.share_project(project_local.clone(), cx)
2764 })
2765 .await
2766 .unwrap();
2767
2768 let project_remote = client_b.build_remote_project(project_id, cx_b).await;
2769 client_a
2770 .fs()
2771 .set_branch_name(Path::new("/dir/.git"), Some("branch-1"));
2772
2773 // Wait for it to catch up to the new branch
2774 executor.run_until_parked();
2775
2776 #[track_caller]
2777 fn assert_branch(branch_name: Option<impl Into<String>>, project: &Project, cx: &AppContext) {
2778 let branch_name = branch_name.map(Into::into);
2779 let worktrees = project.visible_worktrees(cx).collect::<Vec<_>>();
2780 assert_eq!(worktrees.len(), 1);
2781 let worktree = worktrees[0].clone();
2782 let root_entry = worktree.read(cx).snapshot().root_git_entry().unwrap();
2783 assert_eq!(root_entry.branch(), branch_name.map(Into::into));
2784 }
2785
2786 // Smoke test branch reading
2787
2788 project_local.read_with(cx_a, |project, cx| {
2789 assert_branch(Some("branch-1"), project, cx)
2790 });
2791
2792 project_remote.read_with(cx_b, |project, cx| {
2793 assert_branch(Some("branch-1"), project, cx)
2794 });
2795
2796 client_a
2797 .fs()
2798 .set_branch_name(Path::new("/dir/.git"), Some("branch-2"));
2799
2800 // Wait for buffer_local_a to receive it
2801 executor.run_until_parked();
2802
2803 // Smoke test branch reading
2804
2805 project_local.read_with(cx_a, |project, cx| {
2806 assert_branch(Some("branch-2"), project, cx)
2807 });
2808
2809 project_remote.read_with(cx_b, |project, cx| {
2810 assert_branch(Some("branch-2"), project, cx)
2811 });
2812
2813 let project_remote_c = client_c.build_remote_project(project_id, cx_c).await;
2814 executor.run_until_parked();
2815
2816 project_remote_c.read_with(cx_c, |project, cx| {
2817 assert_branch(Some("branch-2"), project, cx)
2818 });
2819}
2820
2821#[gpui::test]
2822async fn test_git_status_sync(
2823 executor: BackgroundExecutor,
2824 cx_a: &mut TestAppContext,
2825 cx_b: &mut TestAppContext,
2826 cx_c: &mut TestAppContext,
2827) {
2828 let mut server = TestServer::start(executor.clone()).await;
2829 let client_a = server.create_client(cx_a, "user_a").await;
2830 let client_b = server.create_client(cx_b, "user_b").await;
2831 let client_c = server.create_client(cx_c, "user_c").await;
2832 server
2833 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b), (&client_c, cx_c)])
2834 .await;
2835 let active_call_a = cx_a.read(ActiveCall::global);
2836
2837 client_a
2838 .fs()
2839 .insert_tree(
2840 "/dir",
2841 json!({
2842 ".git": {},
2843 "a.txt": "a",
2844 "b.txt": "b",
2845 }),
2846 )
2847 .await;
2848
2849 const A_TXT: &str = "a.txt";
2850 const B_TXT: &str = "b.txt";
2851
2852 client_a.fs().set_status_for_repo_via_git_operation(
2853 Path::new("/dir/.git"),
2854 &[
2855 (&Path::new(A_TXT), GitFileStatus::Added),
2856 (&Path::new(B_TXT), GitFileStatus::Added),
2857 ],
2858 );
2859
2860 let (project_local, _worktree_id) = client_a.build_local_project("/dir", cx_a).await;
2861 let project_id = active_call_a
2862 .update(cx_a, |call, cx| {
2863 call.share_project(project_local.clone(), cx)
2864 })
2865 .await
2866 .unwrap();
2867
2868 let project_remote = client_b.build_remote_project(project_id, cx_b).await;
2869
2870 // Wait for it to catch up to the new status
2871 executor.run_until_parked();
2872
2873 #[track_caller]
2874 fn assert_status(
2875 file: &impl AsRef<Path>,
2876 status: Option<GitFileStatus>,
2877 project: &Project,
2878 cx: &AppContext,
2879 ) {
2880 let file = file.as_ref();
2881 let worktrees = project.visible_worktrees(cx).collect::<Vec<_>>();
2882 assert_eq!(worktrees.len(), 1);
2883 let worktree = worktrees[0].clone();
2884 let snapshot = worktree.read(cx).snapshot();
2885 assert_eq!(snapshot.status_for_file(file), status);
2886 }
2887
2888 // Smoke test status reading
2889
2890 project_local.read_with(cx_a, |project, cx| {
2891 assert_status(&Path::new(A_TXT), Some(GitFileStatus::Added), project, cx);
2892 assert_status(&Path::new(B_TXT), Some(GitFileStatus::Added), project, cx);
2893 });
2894
2895 project_remote.read_with(cx_b, |project, cx| {
2896 assert_status(&Path::new(A_TXT), Some(GitFileStatus::Added), project, cx);
2897 assert_status(&Path::new(B_TXT), Some(GitFileStatus::Added), project, cx);
2898 });
2899
2900 client_a.fs().set_status_for_repo_via_working_copy_change(
2901 Path::new("/dir/.git"),
2902 &[
2903 (&Path::new(A_TXT), GitFileStatus::Modified),
2904 (&Path::new(B_TXT), GitFileStatus::Modified),
2905 ],
2906 );
2907
2908 // Wait for buffer_local_a to receive it
2909 executor.run_until_parked();
2910
2911 // Smoke test status reading
2912
2913 project_local.read_with(cx_a, |project, cx| {
2914 assert_status(
2915 &Path::new(A_TXT),
2916 Some(GitFileStatus::Modified),
2917 project,
2918 cx,
2919 );
2920 assert_status(
2921 &Path::new(B_TXT),
2922 Some(GitFileStatus::Modified),
2923 project,
2924 cx,
2925 );
2926 });
2927
2928 project_remote.read_with(cx_b, |project, cx| {
2929 assert_status(
2930 &Path::new(A_TXT),
2931 Some(GitFileStatus::Modified),
2932 project,
2933 cx,
2934 );
2935 assert_status(
2936 &Path::new(B_TXT),
2937 Some(GitFileStatus::Modified),
2938 project,
2939 cx,
2940 );
2941 });
2942
2943 // And synchronization while joining
2944 let project_remote_c = client_c.build_remote_project(project_id, cx_c).await;
2945 executor.run_until_parked();
2946
2947 project_remote_c.read_with(cx_c, |project, cx| {
2948 assert_status(
2949 &Path::new(A_TXT),
2950 Some(GitFileStatus::Modified),
2951 project,
2952 cx,
2953 );
2954 assert_status(
2955 &Path::new(B_TXT),
2956 Some(GitFileStatus::Modified),
2957 project,
2958 cx,
2959 );
2960 });
2961}
2962
2963#[gpui::test(iterations = 10)]
2964async fn test_fs_operations(
2965 executor: BackgroundExecutor,
2966 cx_a: &mut TestAppContext,
2967 cx_b: &mut TestAppContext,
2968) {
2969 let mut server = TestServer::start(executor.clone()).await;
2970 let client_a = server.create_client(cx_a, "user_a").await;
2971 let client_b = server.create_client(cx_b, "user_b").await;
2972 server
2973 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
2974 .await;
2975 let active_call_a = cx_a.read(ActiveCall::global);
2976
2977 client_a
2978 .fs()
2979 .insert_tree(
2980 "/dir",
2981 json!({
2982 "a.txt": "a-contents",
2983 "b.txt": "b-contents",
2984 }),
2985 )
2986 .await;
2987 let (project_a, worktree_id) = client_a.build_local_project("/dir", cx_a).await;
2988 let project_id = active_call_a
2989 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
2990 .await
2991 .unwrap();
2992 let project_b = client_b.build_remote_project(project_id, cx_b).await;
2993
2994 let worktree_a = project_a.read_with(cx_a, |project, _| project.worktrees().next().unwrap());
2995
2996 let worktree_b = project_b.read_with(cx_b, |project, _| project.worktrees().next().unwrap());
2997
2998 let entry = project_b
2999 .update(cx_b, |project, cx| {
3000 project.create_entry((worktree_id, "c.txt"), false, cx)
3001 })
3002 .await
3003 .unwrap()
3004 .unwrap();
3005
3006 worktree_a.read_with(cx_a, |worktree, _| {
3007 assert_eq!(
3008 worktree
3009 .paths()
3010 .map(|p| p.to_string_lossy())
3011 .collect::<Vec<_>>(),
3012 ["a.txt", "b.txt", "c.txt"]
3013 );
3014 });
3015
3016 worktree_b.read_with(cx_b, |worktree, _| {
3017 assert_eq!(
3018 worktree
3019 .paths()
3020 .map(|p| p.to_string_lossy())
3021 .collect::<Vec<_>>(),
3022 ["a.txt", "b.txt", "c.txt"]
3023 );
3024 });
3025
3026 project_b
3027 .update(cx_b, |project, cx| {
3028 project.rename_entry(entry.id, Path::new("d.txt"), cx)
3029 })
3030 .await
3031 .unwrap()
3032 .unwrap();
3033
3034 worktree_a.read_with(cx_a, |worktree, _| {
3035 assert_eq!(
3036 worktree
3037 .paths()
3038 .map(|p| p.to_string_lossy())
3039 .collect::<Vec<_>>(),
3040 ["a.txt", "b.txt", "d.txt"]
3041 );
3042 });
3043
3044 worktree_b.read_with(cx_b, |worktree, _| {
3045 assert_eq!(
3046 worktree
3047 .paths()
3048 .map(|p| p.to_string_lossy())
3049 .collect::<Vec<_>>(),
3050 ["a.txt", "b.txt", "d.txt"]
3051 );
3052 });
3053
3054 let dir_entry = project_b
3055 .update(cx_b, |project, cx| {
3056 project.create_entry((worktree_id, "DIR"), true, cx)
3057 })
3058 .await
3059 .unwrap()
3060 .unwrap();
3061
3062 worktree_a.read_with(cx_a, |worktree, _| {
3063 assert_eq!(
3064 worktree
3065 .paths()
3066 .map(|p| p.to_string_lossy())
3067 .collect::<Vec<_>>(),
3068 ["DIR", "a.txt", "b.txt", "d.txt"]
3069 );
3070 });
3071
3072 worktree_b.read_with(cx_b, |worktree, _| {
3073 assert_eq!(
3074 worktree
3075 .paths()
3076 .map(|p| p.to_string_lossy())
3077 .collect::<Vec<_>>(),
3078 ["DIR", "a.txt", "b.txt", "d.txt"]
3079 );
3080 });
3081
3082 project_b
3083 .update(cx_b, |project, cx| {
3084 project.create_entry((worktree_id, "DIR/e.txt"), false, cx)
3085 })
3086 .await
3087 .unwrap()
3088 .unwrap();
3089 project_b
3090 .update(cx_b, |project, cx| {
3091 project.create_entry((worktree_id, "DIR/SUBDIR"), true, cx)
3092 })
3093 .await
3094 .unwrap()
3095 .unwrap();
3096 project_b
3097 .update(cx_b, |project, cx| {
3098 project.create_entry((worktree_id, "DIR/SUBDIR/f.txt"), false, cx)
3099 })
3100 .await
3101 .unwrap()
3102 .unwrap();
3103
3104 worktree_a.read_with(cx_a, |worktree, _| {
3105 assert_eq!(
3106 worktree
3107 .paths()
3108 .map(|p| p.to_string_lossy())
3109 .collect::<Vec<_>>(),
3110 [
3111 "DIR",
3112 "DIR/SUBDIR",
3113 "DIR/SUBDIR/f.txt",
3114 "DIR/e.txt",
3115 "a.txt",
3116 "b.txt",
3117 "d.txt"
3118 ]
3119 );
3120 });
3121
3122 worktree_b.read_with(cx_b, |worktree, _| {
3123 assert_eq!(
3124 worktree
3125 .paths()
3126 .map(|p| p.to_string_lossy())
3127 .collect::<Vec<_>>(),
3128 [
3129 "DIR",
3130 "DIR/SUBDIR",
3131 "DIR/SUBDIR/f.txt",
3132 "DIR/e.txt",
3133 "a.txt",
3134 "b.txt",
3135 "d.txt"
3136 ]
3137 );
3138 });
3139
3140 project_b
3141 .update(cx_b, |project, cx| {
3142 project.copy_entry(entry.id, Path::new("f.txt"), cx)
3143 })
3144 .await
3145 .unwrap()
3146 .unwrap();
3147
3148 worktree_a.read_with(cx_a, |worktree, _| {
3149 assert_eq!(
3150 worktree
3151 .paths()
3152 .map(|p| p.to_string_lossy())
3153 .collect::<Vec<_>>(),
3154 [
3155 "DIR",
3156 "DIR/SUBDIR",
3157 "DIR/SUBDIR/f.txt",
3158 "DIR/e.txt",
3159 "a.txt",
3160 "b.txt",
3161 "d.txt",
3162 "f.txt"
3163 ]
3164 );
3165 });
3166
3167 worktree_b.read_with(cx_b, |worktree, _| {
3168 assert_eq!(
3169 worktree
3170 .paths()
3171 .map(|p| p.to_string_lossy())
3172 .collect::<Vec<_>>(),
3173 [
3174 "DIR",
3175 "DIR/SUBDIR",
3176 "DIR/SUBDIR/f.txt",
3177 "DIR/e.txt",
3178 "a.txt",
3179 "b.txt",
3180 "d.txt",
3181 "f.txt"
3182 ]
3183 );
3184 });
3185
3186 project_b
3187 .update(cx_b, |project, cx| {
3188 project.delete_entry(dir_entry.id, cx).unwrap()
3189 })
3190 .await
3191 .unwrap();
3192 executor.run_until_parked();
3193
3194 worktree_a.read_with(cx_a, |worktree, _| {
3195 assert_eq!(
3196 worktree
3197 .paths()
3198 .map(|p| p.to_string_lossy())
3199 .collect::<Vec<_>>(),
3200 ["a.txt", "b.txt", "d.txt", "f.txt"]
3201 );
3202 });
3203
3204 worktree_b.read_with(cx_b, |worktree, _| {
3205 assert_eq!(
3206 worktree
3207 .paths()
3208 .map(|p| p.to_string_lossy())
3209 .collect::<Vec<_>>(),
3210 ["a.txt", "b.txt", "d.txt", "f.txt"]
3211 );
3212 });
3213
3214 project_b
3215 .update(cx_b, |project, cx| {
3216 project.delete_entry(entry.id, cx).unwrap()
3217 })
3218 .await
3219 .unwrap();
3220
3221 worktree_a.read_with(cx_a, |worktree, _| {
3222 assert_eq!(
3223 worktree
3224 .paths()
3225 .map(|p| p.to_string_lossy())
3226 .collect::<Vec<_>>(),
3227 ["a.txt", "b.txt", "f.txt"]
3228 );
3229 });
3230
3231 worktree_b.read_with(cx_b, |worktree, _| {
3232 assert_eq!(
3233 worktree
3234 .paths()
3235 .map(|p| p.to_string_lossy())
3236 .collect::<Vec<_>>(),
3237 ["a.txt", "b.txt", "f.txt"]
3238 );
3239 });
3240}
3241
3242#[gpui::test(iterations = 10)]
3243async fn test_local_settings(
3244 executor: BackgroundExecutor,
3245 cx_a: &mut TestAppContext,
3246 cx_b: &mut TestAppContext,
3247) {
3248 let mut server = TestServer::start(executor.clone()).await;
3249 let client_a = server.create_client(cx_a, "user_a").await;
3250 let client_b = server.create_client(cx_b, "user_b").await;
3251 server
3252 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
3253 .await;
3254 let active_call_a = cx_a.read(ActiveCall::global);
3255
3256 // As client A, open a project that contains some local settings files
3257 client_a
3258 .fs()
3259 .insert_tree(
3260 "/dir",
3261 json!({
3262 ".zed": {
3263 "settings.json": r#"{ "tab_size": 2 }"#
3264 },
3265 "a": {
3266 ".zed": {
3267 "settings.json": r#"{ "tab_size": 8 }"#
3268 },
3269 "a.txt": "a-contents",
3270 },
3271 "b": {
3272 "b.txt": "b-contents",
3273 }
3274 }),
3275 )
3276 .await;
3277 let (project_a, _) = client_a.build_local_project("/dir", cx_a).await;
3278 executor.run_until_parked();
3279 let project_id = active_call_a
3280 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
3281 .await
3282 .unwrap();
3283 executor.run_until_parked();
3284
3285 // As client B, join that project and observe the local settings.
3286 let project_b = client_b.build_remote_project(project_id, cx_b).await;
3287
3288 let worktree_b = project_b.read_with(cx_b, |project, _| project.worktrees().next().unwrap());
3289 executor.run_until_parked();
3290 cx_b.read(|cx| {
3291 let store = cx.global::<SettingsStore>();
3292 assert_eq!(
3293 store
3294 .local_settings(worktree_b.read(cx).id().to_usize())
3295 .collect::<Vec<_>>(),
3296 &[
3297 (Path::new("").into(), r#"{"tab_size":2}"#.to_string()),
3298 (Path::new("a").into(), r#"{"tab_size":8}"#.to_string()),
3299 ]
3300 )
3301 });
3302
3303 // As client A, update a settings file. As Client B, see the changed settings.
3304 client_a
3305 .fs()
3306 .insert_file("/dir/.zed/settings.json", r#"{}"#.into())
3307 .await;
3308 executor.run_until_parked();
3309 cx_b.read(|cx| {
3310 let store = cx.global::<SettingsStore>();
3311 assert_eq!(
3312 store
3313 .local_settings(worktree_b.read(cx).id().to_usize())
3314 .collect::<Vec<_>>(),
3315 &[
3316 (Path::new("").into(), r#"{}"#.to_string()),
3317 (Path::new("a").into(), r#"{"tab_size":8}"#.to_string()),
3318 ]
3319 )
3320 });
3321
3322 // As client A, create and remove some settings files. As client B, see the changed settings.
3323 client_a
3324 .fs()
3325 .remove_file("/dir/.zed/settings.json".as_ref(), Default::default())
3326 .await
3327 .unwrap();
3328 client_a
3329 .fs()
3330 .create_dir("/dir/b/.zed".as_ref())
3331 .await
3332 .unwrap();
3333 client_a
3334 .fs()
3335 .insert_file("/dir/b/.zed/settings.json", r#"{"tab_size": 4}"#.into())
3336 .await;
3337 executor.run_until_parked();
3338 cx_b.read(|cx| {
3339 let store = cx.global::<SettingsStore>();
3340 assert_eq!(
3341 store
3342 .local_settings(worktree_b.read(cx).id().to_usize())
3343 .collect::<Vec<_>>(),
3344 &[
3345 (Path::new("a").into(), r#"{"tab_size":8}"#.to_string()),
3346 (Path::new("b").into(), r#"{"tab_size":4}"#.to_string()),
3347 ]
3348 )
3349 });
3350
3351 // As client B, disconnect.
3352 server.forbid_connections();
3353 server.disconnect_client(client_b.peer_id().unwrap());
3354
3355 // As client A, change and remove settings files while client B is disconnected.
3356 client_a
3357 .fs()
3358 .insert_file("/dir/a/.zed/settings.json", r#"{"hard_tabs":true}"#.into())
3359 .await;
3360 client_a
3361 .fs()
3362 .remove_file("/dir/b/.zed/settings.json".as_ref(), Default::default())
3363 .await
3364 .unwrap();
3365 executor.run_until_parked();
3366
3367 // As client B, reconnect and see the changed settings.
3368 server.allow_connections();
3369 executor.advance_clock(RECEIVE_TIMEOUT);
3370 cx_b.read(|cx| {
3371 let store = cx.global::<SettingsStore>();
3372 assert_eq!(
3373 store
3374 .local_settings(worktree_b.read(cx).id().to_usize())
3375 .collect::<Vec<_>>(),
3376 &[(Path::new("a").into(), r#"{"hard_tabs":true}"#.to_string()),]
3377 )
3378 });
3379}
3380
3381#[gpui::test(iterations = 10)]
3382async fn test_buffer_conflict_after_save(
3383 executor: BackgroundExecutor,
3384 cx_a: &mut TestAppContext,
3385 cx_b: &mut TestAppContext,
3386) {
3387 let mut server = TestServer::start(executor.clone()).await;
3388 let client_a = server.create_client(cx_a, "user_a").await;
3389 let client_b = server.create_client(cx_b, "user_b").await;
3390 server
3391 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
3392 .await;
3393 let active_call_a = cx_a.read(ActiveCall::global);
3394
3395 client_a
3396 .fs()
3397 .insert_tree(
3398 "/dir",
3399 json!({
3400 "a.txt": "a-contents",
3401 }),
3402 )
3403 .await;
3404 let (project_a, worktree_id) = client_a.build_local_project("/dir", cx_a).await;
3405 let project_id = active_call_a
3406 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
3407 .await
3408 .unwrap();
3409 let project_b = client_b.build_remote_project(project_id, cx_b).await;
3410
3411 // Open a buffer as client B
3412 let buffer_b = project_b
3413 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
3414 .await
3415 .unwrap();
3416
3417 buffer_b.update(cx_b, |buf, cx| buf.edit([(0..0, "world ")], None, cx));
3418
3419 buffer_b.read_with(cx_b, |buf, _| {
3420 assert!(buf.is_dirty());
3421 assert!(!buf.has_conflict());
3422 });
3423
3424 project_b
3425 .update(cx_b, |project, cx| {
3426 project.save_buffer(buffer_b.clone(), cx)
3427 })
3428 .await
3429 .unwrap();
3430
3431 buffer_b.read_with(cx_b, |buffer_b, _| assert!(!buffer_b.is_dirty()));
3432
3433 buffer_b.read_with(cx_b, |buf, _| {
3434 assert!(!buf.has_conflict());
3435 });
3436
3437 buffer_b.update(cx_b, |buf, cx| buf.edit([(0..0, "hello ")], None, cx));
3438
3439 buffer_b.read_with(cx_b, |buf, _| {
3440 assert!(buf.is_dirty());
3441 assert!(!buf.has_conflict());
3442 });
3443}
3444
3445#[gpui::test(iterations = 10)]
3446async fn test_buffer_reloading(
3447 executor: BackgroundExecutor,
3448 cx_a: &mut TestAppContext,
3449 cx_b: &mut TestAppContext,
3450) {
3451 let mut server = TestServer::start(executor.clone()).await;
3452 let client_a = server.create_client(cx_a, "user_a").await;
3453 let client_b = server.create_client(cx_b, "user_b").await;
3454 server
3455 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
3456 .await;
3457 let active_call_a = cx_a.read(ActiveCall::global);
3458
3459 client_a
3460 .fs()
3461 .insert_tree(
3462 "/dir",
3463 json!({
3464 "a.txt": "a\nb\nc",
3465 }),
3466 )
3467 .await;
3468 let (project_a, worktree_id) = client_a.build_local_project("/dir", cx_a).await;
3469 let project_id = active_call_a
3470 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
3471 .await
3472 .unwrap();
3473 let project_b = client_b.build_remote_project(project_id, cx_b).await;
3474
3475 // Open a buffer as client B
3476 let buffer_b = project_b
3477 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
3478 .await
3479 .unwrap();
3480
3481 buffer_b.read_with(cx_b, |buf, _| {
3482 assert!(!buf.is_dirty());
3483 assert!(!buf.has_conflict());
3484 assert_eq!(buf.line_ending(), LineEnding::Unix);
3485 });
3486
3487 let new_contents = Rope::from("d\ne\nf");
3488 client_a
3489 .fs()
3490 .save("/dir/a.txt".as_ref(), &new_contents, LineEnding::Windows)
3491 .await
3492 .unwrap();
3493
3494 executor.run_until_parked();
3495
3496 buffer_b.read_with(cx_b, |buf, _| {
3497 assert_eq!(buf.text(), new_contents.to_string());
3498 assert!(!buf.is_dirty());
3499 assert!(!buf.has_conflict());
3500 assert_eq!(buf.line_ending(), LineEnding::Windows);
3501 });
3502}
3503
3504#[gpui::test(iterations = 10)]
3505async fn test_editing_while_guest_opens_buffer(
3506 executor: BackgroundExecutor,
3507 cx_a: &mut TestAppContext,
3508 cx_b: &mut TestAppContext,
3509) {
3510 let mut server = TestServer::start(executor.clone()).await;
3511 let client_a = server.create_client(cx_a, "user_a").await;
3512 let client_b = server.create_client(cx_b, "user_b").await;
3513 server
3514 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
3515 .await;
3516 let active_call_a = cx_a.read(ActiveCall::global);
3517
3518 client_a
3519 .fs()
3520 .insert_tree("/dir", json!({ "a.txt": "a-contents" }))
3521 .await;
3522 let (project_a, worktree_id) = client_a.build_local_project("/dir", cx_a).await;
3523 let project_id = active_call_a
3524 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
3525 .await
3526 .unwrap();
3527 let project_b = client_b.build_remote_project(project_id, cx_b).await;
3528
3529 // Open a buffer as client A
3530 let buffer_a = project_a
3531 .update(cx_a, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
3532 .await
3533 .unwrap();
3534
3535 // Start opening the same buffer as client B
3536 let open_buffer = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx));
3537 let buffer_b = cx_b.executor().spawn(open_buffer);
3538
3539 // Edit the buffer as client A while client B is still opening it.
3540 cx_b.executor().simulate_random_delay().await;
3541 buffer_a.update(cx_a, |buf, cx| buf.edit([(0..0, "X")], None, cx));
3542 cx_b.executor().simulate_random_delay().await;
3543 buffer_a.update(cx_a, |buf, cx| buf.edit([(1..1, "Y")], None, cx));
3544
3545 let text = buffer_a.read_with(cx_a, |buf, _| buf.text());
3546 let buffer_b = buffer_b.await.unwrap();
3547 executor.run_until_parked();
3548
3549 buffer_b.read_with(cx_b, |buf, _| assert_eq!(buf.text(), text));
3550}
3551
3552#[gpui::test(iterations = 10)]
3553async fn test_leaving_worktree_while_opening_buffer(
3554 executor: BackgroundExecutor,
3555 cx_a: &mut TestAppContext,
3556 cx_b: &mut TestAppContext,
3557) {
3558 let mut server = TestServer::start(executor.clone()).await;
3559 let client_a = server.create_client(cx_a, "user_a").await;
3560 let client_b = server.create_client(cx_b, "user_b").await;
3561 server
3562 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
3563 .await;
3564 let active_call_a = cx_a.read(ActiveCall::global);
3565
3566 client_a
3567 .fs()
3568 .insert_tree("/dir", json!({ "a.txt": "a-contents" }))
3569 .await;
3570 let (project_a, worktree_id) = client_a.build_local_project("/dir", cx_a).await;
3571 let project_id = active_call_a
3572 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
3573 .await
3574 .unwrap();
3575 let project_b = client_b.build_remote_project(project_id, cx_b).await;
3576
3577 // See that a guest has joined as client A.
3578 executor.run_until_parked();
3579
3580 project_a.read_with(cx_a, |p, _| assert_eq!(p.collaborators().len(), 1));
3581
3582 // Begin opening a buffer as client B, but leave the project before the open completes.
3583 let open_buffer = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx));
3584 let buffer_b = cx_b.executor().spawn(open_buffer);
3585 cx_b.update(|_| drop(project_b));
3586 drop(buffer_b);
3587
3588 // See that the guest has left.
3589 executor.run_until_parked();
3590
3591 project_a.read_with(cx_a, |p, _| assert!(p.collaborators().is_empty()));
3592}
3593
3594#[gpui::test(iterations = 10)]
3595async fn test_canceling_buffer_opening(
3596 executor: BackgroundExecutor,
3597 cx_a: &mut TestAppContext,
3598 cx_b: &mut TestAppContext,
3599) {
3600 let mut server = TestServer::start(executor.clone()).await;
3601 let client_a = server.create_client(cx_a, "user_a").await;
3602 let client_b = server.create_client(cx_b, "user_b").await;
3603 server
3604 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
3605 .await;
3606 let active_call_a = cx_a.read(ActiveCall::global);
3607
3608 client_a
3609 .fs()
3610 .insert_tree(
3611 "/dir",
3612 json!({
3613 "a.txt": "abc",
3614 }),
3615 )
3616 .await;
3617 let (project_a, worktree_id) = client_a.build_local_project("/dir", cx_a).await;
3618 let project_id = active_call_a
3619 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
3620 .await
3621 .unwrap();
3622 let project_b = client_b.build_remote_project(project_id, cx_b).await;
3623
3624 let buffer_a = project_a
3625 .update(cx_a, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
3626 .await
3627 .unwrap();
3628
3629 // Open a buffer as client B but cancel after a random amount of time.
3630 let buffer_b = project_b.update(cx_b, |p, cx| {
3631 p.open_buffer_by_id(buffer_a.read_with(cx_a, |a, _| a.remote_id()), cx)
3632 });
3633 executor.simulate_random_delay().await;
3634 drop(buffer_b);
3635
3636 // Try opening the same buffer again as client B, and ensure we can
3637 // still do it despite the cancellation above.
3638 let buffer_b = project_b
3639 .update(cx_b, |p, cx| {
3640 p.open_buffer_by_id(buffer_a.read_with(cx_a, |a, _| a.remote_id()), cx)
3641 })
3642 .await
3643 .unwrap();
3644
3645 buffer_b.read_with(cx_b, |buf, _| assert_eq!(buf.text(), "abc"));
3646}
3647
3648#[gpui::test(iterations = 10)]
3649async fn test_leaving_project(
3650 executor: BackgroundExecutor,
3651 cx_a: &mut TestAppContext,
3652 cx_b: &mut TestAppContext,
3653 cx_c: &mut TestAppContext,
3654) {
3655 let mut server = TestServer::start(executor.clone()).await;
3656 let client_a = server.create_client(cx_a, "user_a").await;
3657 let client_b = server.create_client(cx_b, "user_b").await;
3658 let client_c = server.create_client(cx_c, "user_c").await;
3659 server
3660 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b), (&client_c, cx_c)])
3661 .await;
3662 let active_call_a = cx_a.read(ActiveCall::global);
3663
3664 client_a
3665 .fs()
3666 .insert_tree(
3667 "/a",
3668 json!({
3669 "a.txt": "a-contents",
3670 "b.txt": "b-contents",
3671 }),
3672 )
3673 .await;
3674 let (project_a, _) = client_a.build_local_project("/a", cx_a).await;
3675 let project_id = active_call_a
3676 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
3677 .await
3678 .unwrap();
3679 let project_b1 = client_b.build_remote_project(project_id, cx_b).await;
3680 let project_c = client_c.build_remote_project(project_id, cx_c).await;
3681
3682 // Client A sees that a guest has joined.
3683 executor.run_until_parked();
3684
3685 project_a.read_with(cx_a, |project, _| {
3686 assert_eq!(project.collaborators().len(), 2);
3687 });
3688
3689 project_b1.read_with(cx_b, |project, _| {
3690 assert_eq!(project.collaborators().len(), 2);
3691 });
3692
3693 project_c.read_with(cx_c, |project, _| {
3694 assert_eq!(project.collaborators().len(), 2);
3695 });
3696
3697 // Client B opens a buffer.
3698 let buffer_b1 = project_b1
3699 .update(cx_b, |project, cx| {
3700 let worktree_id = project.worktrees().next().unwrap().read(cx).id();
3701 project.open_buffer((worktree_id, "a.txt"), cx)
3702 })
3703 .await
3704 .unwrap();
3705
3706 buffer_b1.read_with(cx_b, |buffer, _| assert_eq!(buffer.text(), "a-contents"));
3707
3708 // Drop client B's project and ensure client A and client C observe client B leaving.
3709 cx_b.update(|_| drop(project_b1));
3710 executor.run_until_parked();
3711
3712 project_a.read_with(cx_a, |project, _| {
3713 assert_eq!(project.collaborators().len(), 1);
3714 });
3715
3716 project_c.read_with(cx_c, |project, _| {
3717 assert_eq!(project.collaborators().len(), 1);
3718 });
3719
3720 // Client B re-joins the project and can open buffers as before.
3721 let project_b2 = client_b.build_remote_project(project_id, cx_b).await;
3722 executor.run_until_parked();
3723
3724 project_a.read_with(cx_a, |project, _| {
3725 assert_eq!(project.collaborators().len(), 2);
3726 });
3727
3728 project_b2.read_with(cx_b, |project, _| {
3729 assert_eq!(project.collaborators().len(), 2);
3730 });
3731
3732 project_c.read_with(cx_c, |project, _| {
3733 assert_eq!(project.collaborators().len(), 2);
3734 });
3735
3736 let buffer_b2 = project_b2
3737 .update(cx_b, |project, cx| {
3738 let worktree_id = project.worktrees().next().unwrap().read(cx).id();
3739 project.open_buffer((worktree_id, "a.txt"), cx)
3740 })
3741 .await
3742 .unwrap();
3743
3744 buffer_b2.read_with(cx_b, |buffer, _| assert_eq!(buffer.text(), "a-contents"));
3745
3746 project_a.read_with(cx_a, |project, _| {
3747 assert_eq!(project.collaborators().len(), 2);
3748 });
3749
3750 // Drop client B's connection and ensure client A and client C observe client B leaving.
3751 client_b.disconnect(&cx_b.to_async());
3752 executor.advance_clock(RECONNECT_TIMEOUT);
3753
3754 project_a.read_with(cx_a, |project, _| {
3755 assert_eq!(project.collaborators().len(), 1);
3756 });
3757
3758 project_b2.read_with(cx_b, |project, _| {
3759 assert!(project.is_disconnected());
3760 });
3761
3762 project_c.read_with(cx_c, |project, _| {
3763 assert_eq!(project.collaborators().len(), 1);
3764 });
3765
3766 // Client B can't join the project, unless they re-join the room.
3767 cx_b.spawn(|cx| {
3768 Project::in_room(
3769 project_id,
3770 client_b.app_state.client.clone(),
3771 client_b.user_store().clone(),
3772 client_b.language_registry().clone(),
3773 FakeFs::new(cx.background_executor().clone()),
3774 cx,
3775 )
3776 })
3777 .await
3778 .unwrap_err();
3779
3780 // Simulate connection loss for client C and ensure client A observes client C leaving the project.
3781 client_c.wait_for_current_user(cx_c).await;
3782 server.forbid_connections();
3783 server.disconnect_client(client_c.peer_id().unwrap());
3784 executor.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
3785 executor.run_until_parked();
3786
3787 project_a.read_with(cx_a, |project, _| {
3788 assert_eq!(project.collaborators().len(), 0);
3789 });
3790
3791 project_b2.read_with(cx_b, |project, _| {
3792 assert!(project.is_disconnected());
3793 });
3794
3795 project_c.read_with(cx_c, |project, _| {
3796 assert!(project.is_disconnected());
3797 });
3798}
3799
3800#[gpui::test(iterations = 10)]
3801async fn test_collaborating_with_diagnostics(
3802 executor: BackgroundExecutor,
3803 cx_a: &mut TestAppContext,
3804 cx_b: &mut TestAppContext,
3805 cx_c: &mut TestAppContext,
3806) {
3807 let mut server = TestServer::start(executor.clone()).await;
3808 let client_a = server.create_client(cx_a, "user_a").await;
3809 let client_b = server.create_client(cx_b, "user_b").await;
3810 let client_c = server.create_client(cx_c, "user_c").await;
3811 server
3812 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b), (&client_c, cx_c)])
3813 .await;
3814 let active_call_a = cx_a.read(ActiveCall::global);
3815
3816 client_a.language_registry().add(Arc::new(Language::new(
3817 LanguageConfig {
3818 name: "Rust".into(),
3819 matcher: LanguageMatcher {
3820 path_suffixes: vec!["rs".to_string()],
3821 ..Default::default()
3822 },
3823 ..Default::default()
3824 },
3825 Some(tree_sitter_rust::language()),
3826 )));
3827 let mut fake_language_servers = client_a
3828 .language_registry()
3829 .register_fake_lsp_adapter("Rust", Default::default());
3830
3831 // Share a project as client A
3832 client_a
3833 .fs()
3834 .insert_tree(
3835 "/a",
3836 json!({
3837 "a.rs": "let one = two",
3838 "other.rs": "",
3839 }),
3840 )
3841 .await;
3842 let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
3843
3844 // Cause the language server to start.
3845 let _buffer = project_a
3846 .update(cx_a, |project, cx| {
3847 project.open_buffer(
3848 ProjectPath {
3849 worktree_id,
3850 path: Path::new("other.rs").into(),
3851 },
3852 cx,
3853 )
3854 })
3855 .await
3856 .unwrap();
3857
3858 // Simulate a language server reporting errors for a file.
3859 let mut fake_language_server = fake_language_servers.next().await.unwrap();
3860 fake_language_server
3861 .receive_notification::<lsp::notification::DidOpenTextDocument>()
3862 .await;
3863 fake_language_server.notify::<lsp::notification::PublishDiagnostics>(
3864 lsp::PublishDiagnosticsParams {
3865 uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
3866 version: None,
3867 diagnostics: vec![lsp::Diagnostic {
3868 severity: Some(lsp::DiagnosticSeverity::WARNING),
3869 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
3870 message: "message 0".to_string(),
3871 ..Default::default()
3872 }],
3873 },
3874 );
3875
3876 // Client A shares the project and, simultaneously, the language server
3877 // publishes a diagnostic. This is done to ensure that the server always
3878 // observes the latest diagnostics for a worktree.
3879 let project_id = active_call_a
3880 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
3881 .await
3882 .unwrap();
3883 fake_language_server.notify::<lsp::notification::PublishDiagnostics>(
3884 lsp::PublishDiagnosticsParams {
3885 uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
3886 version: None,
3887 diagnostics: vec![lsp::Diagnostic {
3888 severity: Some(lsp::DiagnosticSeverity::ERROR),
3889 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
3890 message: "message 1".to_string(),
3891 ..Default::default()
3892 }],
3893 },
3894 );
3895
3896 // Join the worktree as client B.
3897 let project_b = client_b.build_remote_project(project_id, cx_b).await;
3898
3899 // Wait for server to see the diagnostics update.
3900 executor.run_until_parked();
3901
3902 // Ensure client B observes the new diagnostics.
3903
3904 project_b.read_with(cx_b, |project, cx| {
3905 assert_eq!(
3906 project.diagnostic_summaries(false, cx).collect::<Vec<_>>(),
3907 &[(
3908 ProjectPath {
3909 worktree_id,
3910 path: Arc::from(Path::new("a.rs")),
3911 },
3912 LanguageServerId(0),
3913 DiagnosticSummary {
3914 error_count: 1,
3915 warning_count: 0,
3916 },
3917 )]
3918 )
3919 });
3920
3921 // Join project as client C and observe the diagnostics.
3922 let project_c = client_c.build_remote_project(project_id, cx_c).await;
3923 executor.run_until_parked();
3924 let project_c_diagnostic_summaries =
3925 Rc::new(RefCell::new(project_c.read_with(cx_c, |project, cx| {
3926 project.diagnostic_summaries(false, cx).collect::<Vec<_>>()
3927 })));
3928 project_c.update(cx_c, |_, cx| {
3929 let summaries = project_c_diagnostic_summaries.clone();
3930 cx.subscribe(&project_c, {
3931 move |p, _, event, cx| {
3932 if let project::Event::DiskBasedDiagnosticsFinished { .. } = event {
3933 *summaries.borrow_mut() = p.diagnostic_summaries(false, cx).collect();
3934 }
3935 }
3936 })
3937 .detach();
3938 });
3939
3940 executor.run_until_parked();
3941 assert_eq!(
3942 project_c_diagnostic_summaries.borrow().as_slice(),
3943 &[(
3944 ProjectPath {
3945 worktree_id,
3946 path: Arc::from(Path::new("a.rs")),
3947 },
3948 LanguageServerId(0),
3949 DiagnosticSummary {
3950 error_count: 1,
3951 warning_count: 0,
3952 },
3953 )]
3954 );
3955
3956 // Simulate a language server reporting more errors for a file.
3957 fake_language_server.notify::<lsp::notification::PublishDiagnostics>(
3958 lsp::PublishDiagnosticsParams {
3959 uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
3960 version: None,
3961 diagnostics: vec![
3962 lsp::Diagnostic {
3963 severity: Some(lsp::DiagnosticSeverity::ERROR),
3964 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
3965 message: "message 1".to_string(),
3966 ..Default::default()
3967 },
3968 lsp::Diagnostic {
3969 severity: Some(lsp::DiagnosticSeverity::WARNING),
3970 range: lsp::Range::new(lsp::Position::new(0, 10), lsp::Position::new(0, 13)),
3971 message: "message 2".to_string(),
3972 ..Default::default()
3973 },
3974 ],
3975 },
3976 );
3977
3978 // Clients B and C get the updated summaries
3979 executor.run_until_parked();
3980
3981 project_b.read_with(cx_b, |project, cx| {
3982 assert_eq!(
3983 project.diagnostic_summaries(false, cx).collect::<Vec<_>>(),
3984 [(
3985 ProjectPath {
3986 worktree_id,
3987 path: Arc::from(Path::new("a.rs")),
3988 },
3989 LanguageServerId(0),
3990 DiagnosticSummary {
3991 error_count: 1,
3992 warning_count: 1,
3993 },
3994 )]
3995 );
3996 });
3997
3998 project_c.read_with(cx_c, |project, cx| {
3999 assert_eq!(
4000 project.diagnostic_summaries(false, cx).collect::<Vec<_>>(),
4001 [(
4002 ProjectPath {
4003 worktree_id,
4004 path: Arc::from(Path::new("a.rs")),
4005 },
4006 LanguageServerId(0),
4007 DiagnosticSummary {
4008 error_count: 1,
4009 warning_count: 1,
4010 },
4011 )]
4012 );
4013 });
4014
4015 // Open the file with the errors on client B. They should be present.
4016 let open_buffer = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx));
4017 let buffer_b = cx_b.executor().spawn(open_buffer).await.unwrap();
4018
4019 buffer_b.read_with(cx_b, |buffer, _| {
4020 assert_eq!(
4021 buffer
4022 .snapshot()
4023 .diagnostics_in_range::<_, Point>(0..buffer.len(), false)
4024 .collect::<Vec<_>>(),
4025 &[
4026 DiagnosticEntry {
4027 range: Point::new(0, 4)..Point::new(0, 7),
4028 diagnostic: Diagnostic {
4029 group_id: 2,
4030 message: "message 1".to_string(),
4031 severity: lsp::DiagnosticSeverity::ERROR,
4032 is_primary: true,
4033 ..Default::default()
4034 }
4035 },
4036 DiagnosticEntry {
4037 range: Point::new(0, 10)..Point::new(0, 13),
4038 diagnostic: Diagnostic {
4039 group_id: 3,
4040 severity: lsp::DiagnosticSeverity::WARNING,
4041 message: "message 2".to_string(),
4042 is_primary: true,
4043 ..Default::default()
4044 }
4045 }
4046 ]
4047 );
4048 });
4049
4050 // Simulate a language server reporting no errors for a file.
4051 fake_language_server.notify::<lsp::notification::PublishDiagnostics>(
4052 lsp::PublishDiagnosticsParams {
4053 uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
4054 version: None,
4055 diagnostics: vec![],
4056 },
4057 );
4058 executor.run_until_parked();
4059
4060 project_a.read_with(cx_a, |project, cx| {
4061 assert_eq!(
4062 project.diagnostic_summaries(false, cx).collect::<Vec<_>>(),
4063 []
4064 )
4065 });
4066
4067 project_b.read_with(cx_b, |project, cx| {
4068 assert_eq!(
4069 project.diagnostic_summaries(false, cx).collect::<Vec<_>>(),
4070 []
4071 )
4072 });
4073
4074 project_c.read_with(cx_c, |project, cx| {
4075 assert_eq!(
4076 project.diagnostic_summaries(false, cx).collect::<Vec<_>>(),
4077 []
4078 )
4079 });
4080}
4081
4082#[gpui::test(iterations = 10)]
4083async fn test_collaborating_with_lsp_progress_updates_and_diagnostics_ordering(
4084 executor: BackgroundExecutor,
4085 cx_a: &mut TestAppContext,
4086 cx_b: &mut TestAppContext,
4087) {
4088 let mut server = TestServer::start(executor.clone()).await;
4089 let client_a = server.create_client(cx_a, "user_a").await;
4090 let client_b = server.create_client(cx_b, "user_b").await;
4091 server
4092 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
4093 .await;
4094
4095 client_a.language_registry().add(rust_lang());
4096 let mut fake_language_servers = client_a.language_registry().register_fake_lsp_adapter(
4097 "Rust",
4098 FakeLspAdapter {
4099 disk_based_diagnostics_progress_token: Some("the-disk-based-token".into()),
4100 disk_based_diagnostics_sources: vec!["the-disk-based-diagnostics-source".into()],
4101 ..Default::default()
4102 },
4103 );
4104
4105 let file_names = &["one.rs", "two.rs", "three.rs", "four.rs", "five.rs"];
4106 client_a
4107 .fs()
4108 .insert_tree(
4109 "/test",
4110 json!({
4111 "one.rs": "const ONE: usize = 1;",
4112 "two.rs": "const TWO: usize = 2;",
4113 "three.rs": "const THREE: usize = 3;",
4114 "four.rs": "const FOUR: usize = 3;",
4115 "five.rs": "const FIVE: usize = 3;",
4116 }),
4117 )
4118 .await;
4119
4120 let (project_a, worktree_id) = client_a.build_local_project("/test", cx_a).await;
4121
4122 // Share a project as client A
4123 let active_call_a = cx_a.read(ActiveCall::global);
4124 let project_id = active_call_a
4125 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
4126 .await
4127 .unwrap();
4128
4129 // Join the project as client B and open all three files.
4130 let project_b = client_b.build_remote_project(project_id, cx_b).await;
4131 let guest_buffers = futures::future::try_join_all(file_names.iter().map(|file_name| {
4132 project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, file_name), cx))
4133 }))
4134 .await
4135 .unwrap();
4136
4137 // Simulate a language server reporting errors for a file.
4138 let fake_language_server = fake_language_servers.next().await.unwrap();
4139 fake_language_server
4140 .request::<lsp::request::WorkDoneProgressCreate>(lsp::WorkDoneProgressCreateParams {
4141 token: lsp::NumberOrString::String("the-disk-based-token".to_string()),
4142 })
4143 .await
4144 .unwrap();
4145 fake_language_server.notify::<lsp::notification::Progress>(lsp::ProgressParams {
4146 token: lsp::NumberOrString::String("the-disk-based-token".to_string()),
4147 value: lsp::ProgressParamsValue::WorkDone(lsp::WorkDoneProgress::Begin(
4148 lsp::WorkDoneProgressBegin {
4149 title: "Progress Began".into(),
4150 ..Default::default()
4151 },
4152 )),
4153 });
4154 for file_name in file_names {
4155 fake_language_server.notify::<lsp::notification::PublishDiagnostics>(
4156 lsp::PublishDiagnosticsParams {
4157 uri: lsp::Url::from_file_path(Path::new("/test").join(file_name)).unwrap(),
4158 version: None,
4159 diagnostics: vec![lsp::Diagnostic {
4160 severity: Some(lsp::DiagnosticSeverity::WARNING),
4161 source: Some("the-disk-based-diagnostics-source".into()),
4162 range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
4163 message: "message one".to_string(),
4164 ..Default::default()
4165 }],
4166 },
4167 );
4168 }
4169 fake_language_server.notify::<lsp::notification::Progress>(lsp::ProgressParams {
4170 token: lsp::NumberOrString::String("the-disk-based-token".to_string()),
4171 value: lsp::ProgressParamsValue::WorkDone(lsp::WorkDoneProgress::End(
4172 lsp::WorkDoneProgressEnd { message: None },
4173 )),
4174 });
4175
4176 // When the "disk base diagnostics finished" message is received, the buffers'
4177 // diagnostics are expected to be present.
4178 let disk_based_diagnostics_finished = Arc::new(AtomicBool::new(false));
4179 project_b.update(cx_b, {
4180 let project_b = project_b.clone();
4181 let disk_based_diagnostics_finished = disk_based_diagnostics_finished.clone();
4182 move |_, cx| {
4183 cx.subscribe(&project_b, move |_, _, event, cx| {
4184 if let project::Event::DiskBasedDiagnosticsFinished { .. } = event {
4185 disk_based_diagnostics_finished.store(true, SeqCst);
4186 for buffer in &guest_buffers {
4187 assert_eq!(
4188 buffer
4189 .read(cx)
4190 .snapshot()
4191 .diagnostics_in_range::<_, usize>(0..5, false)
4192 .count(),
4193 1,
4194 "expected a diagnostic for buffer {:?}",
4195 buffer.read(cx).file().unwrap().path(),
4196 );
4197 }
4198 }
4199 })
4200 .detach();
4201 }
4202 });
4203
4204 executor.run_until_parked();
4205 assert!(disk_based_diagnostics_finished.load(SeqCst));
4206}
4207
4208#[gpui::test(iterations = 10)]
4209async fn test_reloading_buffer_manually(
4210 executor: BackgroundExecutor,
4211 cx_a: &mut TestAppContext,
4212 cx_b: &mut TestAppContext,
4213) {
4214 let mut server = TestServer::start(executor.clone()).await;
4215 let client_a = server.create_client(cx_a, "user_a").await;
4216 let client_b = server.create_client(cx_b, "user_b").await;
4217 server
4218 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
4219 .await;
4220 let active_call_a = cx_a.read(ActiveCall::global);
4221
4222 client_a
4223 .fs()
4224 .insert_tree("/a", json!({ "a.rs": "let one = 1;" }))
4225 .await;
4226 let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
4227 let buffer_a = project_a
4228 .update(cx_a, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
4229 .await
4230 .unwrap();
4231 let project_id = active_call_a
4232 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
4233 .await
4234 .unwrap();
4235
4236 let project_b = client_b.build_remote_project(project_id, cx_b).await;
4237
4238 let open_buffer = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx));
4239 let buffer_b = cx_b.executor().spawn(open_buffer).await.unwrap();
4240 buffer_b.update(cx_b, |buffer, cx| {
4241 buffer.edit([(4..7, "six")], None, cx);
4242 buffer.edit([(10..11, "6")], None, cx);
4243 assert_eq!(buffer.text(), "let six = 6;");
4244 assert!(buffer.is_dirty());
4245 assert!(!buffer.has_conflict());
4246 });
4247 executor.run_until_parked();
4248
4249 buffer_a.read_with(cx_a, |buffer, _| assert_eq!(buffer.text(), "let six = 6;"));
4250
4251 client_a
4252 .fs()
4253 .save(
4254 "/a/a.rs".as_ref(),
4255 &Rope::from("let seven = 7;"),
4256 LineEnding::Unix,
4257 )
4258 .await
4259 .unwrap();
4260 executor.run_until_parked();
4261
4262 buffer_a.read_with(cx_a, |buffer, _| assert!(buffer.has_conflict()));
4263
4264 buffer_b.read_with(cx_b, |buffer, _| assert!(buffer.has_conflict()));
4265
4266 project_b
4267 .update(cx_b, |project, cx| {
4268 project.reload_buffers(HashSet::from_iter([buffer_b.clone()]), true, cx)
4269 })
4270 .await
4271 .unwrap();
4272
4273 buffer_a.read_with(cx_a, |buffer, _| {
4274 assert_eq!(buffer.text(), "let seven = 7;");
4275 assert!(!buffer.is_dirty());
4276 assert!(!buffer.has_conflict());
4277 });
4278
4279 buffer_b.read_with(cx_b, |buffer, _| {
4280 assert_eq!(buffer.text(), "let seven = 7;");
4281 assert!(!buffer.is_dirty());
4282 assert!(!buffer.has_conflict());
4283 });
4284
4285 buffer_a.update(cx_a, |buffer, cx| {
4286 // Undoing on the host is a no-op when the reload was initiated by the guest.
4287 buffer.undo(cx);
4288 assert_eq!(buffer.text(), "let seven = 7;");
4289 assert!(!buffer.is_dirty());
4290 assert!(!buffer.has_conflict());
4291 });
4292 buffer_b.update(cx_b, |buffer, cx| {
4293 // Undoing on the guest rolls back the buffer to before it was reloaded but the conflict gets cleared.
4294 buffer.undo(cx);
4295 assert_eq!(buffer.text(), "let six = 6;");
4296 assert!(buffer.is_dirty());
4297 assert!(!buffer.has_conflict());
4298 });
4299}
4300
4301#[gpui::test(iterations = 10)]
4302async fn test_formatting_buffer(
4303 executor: BackgroundExecutor,
4304 cx_a: &mut TestAppContext,
4305 cx_b: &mut TestAppContext,
4306) {
4307 executor.allow_parking();
4308 let mut server = TestServer::start(executor.clone()).await;
4309 let client_a = server.create_client(cx_a, "user_a").await;
4310 let client_b = server.create_client(cx_b, "user_b").await;
4311 server
4312 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
4313 .await;
4314 let active_call_a = cx_a.read(ActiveCall::global);
4315
4316 client_a.language_registry().add(rust_lang());
4317 let mut fake_language_servers = client_a
4318 .language_registry()
4319 .register_fake_lsp_adapter("Rust", FakeLspAdapter::default());
4320
4321 // Here we insert a fake tree with a directory that exists on disk. This is needed
4322 // because later we'll invoke a command, which requires passing a working directory
4323 // that points to a valid location on disk.
4324 let directory = env::current_dir().unwrap();
4325 client_a
4326 .fs()
4327 .insert_tree(&directory, json!({ "a.rs": "let one = \"two\"" }))
4328 .await;
4329 let (project_a, worktree_id) = client_a.build_local_project(&directory, cx_a).await;
4330 let project_id = active_call_a
4331 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
4332 .await
4333 .unwrap();
4334 let project_b = client_b.build_remote_project(project_id, cx_b).await;
4335
4336 let open_buffer = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx));
4337 let buffer_b = cx_b.executor().spawn(open_buffer).await.unwrap();
4338
4339 let fake_language_server = fake_language_servers.next().await.unwrap();
4340 fake_language_server.handle_request::<lsp::request::Formatting, _, _>(|_, _| async move {
4341 Ok(Some(vec![
4342 lsp::TextEdit {
4343 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 4)),
4344 new_text: "h".to_string(),
4345 },
4346 lsp::TextEdit {
4347 range: lsp::Range::new(lsp::Position::new(0, 7), lsp::Position::new(0, 7)),
4348 new_text: "y".to_string(),
4349 },
4350 ]))
4351 });
4352
4353 project_b
4354 .update(cx_b, |project, cx| {
4355 project.format(
4356 HashSet::from_iter([buffer_b.clone()]),
4357 true,
4358 FormatTrigger::Save,
4359 cx,
4360 )
4361 })
4362 .await
4363 .unwrap();
4364
4365 // The edits from the LSP are applied, and a final newline is added.
4366 assert_eq!(
4367 buffer_b.read_with(cx_b, |buffer, _| buffer.text()),
4368 "let honey = \"two\"\n"
4369 );
4370
4371 // Ensure buffer can be formatted using an external command. Notice how the
4372 // host's configuration is honored as opposed to using the guest's settings.
4373 cx_a.update(|cx| {
4374 cx.update_global(|store: &mut SettingsStore, cx| {
4375 store.update_user_settings::<AllLanguageSettings>(cx, |file| {
4376 file.defaults.formatter = Some(Formatter::External {
4377 command: "awk".into(),
4378 arguments: vec!["{sub(/two/,\"{buffer_path}\")}1".to_string()].into(),
4379 });
4380 });
4381 });
4382 });
4383 project_b
4384 .update(cx_b, |project, cx| {
4385 project.format(
4386 HashSet::from_iter([buffer_b.clone()]),
4387 true,
4388 FormatTrigger::Save,
4389 cx,
4390 )
4391 })
4392 .await
4393 .unwrap();
4394 assert_eq!(
4395 buffer_b.read_with(cx_b, |buffer, _| buffer.text()),
4396 format!("let honey = \"{}/a.rs\"\n", directory.to_str().unwrap())
4397 );
4398}
4399
4400#[gpui::test(iterations = 10)]
4401async fn test_prettier_formatting_buffer(
4402 executor: BackgroundExecutor,
4403 cx_a: &mut TestAppContext,
4404 cx_b: &mut TestAppContext,
4405) {
4406 let mut server = TestServer::start(executor.clone()).await;
4407 let client_a = server.create_client(cx_a, "user_a").await;
4408 let client_b = server.create_client(cx_b, "user_b").await;
4409 server
4410 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
4411 .await;
4412 let active_call_a = cx_a.read(ActiveCall::global);
4413
4414 let test_plugin = "test_plugin";
4415
4416 client_a.language_registry().add(Arc::new(Language::new(
4417 LanguageConfig {
4418 name: "Rust".into(),
4419 matcher: LanguageMatcher {
4420 path_suffixes: vec!["rs".to_string()],
4421 ..Default::default()
4422 },
4423 prettier_parser_name: Some("test_parser".to_string()),
4424 ..Default::default()
4425 },
4426 Some(tree_sitter_rust::language()),
4427 )));
4428 let mut fake_language_servers = client_a.language_registry().register_fake_lsp_adapter(
4429 "Rust",
4430 FakeLspAdapter {
4431 prettier_plugins: vec![test_plugin],
4432 ..Default::default()
4433 },
4434 );
4435
4436 // Here we insert a fake tree with a directory that exists on disk. This is needed
4437 // because later we'll invoke a command, which requires passing a working directory
4438 // that points to a valid location on disk.
4439 let directory = env::current_dir().unwrap();
4440 let buffer_text = "let one = \"two\"";
4441 client_a
4442 .fs()
4443 .insert_tree(&directory, json!({ "a.rs": buffer_text }))
4444 .await;
4445 let (project_a, worktree_id) = client_a.build_local_project(&directory, cx_a).await;
4446 let prettier_format_suffix = project::TEST_PRETTIER_FORMAT_SUFFIX;
4447 let open_buffer = project_a.update(cx_a, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx));
4448 let buffer_a = cx_a.executor().spawn(open_buffer).await.unwrap();
4449
4450 let project_id = active_call_a
4451 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
4452 .await
4453 .unwrap();
4454 let project_b = client_b.build_remote_project(project_id, cx_b).await;
4455 let open_buffer = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx));
4456 let buffer_b = cx_b.executor().spawn(open_buffer).await.unwrap();
4457
4458 cx_a.update(|cx| {
4459 cx.update_global(|store: &mut SettingsStore, cx| {
4460 store.update_user_settings::<AllLanguageSettings>(cx, |file| {
4461 file.defaults.formatter = Some(Formatter::Auto);
4462 });
4463 });
4464 });
4465 cx_b.update(|cx| {
4466 cx.update_global(|store: &mut SettingsStore, cx| {
4467 store.update_user_settings::<AllLanguageSettings>(cx, |file| {
4468 file.defaults.formatter = Some(Formatter::LanguageServer);
4469 });
4470 });
4471 });
4472 let fake_language_server = fake_language_servers.next().await.unwrap();
4473 fake_language_server.handle_request::<lsp::request::Formatting, _, _>(|_, _| async move {
4474 panic!(
4475 "Unexpected: prettier should be preferred since it's enabled and language supports it"
4476 )
4477 });
4478
4479 project_b
4480 .update(cx_b, |project, cx| {
4481 project.format(
4482 HashSet::from_iter([buffer_b.clone()]),
4483 true,
4484 FormatTrigger::Save,
4485 cx,
4486 )
4487 })
4488 .await
4489 .unwrap();
4490
4491 executor.run_until_parked();
4492 assert_eq!(
4493 buffer_b.read_with(cx_b, |buffer, _| buffer.text()),
4494 buffer_text.to_string() + "\n" + prettier_format_suffix,
4495 "Prettier formatting was not applied to client buffer after client's request"
4496 );
4497
4498 project_a
4499 .update(cx_a, |project, cx| {
4500 project.format(
4501 HashSet::from_iter([buffer_a.clone()]),
4502 true,
4503 FormatTrigger::Manual,
4504 cx,
4505 )
4506 })
4507 .await
4508 .unwrap();
4509
4510 executor.run_until_parked();
4511 assert_eq!(
4512 buffer_b.read_with(cx_b, |buffer, _| buffer.text()),
4513 buffer_text.to_string() + "\n" + prettier_format_suffix + "\n" + prettier_format_suffix,
4514 "Prettier formatting was not applied to client buffer after host's request"
4515 );
4516}
4517
4518#[gpui::test(iterations = 10)]
4519async fn test_definition(
4520 executor: BackgroundExecutor,
4521 cx_a: &mut TestAppContext,
4522 cx_b: &mut TestAppContext,
4523) {
4524 let mut server = TestServer::start(executor.clone()).await;
4525 let client_a = server.create_client(cx_a, "user_a").await;
4526 let client_b = server.create_client(cx_b, "user_b").await;
4527 server
4528 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
4529 .await;
4530 let active_call_a = cx_a.read(ActiveCall::global);
4531
4532 let mut fake_language_servers = client_a
4533 .language_registry()
4534 .register_fake_lsp_adapter("Rust", Default::default());
4535 client_a.language_registry().add(rust_lang());
4536
4537 client_a
4538 .fs()
4539 .insert_tree(
4540 "/root",
4541 json!({
4542 "dir-1": {
4543 "a.rs": "const ONE: usize = b::TWO + b::THREE;",
4544 },
4545 "dir-2": {
4546 "b.rs": "const TWO: c::T2 = 2;\nconst THREE: usize = 3;",
4547 "c.rs": "type T2 = usize;",
4548 }
4549 }),
4550 )
4551 .await;
4552 let (project_a, worktree_id) = client_a.build_local_project("/root/dir-1", cx_a).await;
4553 let project_id = active_call_a
4554 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
4555 .await
4556 .unwrap();
4557 let project_b = client_b.build_remote_project(project_id, cx_b).await;
4558
4559 // Open the file on client B.
4560 let open_buffer = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx));
4561 let buffer_b = cx_b.executor().spawn(open_buffer).await.unwrap();
4562
4563 // Request the definition of a symbol as the guest.
4564 let fake_language_server = fake_language_servers.next().await.unwrap();
4565 fake_language_server.handle_request::<lsp::request::GotoDefinition, _, _>(|_, _| async move {
4566 Ok(Some(lsp::GotoDefinitionResponse::Scalar(
4567 lsp::Location::new(
4568 lsp::Url::from_file_path("/root/dir-2/b.rs").unwrap(),
4569 lsp::Range::new(lsp::Position::new(0, 6), lsp::Position::new(0, 9)),
4570 ),
4571 )))
4572 });
4573
4574 let definitions_1 = project_b
4575 .update(cx_b, |p, cx| p.definition(&buffer_b, 23, cx))
4576 .await
4577 .unwrap();
4578 cx_b.read(|cx| {
4579 assert_eq!(definitions_1.len(), 1);
4580 assert_eq!(project_b.read(cx).worktrees().count(), 2);
4581 let target_buffer = definitions_1[0].target.buffer.read(cx);
4582 assert_eq!(
4583 target_buffer.text(),
4584 "const TWO: c::T2 = 2;\nconst THREE: usize = 3;"
4585 );
4586 assert_eq!(
4587 definitions_1[0].target.range.to_point(target_buffer),
4588 Point::new(0, 6)..Point::new(0, 9)
4589 );
4590 });
4591
4592 // Try getting more definitions for the same buffer, ensuring the buffer gets reused from
4593 // the previous call to `definition`.
4594 fake_language_server.handle_request::<lsp::request::GotoDefinition, _, _>(|_, _| async move {
4595 Ok(Some(lsp::GotoDefinitionResponse::Scalar(
4596 lsp::Location::new(
4597 lsp::Url::from_file_path("/root/dir-2/b.rs").unwrap(),
4598 lsp::Range::new(lsp::Position::new(1, 6), lsp::Position::new(1, 11)),
4599 ),
4600 )))
4601 });
4602
4603 let definitions_2 = project_b
4604 .update(cx_b, |p, cx| p.definition(&buffer_b, 33, cx))
4605 .await
4606 .unwrap();
4607 cx_b.read(|cx| {
4608 assert_eq!(definitions_2.len(), 1);
4609 assert_eq!(project_b.read(cx).worktrees().count(), 2);
4610 let target_buffer = definitions_2[0].target.buffer.read(cx);
4611 assert_eq!(
4612 target_buffer.text(),
4613 "const TWO: c::T2 = 2;\nconst THREE: usize = 3;"
4614 );
4615 assert_eq!(
4616 definitions_2[0].target.range.to_point(target_buffer),
4617 Point::new(1, 6)..Point::new(1, 11)
4618 );
4619 });
4620 assert_eq!(
4621 definitions_1[0].target.buffer,
4622 definitions_2[0].target.buffer
4623 );
4624
4625 fake_language_server.handle_request::<lsp::request::GotoTypeDefinition, _, _>(
4626 |req, _| async move {
4627 assert_eq!(
4628 req.text_document_position_params.position,
4629 lsp::Position::new(0, 7)
4630 );
4631 Ok(Some(lsp::GotoDefinitionResponse::Scalar(
4632 lsp::Location::new(
4633 lsp::Url::from_file_path("/root/dir-2/c.rs").unwrap(),
4634 lsp::Range::new(lsp::Position::new(0, 5), lsp::Position::new(0, 7)),
4635 ),
4636 )))
4637 },
4638 );
4639
4640 let type_definitions = project_b
4641 .update(cx_b, |p, cx| p.type_definition(&buffer_b, 7, cx))
4642 .await
4643 .unwrap();
4644 cx_b.read(|cx| {
4645 assert_eq!(type_definitions.len(), 1);
4646 let target_buffer = type_definitions[0].target.buffer.read(cx);
4647 assert_eq!(target_buffer.text(), "type T2 = usize;");
4648 assert_eq!(
4649 type_definitions[0].target.range.to_point(target_buffer),
4650 Point::new(0, 5)..Point::new(0, 7)
4651 );
4652 });
4653}
4654
4655#[gpui::test(iterations = 10)]
4656async fn test_references(
4657 executor: BackgroundExecutor,
4658 cx_a: &mut TestAppContext,
4659 cx_b: &mut TestAppContext,
4660) {
4661 let mut server = TestServer::start(executor.clone()).await;
4662 let client_a = server.create_client(cx_a, "user_a").await;
4663 let client_b = server.create_client(cx_b, "user_b").await;
4664 server
4665 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
4666 .await;
4667 let active_call_a = cx_a.read(ActiveCall::global);
4668
4669 client_a.language_registry().add(rust_lang());
4670 let mut fake_language_servers = client_a.language_registry().register_fake_lsp_adapter(
4671 "Rust",
4672 FakeLspAdapter {
4673 name: "my-fake-lsp-adapter",
4674 capabilities: lsp::ServerCapabilities {
4675 references_provider: Some(lsp::OneOf::Left(true)),
4676 ..Default::default()
4677 },
4678 ..Default::default()
4679 },
4680 );
4681
4682 client_a
4683 .fs()
4684 .insert_tree(
4685 "/root",
4686 json!({
4687 "dir-1": {
4688 "one.rs": "const ONE: usize = 1;",
4689 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
4690 },
4691 "dir-2": {
4692 "three.rs": "const THREE: usize = two::TWO + one::ONE;",
4693 }
4694 }),
4695 )
4696 .await;
4697 let (project_a, worktree_id) = client_a.build_local_project("/root/dir-1", cx_a).await;
4698 let project_id = active_call_a
4699 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
4700 .await
4701 .unwrap();
4702 let project_b = client_b.build_remote_project(project_id, cx_b).await;
4703
4704 // Open the file on client B.
4705 let open_buffer = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "one.rs"), cx));
4706 let buffer_b = cx_b.executor().spawn(open_buffer).await.unwrap();
4707
4708 // Request references to a symbol as the guest.
4709 let fake_language_server = fake_language_servers.next().await.unwrap();
4710 let (lsp_response_tx, rx) = mpsc::unbounded::<Result<Option<Vec<lsp::Location>>>>();
4711 fake_language_server.handle_request::<lsp::request::References, _, _>({
4712 let rx = Arc::new(Mutex::new(Some(rx)));
4713 move |params, _| {
4714 assert_eq!(
4715 params.text_document_position.text_document.uri.as_str(),
4716 "file:///root/dir-1/one.rs"
4717 );
4718 let rx = rx.clone();
4719 async move {
4720 let mut response_rx = rx.lock().take().unwrap();
4721 let result = response_rx.next().await.unwrap();
4722 *rx.lock() = Some(response_rx);
4723 result
4724 }
4725 }
4726 });
4727
4728 let references = project_b.update(cx_b, |p, cx| p.references(&buffer_b, 7, cx));
4729
4730 // User is informed that a request is pending.
4731 executor.run_until_parked();
4732 project_b.read_with(cx_b, |project, _| {
4733 let status = project.language_server_statuses().next().cloned().unwrap();
4734 assert_eq!(status.name, "my-fake-lsp-adapter");
4735 assert_eq!(
4736 status.pending_work.values().next().unwrap().message,
4737 Some("Finding references...".into())
4738 );
4739 });
4740
4741 // Cause the language server to respond.
4742 lsp_response_tx
4743 .unbounded_send(Ok(Some(vec![
4744 lsp::Location {
4745 uri: lsp::Url::from_file_path("/root/dir-1/two.rs").unwrap(),
4746 range: lsp::Range::new(lsp::Position::new(0, 24), lsp::Position::new(0, 27)),
4747 },
4748 lsp::Location {
4749 uri: lsp::Url::from_file_path("/root/dir-1/two.rs").unwrap(),
4750 range: lsp::Range::new(lsp::Position::new(0, 35), lsp::Position::new(0, 38)),
4751 },
4752 lsp::Location {
4753 uri: lsp::Url::from_file_path("/root/dir-2/three.rs").unwrap(),
4754 range: lsp::Range::new(lsp::Position::new(0, 37), lsp::Position::new(0, 40)),
4755 },
4756 ])))
4757 .unwrap();
4758
4759 let references = references.await.unwrap();
4760 executor.run_until_parked();
4761 project_b.read_with(cx_b, |project, cx| {
4762 // User is informed that a request is no longer pending.
4763 let status = project.language_server_statuses().next().unwrap();
4764 assert!(status.pending_work.is_empty());
4765
4766 assert_eq!(references.len(), 3);
4767 assert_eq!(project.worktrees().count(), 2);
4768
4769 let two_buffer = references[0].buffer.read(cx);
4770 let three_buffer = references[2].buffer.read(cx);
4771 assert_eq!(
4772 two_buffer.file().unwrap().path().as_ref(),
4773 Path::new("two.rs")
4774 );
4775 assert_eq!(references[1].buffer, references[0].buffer);
4776 assert_eq!(
4777 three_buffer.file().unwrap().full_path(cx),
4778 Path::new("/root/dir-2/three.rs")
4779 );
4780
4781 assert_eq!(references[0].range.to_offset(two_buffer), 24..27);
4782 assert_eq!(references[1].range.to_offset(two_buffer), 35..38);
4783 assert_eq!(references[2].range.to_offset(three_buffer), 37..40);
4784 });
4785
4786 let references = project_b.update(cx_b, |p, cx| p.references(&buffer_b, 7, cx));
4787
4788 // User is informed that a request is pending.
4789 executor.run_until_parked();
4790 project_b.read_with(cx_b, |project, _| {
4791 let status = project.language_server_statuses().next().cloned().unwrap();
4792 assert_eq!(status.name, "my-fake-lsp-adapter");
4793 assert_eq!(
4794 status.pending_work.values().next().unwrap().message,
4795 Some("Finding references...".into())
4796 );
4797 });
4798
4799 // Cause the LSP request to fail.
4800 lsp_response_tx
4801 .unbounded_send(Err(anyhow!("can't find references")))
4802 .unwrap();
4803 references.await.unwrap_err();
4804
4805 // User is informed that the request is no longer pending.
4806 executor.run_until_parked();
4807 project_b.read_with(cx_b, |project, _| {
4808 let status = project.language_server_statuses().next().unwrap();
4809 assert!(status.pending_work.is_empty());
4810 });
4811}
4812
4813#[gpui::test(iterations = 10)]
4814async fn test_project_search(
4815 executor: BackgroundExecutor,
4816 cx_a: &mut TestAppContext,
4817 cx_b: &mut TestAppContext,
4818) {
4819 let mut server = TestServer::start(executor.clone()).await;
4820 let client_a = server.create_client(cx_a, "user_a").await;
4821 let client_b = server.create_client(cx_b, "user_b").await;
4822 server
4823 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
4824 .await;
4825 let active_call_a = cx_a.read(ActiveCall::global);
4826
4827 client_a
4828 .fs()
4829 .insert_tree(
4830 "/root",
4831 json!({
4832 "dir-1": {
4833 "a": "hello world",
4834 "b": "goodnight moon",
4835 "c": "a world of goo",
4836 "d": "world champion of clown world",
4837 },
4838 "dir-2": {
4839 "e": "disney world is fun",
4840 }
4841 }),
4842 )
4843 .await;
4844 let (project_a, _) = client_a.build_local_project("/root/dir-1", cx_a).await;
4845 let (worktree_2, _) = project_a
4846 .update(cx_a, |p, cx| {
4847 p.find_or_create_local_worktree("/root/dir-2", true, cx)
4848 })
4849 .await
4850 .unwrap();
4851 worktree_2
4852 .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
4853 .await;
4854 let project_id = active_call_a
4855 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
4856 .await
4857 .unwrap();
4858
4859 let project_b = client_b.build_remote_project(project_id, cx_b).await;
4860
4861 // Perform a search as the guest.
4862 let mut results = HashMap::default();
4863 let mut search_rx = project_b.update(cx_b, |project, cx| {
4864 project.search(
4865 SearchQuery::text("world", false, false, false, Vec::new(), Vec::new()).unwrap(),
4866 cx,
4867 )
4868 });
4869 while let Some(result) = search_rx.next().await {
4870 match result {
4871 SearchResult::Buffer { buffer, ranges } => {
4872 results.entry(buffer).or_insert(ranges);
4873 }
4874 SearchResult::LimitReached => {
4875 panic!("Unexpectedly reached search limit in tests. If you do want to assert limit-reached, change this panic call.")
4876 }
4877 };
4878 }
4879
4880 let mut ranges_by_path = results
4881 .into_iter()
4882 .map(|(buffer, ranges)| {
4883 buffer.read_with(cx_b, |buffer, cx| {
4884 let path = buffer.file().unwrap().full_path(cx);
4885 let offset_ranges = ranges
4886 .into_iter()
4887 .map(|range| range.to_offset(buffer))
4888 .collect::<Vec<_>>();
4889 (path, offset_ranges)
4890 })
4891 })
4892 .collect::<Vec<_>>();
4893 ranges_by_path.sort_by_key(|(path, _)| path.clone());
4894
4895 assert_eq!(
4896 ranges_by_path,
4897 &[
4898 (PathBuf::from("dir-1/a"), vec![6..11]),
4899 (PathBuf::from("dir-1/c"), vec![2..7]),
4900 (PathBuf::from("dir-1/d"), vec![0..5, 24..29]),
4901 (PathBuf::from("dir-2/e"), vec![7..12]),
4902 ]
4903 );
4904}
4905
4906#[gpui::test(iterations = 10)]
4907async fn test_document_highlights(
4908 executor: BackgroundExecutor,
4909 cx_a: &mut TestAppContext,
4910 cx_b: &mut TestAppContext,
4911) {
4912 let mut server = TestServer::start(executor.clone()).await;
4913 let client_a = server.create_client(cx_a, "user_a").await;
4914 let client_b = server.create_client(cx_b, "user_b").await;
4915 server
4916 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
4917 .await;
4918 let active_call_a = cx_a.read(ActiveCall::global);
4919
4920 client_a
4921 .fs()
4922 .insert_tree(
4923 "/root-1",
4924 json!({
4925 "main.rs": "fn double(number: i32) -> i32 { number + number }",
4926 }),
4927 )
4928 .await;
4929
4930 let mut fake_language_servers = client_a
4931 .language_registry()
4932 .register_fake_lsp_adapter("Rust", Default::default());
4933 client_a.language_registry().add(rust_lang());
4934
4935 let (project_a, worktree_id) = client_a.build_local_project("/root-1", cx_a).await;
4936 let project_id = active_call_a
4937 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
4938 .await
4939 .unwrap();
4940 let project_b = client_b.build_remote_project(project_id, cx_b).await;
4941
4942 // Open the file on client B.
4943 let open_b = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "main.rs"), cx));
4944 let buffer_b = cx_b.executor().spawn(open_b).await.unwrap();
4945
4946 // Request document highlights as the guest.
4947 let fake_language_server = fake_language_servers.next().await.unwrap();
4948 fake_language_server.handle_request::<lsp::request::DocumentHighlightRequest, _, _>(
4949 |params, _| async move {
4950 assert_eq!(
4951 params
4952 .text_document_position_params
4953 .text_document
4954 .uri
4955 .as_str(),
4956 "file:///root-1/main.rs"
4957 );
4958 assert_eq!(
4959 params.text_document_position_params.position,
4960 lsp::Position::new(0, 34)
4961 );
4962 Ok(Some(vec![
4963 lsp::DocumentHighlight {
4964 kind: Some(lsp::DocumentHighlightKind::WRITE),
4965 range: lsp::Range::new(lsp::Position::new(0, 10), lsp::Position::new(0, 16)),
4966 },
4967 lsp::DocumentHighlight {
4968 kind: Some(lsp::DocumentHighlightKind::READ),
4969 range: lsp::Range::new(lsp::Position::new(0, 32), lsp::Position::new(0, 38)),
4970 },
4971 lsp::DocumentHighlight {
4972 kind: Some(lsp::DocumentHighlightKind::READ),
4973 range: lsp::Range::new(lsp::Position::new(0, 41), lsp::Position::new(0, 47)),
4974 },
4975 ]))
4976 },
4977 );
4978
4979 let highlights = project_b
4980 .update(cx_b, |p, cx| p.document_highlights(&buffer_b, 34, cx))
4981 .await
4982 .unwrap();
4983
4984 buffer_b.read_with(cx_b, |buffer, _| {
4985 let snapshot = buffer.snapshot();
4986
4987 let highlights = highlights
4988 .into_iter()
4989 .map(|highlight| (highlight.kind, highlight.range.to_offset(&snapshot)))
4990 .collect::<Vec<_>>();
4991 assert_eq!(
4992 highlights,
4993 &[
4994 (lsp::DocumentHighlightKind::WRITE, 10..16),
4995 (lsp::DocumentHighlightKind::READ, 32..38),
4996 (lsp::DocumentHighlightKind::READ, 41..47)
4997 ]
4998 )
4999 });
5000}
5001
5002#[gpui::test(iterations = 10)]
5003async fn test_lsp_hover(
5004 executor: BackgroundExecutor,
5005 cx_a: &mut TestAppContext,
5006 cx_b: &mut TestAppContext,
5007) {
5008 let mut server = TestServer::start(executor.clone()).await;
5009 let client_a = server.create_client(cx_a, "user_a").await;
5010 let client_b = server.create_client(cx_b, "user_b").await;
5011 server
5012 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
5013 .await;
5014 let active_call_a = cx_a.read(ActiveCall::global);
5015
5016 client_a
5017 .fs()
5018 .insert_tree(
5019 "/root-1",
5020 json!({
5021 "main.rs": "use std::collections::HashMap;",
5022 }),
5023 )
5024 .await;
5025
5026 client_a.language_registry().add(rust_lang());
5027 let language_server_names = ["rust-analyzer", "CrabLang-ls"];
5028 let mut fake_language_servers = client_a
5029 .language_registry()
5030 .register_specific_fake_lsp_adapter(
5031 "Rust",
5032 true,
5033 FakeLspAdapter {
5034 name: "rust-analyzer",
5035 capabilities: lsp::ServerCapabilities {
5036 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
5037 ..lsp::ServerCapabilities::default()
5038 },
5039 ..FakeLspAdapter::default()
5040 },
5041 );
5042 let _other_server = client_a
5043 .language_registry()
5044 .register_specific_fake_lsp_adapter(
5045 "Rust",
5046 false,
5047 FakeLspAdapter {
5048 name: "CrabLang-ls",
5049 capabilities: lsp::ServerCapabilities {
5050 hover_provider: Some(lsp::HoverProviderCapability::Simple(true)),
5051 ..lsp::ServerCapabilities::default()
5052 },
5053 ..FakeLspAdapter::default()
5054 },
5055 );
5056
5057 let (project_a, worktree_id) = client_a.build_local_project("/root-1", cx_a).await;
5058 let project_id = active_call_a
5059 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
5060 .await
5061 .unwrap();
5062 let project_b = client_b.build_remote_project(project_id, cx_b).await;
5063
5064 // Open the file as the guest
5065 let open_buffer = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "main.rs"), cx));
5066 let buffer_b = cx_b.executor().spawn(open_buffer).await.unwrap();
5067
5068 let mut servers_with_hover_requests = HashMap::default();
5069 for i in 0..language_server_names.len() {
5070 let new_server = fake_language_servers.next().await.unwrap_or_else(|| {
5071 panic!(
5072 "Failed to get language server #{i} with name {}",
5073 &language_server_names[i]
5074 )
5075 });
5076 let new_server_name = new_server.server.name();
5077 assert!(
5078 !servers_with_hover_requests.contains_key(new_server_name),
5079 "Unexpected: initialized server with the same name twice. Name: `{new_server_name}`"
5080 );
5081 let new_server_name = new_server_name.to_string();
5082 match new_server_name.as_str() {
5083 "CrabLang-ls" => {
5084 servers_with_hover_requests.insert(
5085 new_server_name.clone(),
5086 new_server.handle_request::<lsp::request::HoverRequest, _, _>(
5087 move |params, _| {
5088 assert_eq!(
5089 params
5090 .text_document_position_params
5091 .text_document
5092 .uri
5093 .as_str(),
5094 "file:///root-1/main.rs"
5095 );
5096 let name = new_server_name.clone();
5097 async move {
5098 Ok(Some(lsp::Hover {
5099 contents: lsp::HoverContents::Scalar(
5100 lsp::MarkedString::String(format!("{name} hover")),
5101 ),
5102 range: None,
5103 }))
5104 }
5105 },
5106 ),
5107 );
5108 }
5109 "rust-analyzer" => {
5110 servers_with_hover_requests.insert(
5111 new_server_name.clone(),
5112 new_server.handle_request::<lsp::request::HoverRequest, _, _>(
5113 |params, _| async move {
5114 assert_eq!(
5115 params
5116 .text_document_position_params
5117 .text_document
5118 .uri
5119 .as_str(),
5120 "file:///root-1/main.rs"
5121 );
5122 assert_eq!(
5123 params.text_document_position_params.position,
5124 lsp::Position::new(0, 22)
5125 );
5126 Ok(Some(lsp::Hover {
5127 contents: lsp::HoverContents::Array(vec![
5128 lsp::MarkedString::String("Test hover content.".to_string()),
5129 lsp::MarkedString::LanguageString(lsp::LanguageString {
5130 language: "Rust".to_string(),
5131 value: "let foo = 42;".to_string(),
5132 }),
5133 ]),
5134 range: Some(lsp::Range::new(
5135 lsp::Position::new(0, 22),
5136 lsp::Position::new(0, 29),
5137 )),
5138 }))
5139 },
5140 ),
5141 );
5142 }
5143 unexpected => panic!("Unexpected server name: {unexpected}"),
5144 }
5145 }
5146
5147 // Request hover information as the guest.
5148 let mut hovers = project_b
5149 .update(cx_b, |p, cx| p.hover(&buffer_b, 22, cx))
5150 .await;
5151 assert_eq!(
5152 hovers.len(),
5153 2,
5154 "Expected two hovers from both language servers, but got: {hovers:?}"
5155 );
5156
5157 let _: Vec<()> = futures::future::join_all(servers_with_hover_requests.into_values().map(
5158 |mut hover_request| async move {
5159 hover_request
5160 .next()
5161 .await
5162 .expect("All hover requests should have been triggered")
5163 },
5164 ))
5165 .await;
5166
5167 hovers.sort_by_key(|hover| hover.contents.len());
5168 let first_hover = hovers.first().cloned().unwrap();
5169 assert_eq!(
5170 first_hover.contents,
5171 vec![project::HoverBlock {
5172 text: "CrabLang-ls hover".to_string(),
5173 kind: HoverBlockKind::Markdown,
5174 },]
5175 );
5176 let second_hover = hovers.last().cloned().unwrap();
5177 assert_eq!(
5178 second_hover.contents,
5179 vec![
5180 project::HoverBlock {
5181 text: "Test hover content.".to_string(),
5182 kind: HoverBlockKind::Markdown,
5183 },
5184 project::HoverBlock {
5185 text: "let foo = 42;".to_string(),
5186 kind: HoverBlockKind::Code {
5187 language: "Rust".to_string()
5188 },
5189 }
5190 ]
5191 );
5192 buffer_b.read_with(cx_b, |buffer, _| {
5193 let snapshot = buffer.snapshot();
5194 assert_eq!(second_hover.range.unwrap().to_offset(&snapshot), 22..29);
5195 });
5196}
5197
5198#[gpui::test(iterations = 10)]
5199async fn test_project_symbols(
5200 executor: BackgroundExecutor,
5201 cx_a: &mut TestAppContext,
5202 cx_b: &mut TestAppContext,
5203) {
5204 let mut server = TestServer::start(executor.clone()).await;
5205 let client_a = server.create_client(cx_a, "user_a").await;
5206 let client_b = server.create_client(cx_b, "user_b").await;
5207 server
5208 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
5209 .await;
5210 let active_call_a = cx_a.read(ActiveCall::global);
5211
5212 client_a.language_registry().add(rust_lang());
5213 let mut fake_language_servers = client_a
5214 .language_registry()
5215 .register_fake_lsp_adapter("Rust", Default::default());
5216
5217 client_a
5218 .fs()
5219 .insert_tree(
5220 "/code",
5221 json!({
5222 "crate-1": {
5223 "one.rs": "const ONE: usize = 1;",
5224 },
5225 "crate-2": {
5226 "two.rs": "const TWO: usize = 2; const THREE: usize = 3;",
5227 },
5228 "private": {
5229 "passwords.txt": "the-password",
5230 }
5231 }),
5232 )
5233 .await;
5234 let (project_a, worktree_id) = client_a.build_local_project("/code/crate-1", cx_a).await;
5235 let project_id = active_call_a
5236 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
5237 .await
5238 .unwrap();
5239 let project_b = client_b.build_remote_project(project_id, cx_b).await;
5240
5241 // Cause the language server to start.
5242 let open_buffer_task =
5243 project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "one.rs"), cx));
5244 let _buffer = cx_b.executor().spawn(open_buffer_task).await.unwrap();
5245
5246 let fake_language_server = fake_language_servers.next().await.unwrap();
5247 fake_language_server.handle_request::<lsp::WorkspaceSymbolRequest, _, _>(|_, _| async move {
5248 Ok(Some(lsp::WorkspaceSymbolResponse::Flat(vec![
5249 #[allow(deprecated)]
5250 lsp::SymbolInformation {
5251 name: "TWO".into(),
5252 location: lsp::Location {
5253 uri: lsp::Url::from_file_path("/code/crate-2/two.rs").unwrap(),
5254 range: lsp::Range::new(lsp::Position::new(0, 6), lsp::Position::new(0, 9)),
5255 },
5256 kind: lsp::SymbolKind::CONSTANT,
5257 tags: None,
5258 container_name: None,
5259 deprecated: None,
5260 },
5261 ])))
5262 });
5263
5264 // Request the definition of a symbol as the guest.
5265 let symbols = project_b
5266 .update(cx_b, |p, cx| p.symbols("two", cx))
5267 .await
5268 .unwrap();
5269 assert_eq!(symbols.len(), 1);
5270 assert_eq!(symbols[0].name, "TWO");
5271
5272 // Open one of the returned symbols.
5273 let buffer_b_2 = project_b
5274 .update(cx_b, |project, cx| {
5275 project.open_buffer_for_symbol(&symbols[0], cx)
5276 })
5277 .await
5278 .unwrap();
5279
5280 buffer_b_2.read_with(cx_b, |buffer, cx| {
5281 assert_eq!(
5282 buffer.file().unwrap().full_path(cx),
5283 Path::new("/code/crate-2/two.rs")
5284 );
5285 });
5286
5287 // Attempt to craft a symbol and violate host's privacy by opening an arbitrary file.
5288 let mut fake_symbol = symbols[0].clone();
5289 fake_symbol.path.path = Path::new("/code/secrets").into();
5290 let error = project_b
5291 .update(cx_b, |project, cx| {
5292 project.open_buffer_for_symbol(&fake_symbol, cx)
5293 })
5294 .await
5295 .unwrap_err();
5296 assert!(error.to_string().contains("invalid symbol signature"));
5297}
5298
5299#[gpui::test(iterations = 10)]
5300async fn test_open_buffer_while_getting_definition_pointing_to_it(
5301 executor: BackgroundExecutor,
5302 cx_a: &mut TestAppContext,
5303 cx_b: &mut TestAppContext,
5304 mut rng: StdRng,
5305) {
5306 let mut server = TestServer::start(executor.clone()).await;
5307 let client_a = server.create_client(cx_a, "user_a").await;
5308 let client_b = server.create_client(cx_b, "user_b").await;
5309 server
5310 .create_room(&mut [(&client_a, cx_a), (&client_b, cx_b)])
5311 .await;
5312 let active_call_a = cx_a.read(ActiveCall::global);
5313
5314 client_a.language_registry().add(rust_lang());
5315 let mut fake_language_servers = client_a
5316 .language_registry()
5317 .register_fake_lsp_adapter("Rust", Default::default());
5318
5319 client_a
5320 .fs()
5321 .insert_tree(
5322 "/root",
5323 json!({
5324 "a.rs": "const ONE: usize = b::TWO;",
5325 "b.rs": "const TWO: usize = 2",
5326 }),
5327 )
5328 .await;
5329 let (project_a, worktree_id) = client_a.build_local_project("/root", cx_a).await;
5330 let project_id = active_call_a
5331 .update(cx_a, |call, cx| call.share_project(project_a.clone(), cx))
5332 .await
5333 .unwrap();
5334 let project_b = client_b.build_remote_project(project_id, cx_b).await;
5335
5336 let open_buffer_task = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx));
5337 let buffer_b1 = cx_b.executor().spawn(open_buffer_task).await.unwrap();
5338
5339 let fake_language_server = fake_language_servers.next().await.unwrap();
5340 fake_language_server.handle_request::<lsp::request::GotoDefinition, _, _>(|_, _| async move {
5341 Ok(Some(lsp::GotoDefinitionResponse::Scalar(
5342 lsp::Location::new(
5343 lsp::Url::from_file_path("/root/b.rs").unwrap(),
5344 lsp::Range::new(lsp::Position::new(0, 6), lsp::Position::new(0, 9)),
5345 ),
5346 )))
5347 });
5348
5349 let definitions;
5350 let buffer_b2;
5351 if rng.gen() {
5352 definitions = project_b.update(cx_b, |p, cx| p.definition(&buffer_b1, 23, cx));
5353 buffer_b2 = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "b.rs"), cx));
5354 } else {
5355 buffer_b2 = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "b.rs"), cx));
5356 definitions = project_b.update(cx_b, |p, cx| p.definition(&buffer_b1, 23, cx));
5357 }
5358
5359 let buffer_b2 = buffer_b2.await.unwrap();
5360 let definitions = definitions.await.unwrap();
5361 assert_eq!(definitions.len(), 1);
5362 assert_eq!(definitions[0].target.buffer, buffer_b2);
5363}
5364
5365#[gpui::test(iterations = 10)]
5366async fn test_contacts(
5367 executor: BackgroundExecutor,
5368 cx_a: &mut TestAppContext,
5369 cx_b: &mut TestAppContext,
5370 cx_c: &mut TestAppContext,
5371 cx_d: &mut TestAppContext,
5372) {
5373 let mut server = TestServer::start(executor.clone()).await;
5374 let client_a = server.create_client(cx_a, "user_a").await;
5375 let client_b = server.create_client(cx_b, "user_b").await;
5376 let client_c = server.create_client(cx_c, "user_c").await;
5377 let client_d = server.create_client(cx_d, "user_d").await;
5378 server
5379 .make_contacts(&mut [(&client_a, cx_a), (&client_b, cx_b), (&client_c, cx_c)])
5380 .await;
5381 let active_call_a = cx_a.read(ActiveCall::global);
5382 let active_call_b = cx_b.read(ActiveCall::global);
5383 let active_call_c = cx_c.read(ActiveCall::global);
5384 let _active_call_d = cx_d.read(ActiveCall::global);
5385
5386 executor.run_until_parked();
5387 assert_eq!(
5388 contacts(&client_a, cx_a),
5389 [
5390 ("user_b".to_string(), "online", "free"),
5391 ("user_c".to_string(), "online", "free")
5392 ]
5393 );
5394 assert_eq!(
5395 contacts(&client_b, cx_b),
5396 [
5397 ("user_a".to_string(), "online", "free"),
5398 ("user_c".to_string(), "online", "free")
5399 ]
5400 );
5401 assert_eq!(
5402 contacts(&client_c, cx_c),
5403 [
5404 ("user_a".to_string(), "online", "free"),
5405 ("user_b".to_string(), "online", "free")
5406 ]
5407 );
5408 assert_eq!(contacts(&client_d, cx_d), []);
5409
5410 server.disconnect_client(client_c.peer_id().unwrap());
5411 server.forbid_connections();
5412 executor.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
5413 assert_eq!(
5414 contacts(&client_a, cx_a),
5415 [
5416 ("user_b".to_string(), "online", "free"),
5417 ("user_c".to_string(), "offline", "free")
5418 ]
5419 );
5420 assert_eq!(
5421 contacts(&client_b, cx_b),
5422 [
5423 ("user_a".to_string(), "online", "free"),
5424 ("user_c".to_string(), "offline", "free")
5425 ]
5426 );
5427 assert_eq!(contacts(&client_c, cx_c), []);
5428 assert_eq!(contacts(&client_d, cx_d), []);
5429
5430 server.allow_connections();
5431 client_c
5432 .authenticate_and_connect(false, &cx_c.to_async())
5433 .await
5434 .unwrap();
5435
5436 executor.run_until_parked();
5437 assert_eq!(
5438 contacts(&client_a, cx_a),
5439 [
5440 ("user_b".to_string(), "online", "free"),
5441 ("user_c".to_string(), "online", "free")
5442 ]
5443 );
5444 assert_eq!(
5445 contacts(&client_b, cx_b),
5446 [
5447 ("user_a".to_string(), "online", "free"),
5448 ("user_c".to_string(), "online", "free")
5449 ]
5450 );
5451 assert_eq!(
5452 contacts(&client_c, cx_c),
5453 [
5454 ("user_a".to_string(), "online", "free"),
5455 ("user_b".to_string(), "online", "free")
5456 ]
5457 );
5458 assert_eq!(contacts(&client_d, cx_d), []);
5459
5460 active_call_a
5461 .update(cx_a, |call, cx| {
5462 call.invite(client_b.user_id().unwrap(), None, cx)
5463 })
5464 .await
5465 .unwrap();
5466 executor.run_until_parked();
5467 assert_eq!(
5468 contacts(&client_a, cx_a),
5469 [
5470 ("user_b".to_string(), "online", "busy"),
5471 ("user_c".to_string(), "online", "free")
5472 ]
5473 );
5474 assert_eq!(
5475 contacts(&client_b, cx_b),
5476 [
5477 ("user_a".to_string(), "online", "busy"),
5478 ("user_c".to_string(), "online", "free")
5479 ]
5480 );
5481 assert_eq!(
5482 contacts(&client_c, cx_c),
5483 [
5484 ("user_a".to_string(), "online", "busy"),
5485 ("user_b".to_string(), "online", "busy")
5486 ]
5487 );
5488 assert_eq!(contacts(&client_d, cx_d), []);
5489
5490 // Client B and client D become contacts while client B is being called.
5491 server
5492 .make_contacts(&mut [(&client_b, cx_b), (&client_d, cx_d)])
5493 .await;
5494 executor.run_until_parked();
5495 assert_eq!(
5496 contacts(&client_a, cx_a),
5497 [
5498 ("user_b".to_string(), "online", "busy"),
5499 ("user_c".to_string(), "online", "free")
5500 ]
5501 );
5502 assert_eq!(
5503 contacts(&client_b, cx_b),
5504 [
5505 ("user_a".to_string(), "online", "busy"),
5506 ("user_c".to_string(), "online", "free"),
5507 ("user_d".to_string(), "online", "free"),
5508 ]
5509 );
5510 assert_eq!(
5511 contacts(&client_c, cx_c),
5512 [
5513 ("user_a".to_string(), "online", "busy"),
5514 ("user_b".to_string(), "online", "busy")
5515 ]
5516 );
5517 assert_eq!(
5518 contacts(&client_d, cx_d),
5519 [("user_b".to_string(), "online", "busy")]
5520 );
5521
5522 active_call_b.update(cx_b, |call, cx| call.decline_incoming(cx).unwrap());
5523 executor.run_until_parked();
5524 assert_eq!(
5525 contacts(&client_a, cx_a),
5526 [
5527 ("user_b".to_string(), "online", "free"),
5528 ("user_c".to_string(), "online", "free")
5529 ]
5530 );
5531 assert_eq!(
5532 contacts(&client_b, cx_b),
5533 [
5534 ("user_a".to_string(), "online", "free"),
5535 ("user_c".to_string(), "online", "free"),
5536 ("user_d".to_string(), "online", "free")
5537 ]
5538 );
5539 assert_eq!(
5540 contacts(&client_c, cx_c),
5541 [
5542 ("user_a".to_string(), "online", "free"),
5543 ("user_b".to_string(), "online", "free")
5544 ]
5545 );
5546 assert_eq!(
5547 contacts(&client_d, cx_d),
5548 [("user_b".to_string(), "online", "free")]
5549 );
5550
5551 active_call_c
5552 .update(cx_c, |call, cx| {
5553 call.invite(client_a.user_id().unwrap(), None, cx)
5554 })
5555 .await
5556 .unwrap();
5557 executor.run_until_parked();
5558 assert_eq!(
5559 contacts(&client_a, cx_a),
5560 [
5561 ("user_b".to_string(), "online", "free"),
5562 ("user_c".to_string(), "online", "busy")
5563 ]
5564 );
5565 assert_eq!(
5566 contacts(&client_b, cx_b),
5567 [
5568 ("user_a".to_string(), "online", "busy"),
5569 ("user_c".to_string(), "online", "busy"),
5570 ("user_d".to_string(), "online", "free")
5571 ]
5572 );
5573 assert_eq!(
5574 contacts(&client_c, cx_c),
5575 [
5576 ("user_a".to_string(), "online", "busy"),
5577 ("user_b".to_string(), "online", "free")
5578 ]
5579 );
5580 assert_eq!(
5581 contacts(&client_d, cx_d),
5582 [("user_b".to_string(), "online", "free")]
5583 );
5584
5585 active_call_a
5586 .update(cx_a, |call, cx| call.accept_incoming(cx))
5587 .await
5588 .unwrap();
5589 executor.run_until_parked();
5590 assert_eq!(
5591 contacts(&client_a, cx_a),
5592 [
5593 ("user_b".to_string(), "online", "free"),
5594 ("user_c".to_string(), "online", "busy")
5595 ]
5596 );
5597 assert_eq!(
5598 contacts(&client_b, cx_b),
5599 [
5600 ("user_a".to_string(), "online", "busy"),
5601 ("user_c".to_string(), "online", "busy"),
5602 ("user_d".to_string(), "online", "free")
5603 ]
5604 );
5605 assert_eq!(
5606 contacts(&client_c, cx_c),
5607 [
5608 ("user_a".to_string(), "online", "busy"),
5609 ("user_b".to_string(), "online", "free")
5610 ]
5611 );
5612 assert_eq!(
5613 contacts(&client_d, cx_d),
5614 [("user_b".to_string(), "online", "free")]
5615 );
5616
5617 active_call_a
5618 .update(cx_a, |call, cx| {
5619 call.invite(client_b.user_id().unwrap(), None, cx)
5620 })
5621 .await
5622 .unwrap();
5623 executor.run_until_parked();
5624 assert_eq!(
5625 contacts(&client_a, cx_a),
5626 [
5627 ("user_b".to_string(), "online", "busy"),
5628 ("user_c".to_string(), "online", "busy")
5629 ]
5630 );
5631 assert_eq!(
5632 contacts(&client_b, cx_b),
5633 [
5634 ("user_a".to_string(), "online", "busy"),
5635 ("user_c".to_string(), "online", "busy"),
5636 ("user_d".to_string(), "online", "free")
5637 ]
5638 );
5639 assert_eq!(
5640 contacts(&client_c, cx_c),
5641 [
5642 ("user_a".to_string(), "online", "busy"),
5643 ("user_b".to_string(), "online", "busy")
5644 ]
5645 );
5646 assert_eq!(
5647 contacts(&client_d, cx_d),
5648 [("user_b".to_string(), "online", "busy")]
5649 );
5650
5651 active_call_a
5652 .update(cx_a, |call, cx| call.hang_up(cx))
5653 .await
5654 .unwrap();
5655 executor.run_until_parked();
5656 assert_eq!(
5657 contacts(&client_a, cx_a),
5658 [
5659 ("user_b".to_string(), "online", "free"),
5660 ("user_c".to_string(), "online", "free")
5661 ]
5662 );
5663 assert_eq!(
5664 contacts(&client_b, cx_b),
5665 [
5666 ("user_a".to_string(), "online", "free"),
5667 ("user_c".to_string(), "online", "free"),
5668 ("user_d".to_string(), "online", "free")
5669 ]
5670 );
5671 assert_eq!(
5672 contacts(&client_c, cx_c),
5673 [
5674 ("user_a".to_string(), "online", "free"),
5675 ("user_b".to_string(), "online", "free")
5676 ]
5677 );
5678 assert_eq!(
5679 contacts(&client_d, cx_d),
5680 [("user_b".to_string(), "online", "free")]
5681 );
5682
5683 active_call_a
5684 .update(cx_a, |call, cx| {
5685 call.invite(client_b.user_id().unwrap(), None, cx)
5686 })
5687 .await
5688 .unwrap();
5689 executor.run_until_parked();
5690 assert_eq!(
5691 contacts(&client_a, cx_a),
5692 [
5693 ("user_b".to_string(), "online", "busy"),
5694 ("user_c".to_string(), "online", "free")
5695 ]
5696 );
5697 assert_eq!(
5698 contacts(&client_b, cx_b),
5699 [
5700 ("user_a".to_string(), "online", "busy"),
5701 ("user_c".to_string(), "online", "free"),
5702 ("user_d".to_string(), "online", "free")
5703 ]
5704 );
5705 assert_eq!(
5706 contacts(&client_c, cx_c),
5707 [
5708 ("user_a".to_string(), "online", "busy"),
5709 ("user_b".to_string(), "online", "busy")
5710 ]
5711 );
5712 assert_eq!(
5713 contacts(&client_d, cx_d),
5714 [("user_b".to_string(), "online", "busy")]
5715 );
5716
5717 server.forbid_connections();
5718 server.disconnect_client(client_a.peer_id().unwrap());
5719 executor.advance_clock(RECEIVE_TIMEOUT + RECONNECT_TIMEOUT);
5720 assert_eq!(contacts(&client_a, cx_a), []);
5721 assert_eq!(
5722 contacts(&client_b, cx_b),
5723 [
5724 ("user_a".to_string(), "offline", "free"),
5725 ("user_c".to_string(), "online", "free"),
5726 ("user_d".to_string(), "online", "free")
5727 ]
5728 );
5729 assert_eq!(
5730 contacts(&client_c, cx_c),
5731 [
5732 ("user_a".to_string(), "offline", "free"),
5733 ("user_b".to_string(), "online", "free")
5734 ]
5735 );
5736 assert_eq!(
5737 contacts(&client_d, cx_d),
5738 [("user_b".to_string(), "online", "free")]
5739 );
5740
5741 // Test removing a contact
5742 client_b
5743 .user_store()
5744 .update(cx_b, |store, cx| {
5745 store.remove_contact(client_c.user_id().unwrap(), cx)
5746 })
5747 .await
5748 .unwrap();
5749 executor.run_until_parked();
5750 assert_eq!(
5751 contacts(&client_b, cx_b),
5752 [
5753 ("user_a".to_string(), "offline", "free"),
5754 ("user_d".to_string(), "online", "free")
5755 ]
5756 );
5757 assert_eq!(
5758 contacts(&client_c, cx_c),
5759 [("user_a".to_string(), "offline", "free"),]
5760 );
5761
5762 fn contacts(
5763 client: &TestClient,
5764 cx: &TestAppContext,
5765 ) -> Vec<(String, &'static str, &'static str)> {
5766 client.user_store().read_with(cx, |store, _| {
5767 store
5768 .contacts()
5769 .iter()
5770 .map(|contact| {
5771 (
5772 contact.user.github_login.clone(),
5773 if contact.online { "online" } else { "offline" },
5774 if contact.busy { "busy" } else { "free" },
5775 )
5776 })
5777 .collect()
5778 })
5779 }
5780}
5781
5782#[gpui::test(iterations = 10)]
5783async fn test_contact_requests(
5784 executor: BackgroundExecutor,
5785 cx_a: &mut TestAppContext,
5786 cx_a2: &mut TestAppContext,
5787 cx_b: &mut TestAppContext,
5788 cx_b2: &mut TestAppContext,
5789 cx_c: &mut TestAppContext,
5790 cx_c2: &mut TestAppContext,
5791) {
5792 // Connect to a server as 3 clients.
5793 let mut server = TestServer::start(executor.clone()).await;
5794 let client_a = server.create_client(cx_a, "user_a").await;
5795 let client_a2 = server.create_client(cx_a2, "user_a").await;
5796 let client_b = server.create_client(cx_b, "user_b").await;
5797 let client_b2 = server.create_client(cx_b2, "user_b").await;
5798 let client_c = server.create_client(cx_c, "user_c").await;
5799 let client_c2 = server.create_client(cx_c2, "user_c").await;
5800
5801 assert_eq!(client_a.user_id().unwrap(), client_a2.user_id().unwrap());
5802 assert_eq!(client_b.user_id().unwrap(), client_b2.user_id().unwrap());
5803 assert_eq!(client_c.user_id().unwrap(), client_c2.user_id().unwrap());
5804
5805 // User A and User C request that user B become their contact.
5806 client_a
5807 .user_store()
5808 .update(cx_a, |store, cx| {
5809 store.request_contact(client_b.user_id().unwrap(), cx)
5810 })
5811 .await
5812 .unwrap();
5813 client_c
5814 .user_store()
5815 .update(cx_c, |store, cx| {
5816 store.request_contact(client_b.user_id().unwrap(), cx)
5817 })
5818 .await
5819 .unwrap();
5820 executor.run_until_parked();
5821
5822 // All users see the pending request appear in all their clients.
5823 assert_eq!(
5824 client_a.summarize_contacts(cx_a).outgoing_requests,
5825 &["user_b"]
5826 );
5827 assert_eq!(
5828 client_a2.summarize_contacts(cx_a2).outgoing_requests,
5829 &["user_b"]
5830 );
5831 assert_eq!(
5832 client_b.summarize_contacts(cx_b).incoming_requests,
5833 &["user_a", "user_c"]
5834 );
5835 assert_eq!(
5836 client_b2.summarize_contacts(cx_b2).incoming_requests,
5837 &["user_a", "user_c"]
5838 );
5839 assert_eq!(
5840 client_c.summarize_contacts(cx_c).outgoing_requests,
5841 &["user_b"]
5842 );
5843 assert_eq!(
5844 client_c2.summarize_contacts(cx_c2).outgoing_requests,
5845 &["user_b"]
5846 );
5847
5848 // Contact requests are present upon connecting (tested here via disconnect/reconnect)
5849 disconnect_and_reconnect(&client_a, cx_a).await;
5850 disconnect_and_reconnect(&client_b, cx_b).await;
5851 disconnect_and_reconnect(&client_c, cx_c).await;
5852 executor.run_until_parked();
5853 assert_eq!(
5854 client_a.summarize_contacts(cx_a).outgoing_requests,
5855 &["user_b"]
5856 );
5857 assert_eq!(
5858 client_b.summarize_contacts(cx_b).incoming_requests,
5859 &["user_a", "user_c"]
5860 );
5861 assert_eq!(
5862 client_c.summarize_contacts(cx_c).outgoing_requests,
5863 &["user_b"]
5864 );
5865
5866 // User B accepts the request from user A.
5867 client_b
5868 .user_store()
5869 .update(cx_b, |store, cx| {
5870 store.respond_to_contact_request(client_a.user_id().unwrap(), true, cx)
5871 })
5872 .await
5873 .unwrap();
5874
5875 executor.run_until_parked();
5876
5877 // User B sees user A as their contact now in all client, and the incoming request from them is removed.
5878 let contacts_b = client_b.summarize_contacts(cx_b);
5879 assert_eq!(contacts_b.current, &["user_a"]);
5880 assert_eq!(contacts_b.incoming_requests, &["user_c"]);
5881 let contacts_b2 = client_b2.summarize_contacts(cx_b2);
5882 assert_eq!(contacts_b2.current, &["user_a"]);
5883 assert_eq!(contacts_b2.incoming_requests, &["user_c"]);
5884
5885 // User A sees user B as their contact now in all clients, and the outgoing request to them is removed.
5886 let contacts_a = client_a.summarize_contacts(cx_a);
5887 assert_eq!(contacts_a.current, &["user_b"]);
5888 assert!(contacts_a.outgoing_requests.is_empty());
5889 let contacts_a2 = client_a2.summarize_contacts(cx_a2);
5890 assert_eq!(contacts_a2.current, &["user_b"]);
5891 assert!(contacts_a2.outgoing_requests.is_empty());
5892
5893 // Contacts are present upon connecting (tested here via disconnect/reconnect)
5894 disconnect_and_reconnect(&client_a, cx_a).await;
5895 disconnect_and_reconnect(&client_b, cx_b).await;
5896 disconnect_and_reconnect(&client_c, cx_c).await;
5897 executor.run_until_parked();
5898 assert_eq!(client_a.summarize_contacts(cx_a).current, &["user_b"]);
5899 assert_eq!(client_b.summarize_contacts(cx_b).current, &["user_a"]);
5900 assert_eq!(
5901 client_b.summarize_contacts(cx_b).incoming_requests,
5902 &["user_c"]
5903 );
5904 assert!(client_c.summarize_contacts(cx_c).current.is_empty());
5905 assert_eq!(
5906 client_c.summarize_contacts(cx_c).outgoing_requests,
5907 &["user_b"]
5908 );
5909
5910 // User B rejects the request from user C.
5911 client_b
5912 .user_store()
5913 .update(cx_b, |store, cx| {
5914 store.respond_to_contact_request(client_c.user_id().unwrap(), false, cx)
5915 })
5916 .await
5917 .unwrap();
5918
5919 executor.run_until_parked();
5920
5921 // User B doesn't see user C as their contact, and the incoming request from them is removed.
5922 let contacts_b = client_b.summarize_contacts(cx_b);
5923 assert_eq!(contacts_b.current, &["user_a"]);
5924 assert!(contacts_b.incoming_requests.is_empty());
5925 let contacts_b2 = client_b2.summarize_contacts(cx_b2);
5926 assert_eq!(contacts_b2.current, &["user_a"]);
5927 assert!(contacts_b2.incoming_requests.is_empty());
5928
5929 // User C doesn't see user B as their contact, and the outgoing request to them is removed.
5930 let contacts_c = client_c.summarize_contacts(cx_c);
5931 assert!(contacts_c.current.is_empty());
5932 assert!(contacts_c.outgoing_requests.is_empty());
5933 let contacts_c2 = client_c2.summarize_contacts(cx_c2);
5934 assert!(contacts_c2.current.is_empty());
5935 assert!(contacts_c2.outgoing_requests.is_empty());
5936
5937 // Incoming/outgoing requests are not present upon connecting (tested here via disconnect/reconnect)
5938 disconnect_and_reconnect(&client_a, cx_a).await;
5939 disconnect_and_reconnect(&client_b, cx_b).await;
5940 disconnect_and_reconnect(&client_c, cx_c).await;
5941 executor.run_until_parked();
5942 assert_eq!(client_a.summarize_contacts(cx_a).current, &["user_b"]);
5943 assert_eq!(client_b.summarize_contacts(cx_b).current, &["user_a"]);
5944 assert!(client_b
5945 .summarize_contacts(cx_b)
5946 .incoming_requests
5947 .is_empty());
5948 assert!(client_c.summarize_contacts(cx_c).current.is_empty());
5949 assert!(client_c
5950 .summarize_contacts(cx_c)
5951 .outgoing_requests
5952 .is_empty());
5953
5954 async fn disconnect_and_reconnect(client: &TestClient, cx: &mut TestAppContext) {
5955 client.disconnect(&cx.to_async());
5956 client.clear_contacts(cx).await;
5957 client
5958 .authenticate_and_connect(false, &cx.to_async())
5959 .await
5960 .unwrap();
5961 }
5962}
5963
5964#[gpui::test(iterations = 10)]
5965async fn test_join_call_after_screen_was_shared(
5966 executor: BackgroundExecutor,
5967 cx_a: &mut TestAppContext,
5968 cx_b: &mut TestAppContext,
5969) {
5970 let mut server = TestServer::start(executor.clone()).await;
5971
5972 let client_a = server.create_client(cx_a, "user_a").await;
5973 let client_b = server.create_client(cx_b, "user_b").await;
5974 server
5975 .make_contacts(&mut [(&client_a, cx_a), (&client_b, cx_b)])
5976 .await;
5977
5978 let active_call_a = cx_a.read(ActiveCall::global);
5979 let active_call_b = cx_b.read(ActiveCall::global);
5980
5981 // Call users B and C from client A.
5982 active_call_a
5983 .update(cx_a, |call, cx| {
5984 call.invite(client_b.user_id().unwrap(), None, cx)
5985 })
5986 .await
5987 .unwrap();
5988
5989 let room_a = active_call_a.read_with(cx_a, |call, _| call.room().unwrap().clone());
5990 executor.run_until_parked();
5991 assert_eq!(
5992 room_participants(&room_a, cx_a),
5993 RoomParticipants {
5994 remote: Default::default(),
5995 pending: vec!["user_b".to_string()]
5996 }
5997 );
5998
5999 // User B receives the call.
6000
6001 let mut incoming_call_b = active_call_b.read_with(cx_b, |call, _| call.incoming());
6002 let call_b = incoming_call_b.next().await.unwrap().unwrap();
6003 assert_eq!(call_b.calling_user.github_login, "user_a");
6004
6005 // User A shares their screen
6006 let display = MacOSDisplay::new();
6007 active_call_a
6008 .update(cx_a, |call, cx| {
6009 call.room().unwrap().update(cx, |room, cx| {
6010 room.set_display_sources(vec![display.clone()]);
6011 room.share_screen(cx)
6012 })
6013 })
6014 .await
6015 .unwrap();
6016
6017 client_b.user_store().update(cx_b, |user_store, _| {
6018 user_store.clear_cache();
6019 });
6020
6021 // User B joins the room
6022 active_call_b
6023 .update(cx_b, |call, cx| call.accept_incoming(cx))
6024 .await
6025 .unwrap();
6026
6027 let room_b = active_call_b.read_with(cx_b, |call, _| call.room().unwrap().clone());
6028 assert!(incoming_call_b.next().await.unwrap().is_none());
6029
6030 executor.run_until_parked();
6031 assert_eq!(
6032 room_participants(&room_a, cx_a),
6033 RoomParticipants {
6034 remote: vec!["user_b".to_string()],
6035 pending: vec![],
6036 }
6037 );
6038 assert_eq!(
6039 room_participants(&room_b, cx_b),
6040 RoomParticipants {
6041 remote: vec!["user_a".to_string()],
6042 pending: vec![],
6043 }
6044 );
6045
6046 // Ensure User B sees User A's screenshare.
6047
6048 room_b.read_with(cx_b, |room, _| {
6049 assert_eq!(
6050 room.remote_participants()
6051 .get(&client_a.user_id().unwrap())
6052 .unwrap()
6053 .video_tracks
6054 .len(),
6055 1
6056 );
6057 });
6058}
6059
6060#[gpui::test]
6061async fn test_right_click_menu_behind_collab_panel(cx: &mut TestAppContext) {
6062 let mut server = TestServer::start(cx.executor().clone()).await;
6063 let client_a = server.create_client(cx, "user_a").await;
6064 let (_workspace_a, cx) = client_a.build_test_workspace(cx).await;
6065
6066 cx.simulate_resize(size(px(300.), px(300.)));
6067
6068 cx.simulate_keystrokes("cmd-n cmd-n cmd-n");
6069 cx.update(|cx| cx.refresh());
6070
6071 let tab_bounds = cx.debug_bounds("TAB-2").unwrap();
6072 let new_tab_button_bounds = cx.debug_bounds("ICON-Plus").unwrap();
6073
6074 assert!(
6075 tab_bounds.intersects(&new_tab_button_bounds),
6076 "Tab should overlap with the new tab button, if this is failing check if there's been a redesign!"
6077 );
6078
6079 cx.simulate_event(MouseDownEvent {
6080 button: MouseButton::Right,
6081 position: new_tab_button_bounds.center(),
6082 modifiers: Modifiers::default(),
6083 click_count: 1,
6084 first_mouse: false,
6085 });
6086
6087 // regression test that the right click menu for tabs does not open.
6088 assert!(cx.debug_bounds("MENU_ITEM-Close").is_none());
6089
6090 let tab_bounds = cx.debug_bounds("TAB-1").unwrap();
6091 cx.simulate_event(MouseDownEvent {
6092 button: MouseButton::Right,
6093 position: tab_bounds.center(),
6094 modifiers: Modifiers::default(),
6095 click_count: 1,
6096 first_mouse: false,
6097 });
6098 assert!(cx.debug_bounds("MENU_ITEM-Close").is_some());
6099}
6100
6101#[gpui::test]
6102async fn test_cmd_k_left(cx: &mut TestAppContext) {
6103 let (_, client) = TestServer::start1(cx).await;
6104 let (workspace, cx) = client.build_test_workspace(cx).await;
6105
6106 cx.simulate_keystrokes("cmd-n");
6107 workspace.update(cx, |workspace, cx| {
6108 assert!(workspace.items(cx).collect::<Vec<_>>().len() == 1);
6109 });
6110 cx.simulate_keystrokes("cmd-k left");
6111 workspace.update(cx, |workspace, cx| {
6112 assert!(workspace.items(cx).collect::<Vec<_>>().len() == 2);
6113 });
6114 cx.simulate_keystrokes("cmd-k");
6115 // sleep for longer than the timeout in keyboard shortcut handling
6116 // to verify that it doesn't fire in this case.
6117 cx.executor().advance_clock(Duration::from_secs(2));
6118 cx.simulate_keystrokes("left");
6119 workspace.update(cx, |workspace, cx| {
6120 assert!(workspace.items(cx).collect::<Vec<_>>().len() == 2);
6121 });
6122}
6123
6124#[gpui::test]
6125async fn test_join_after_restart(cx1: &mut TestAppContext, cx2: &mut TestAppContext) {
6126 let (mut server, client) = TestServer::start1(cx1).await;
6127 let channel1 = server.make_public_channel("channel1", &client, cx1).await;
6128 let channel2 = server.make_public_channel("channel2", &client, cx1).await;
6129
6130 join_channel(channel1, &client, cx1).await.unwrap();
6131 drop(client);
6132
6133 let client2 = server.create_client(cx2, "user_a").await;
6134 join_channel(channel2, &client2, cx2).await.unwrap();
6135}
6136
6137#[gpui::test]
6138async fn test_preview_tabs(cx: &mut TestAppContext) {
6139 let (_server, client) = TestServer::start1(cx).await;
6140 let (workspace, cx) = client.build_test_workspace(cx).await;
6141 let project = workspace.update(cx, |workspace, _| workspace.project().clone());
6142
6143 let worktree_id = project.update(cx, |project, cx| {
6144 project.worktrees().next().unwrap().read(cx).id()
6145 });
6146
6147 let path_1 = ProjectPath {
6148 worktree_id,
6149 path: Path::new("1.txt").into(),
6150 };
6151 let path_2 = ProjectPath {
6152 worktree_id,
6153 path: Path::new("2.js").into(),
6154 };
6155 let path_3 = ProjectPath {
6156 worktree_id,
6157 path: Path::new("3.rs").into(),
6158 };
6159
6160 let pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
6161
6162 let get_path = |pane: &Pane, idx: usize, cx: &AppContext| {
6163 pane.item_for_index(idx).unwrap().project_path(cx).unwrap()
6164 };
6165
6166 // Opening item 3 as a "permanent" tab
6167 workspace
6168 .update(cx, |workspace, cx| {
6169 workspace.open_path(path_3.clone(), None, false, cx)
6170 })
6171 .await
6172 .unwrap();
6173
6174 pane.update(cx, |pane, cx| {
6175 assert_eq!(pane.items_len(), 1);
6176 assert_eq!(get_path(pane, 0, cx), path_3.clone());
6177 assert_eq!(pane.preview_item_id(), None);
6178
6179 assert!(!pane.can_navigate_backward());
6180 assert!(!pane.can_navigate_forward());
6181 });
6182
6183 // Open item 1 as preview
6184 workspace
6185 .update(cx, |workspace, cx| {
6186 workspace.open_path_preview(path_1.clone(), None, true, true, cx)
6187 })
6188 .await
6189 .unwrap();
6190
6191 pane.update(cx, |pane, cx| {
6192 assert_eq!(pane.items_len(), 2);
6193 assert_eq!(get_path(pane, 0, cx), path_3.clone());
6194 assert_eq!(get_path(pane, 1, cx), path_1.clone());
6195 assert_eq!(
6196 pane.preview_item_id(),
6197 Some(pane.items().nth(1).unwrap().item_id())
6198 );
6199
6200 assert!(pane.can_navigate_backward());
6201 assert!(!pane.can_navigate_forward());
6202 });
6203
6204 // Open item 2 as preview
6205 workspace
6206 .update(cx, |workspace, cx| {
6207 workspace.open_path_preview(path_2.clone(), None, true, true, cx)
6208 })
6209 .await
6210 .unwrap();
6211
6212 pane.update(cx, |pane, cx| {
6213 assert_eq!(pane.items_len(), 2);
6214 assert_eq!(get_path(pane, 0, cx), path_3.clone());
6215 assert_eq!(get_path(pane, 1, cx), path_2.clone());
6216 assert_eq!(
6217 pane.preview_item_id(),
6218 Some(pane.items().nth(1).unwrap().item_id())
6219 );
6220
6221 assert!(pane.can_navigate_backward());
6222 assert!(!pane.can_navigate_forward());
6223 });
6224
6225 // Going back should show item 1 as preview
6226 workspace
6227 .update(cx, |workspace, cx| workspace.go_back(pane.downgrade(), cx))
6228 .await
6229 .unwrap();
6230
6231 pane.update(cx, |pane, cx| {
6232 assert_eq!(pane.items_len(), 2);
6233 assert_eq!(get_path(pane, 0, cx), path_3.clone());
6234 assert_eq!(get_path(pane, 1, cx), path_1.clone());
6235 assert_eq!(
6236 pane.preview_item_id(),
6237 Some(pane.items().nth(1).unwrap().item_id())
6238 );
6239
6240 assert!(pane.can_navigate_backward());
6241 assert!(pane.can_navigate_forward());
6242 });
6243
6244 // Closing item 1
6245 pane.update(cx, |pane, cx| {
6246 pane.close_item_by_id(
6247 pane.active_item().unwrap().item_id(),
6248 workspace::SaveIntent::Skip,
6249 cx,
6250 )
6251 })
6252 .await
6253 .unwrap();
6254
6255 pane.update(cx, |pane, cx| {
6256 assert_eq!(pane.items_len(), 1);
6257 assert_eq!(get_path(pane, 0, cx), path_3.clone());
6258 assert_eq!(pane.preview_item_id(), None);
6259
6260 assert!(pane.can_navigate_backward());
6261 assert!(!pane.can_navigate_forward());
6262 });
6263
6264 // Going back should show item 1 as preview
6265 workspace
6266 .update(cx, |workspace, cx| workspace.go_back(pane.downgrade(), cx))
6267 .await
6268 .unwrap();
6269
6270 pane.update(cx, |pane, cx| {
6271 assert_eq!(pane.items_len(), 2);
6272 assert_eq!(get_path(pane, 0, cx), path_3.clone());
6273 assert_eq!(get_path(pane, 1, cx), path_1.clone());
6274 assert_eq!(
6275 pane.preview_item_id(),
6276 Some(pane.items().nth(1).unwrap().item_id())
6277 );
6278
6279 assert!(pane.can_navigate_backward());
6280 assert!(pane.can_navigate_forward());
6281 });
6282
6283 // Close permanent tab
6284 pane.update(cx, |pane, cx| {
6285 let id = pane.items().nth(0).unwrap().item_id();
6286 pane.close_item_by_id(id, workspace::SaveIntent::Skip, cx)
6287 })
6288 .await
6289 .unwrap();
6290
6291 pane.update(cx, |pane, cx| {
6292 assert_eq!(pane.items_len(), 1);
6293 assert_eq!(get_path(pane, 0, cx), path_1.clone());
6294 assert_eq!(
6295 pane.preview_item_id(),
6296 Some(pane.items().nth(0).unwrap().item_id())
6297 );
6298
6299 assert!(pane.can_navigate_backward());
6300 assert!(pane.can_navigate_forward());
6301 });
6302
6303 // Split pane to the right
6304 pane.update(cx, |pane, cx| {
6305 pane.split(workspace::SplitDirection::Right, cx);
6306 });
6307
6308 let right_pane = workspace.update(cx, |workspace, _| workspace.active_pane().clone());
6309
6310 pane.update(cx, |pane, cx| {
6311 assert_eq!(pane.items_len(), 1);
6312 assert_eq!(get_path(pane, 0, cx), path_1.clone());
6313 assert_eq!(
6314 pane.preview_item_id(),
6315 Some(pane.items().nth(0).unwrap().item_id())
6316 );
6317
6318 assert!(pane.can_navigate_backward());
6319 assert!(pane.can_navigate_forward());
6320 });
6321
6322 right_pane.update(cx, |pane, cx| {
6323 assert_eq!(pane.items_len(), 1);
6324 assert_eq!(get_path(pane, 0, cx), path_1.clone());
6325 assert_eq!(pane.preview_item_id(), None);
6326
6327 assert!(!pane.can_navigate_backward());
6328 assert!(!pane.can_navigate_forward());
6329 });
6330
6331 // Open item 2 as preview in right pane
6332 workspace
6333 .update(cx, |workspace, cx| {
6334 workspace.open_path_preview(path_2.clone(), None, true, true, cx)
6335 })
6336 .await
6337 .unwrap();
6338
6339 pane.update(cx, |pane, cx| {
6340 assert_eq!(pane.items_len(), 1);
6341 assert_eq!(get_path(pane, 0, cx), path_1.clone());
6342 assert_eq!(
6343 pane.preview_item_id(),
6344 Some(pane.items().nth(0).unwrap().item_id())
6345 );
6346
6347 assert!(pane.can_navigate_backward());
6348 assert!(pane.can_navigate_forward());
6349 });
6350
6351 right_pane.update(cx, |pane, cx| {
6352 assert_eq!(pane.items_len(), 2);
6353 assert_eq!(get_path(pane, 0, cx), path_1.clone());
6354 assert_eq!(get_path(pane, 1, cx), path_2.clone());
6355 assert_eq!(
6356 pane.preview_item_id(),
6357 Some(pane.items().nth(1).unwrap().item_id())
6358 );
6359
6360 assert!(pane.can_navigate_backward());
6361 assert!(!pane.can_navigate_forward());
6362 });
6363
6364 // Focus left pane
6365 workspace.update(cx, |workspace, cx| {
6366 workspace.activate_pane_in_direction(workspace::SplitDirection::Left, cx)
6367 });
6368
6369 // Open item 2 as preview in left pane
6370 workspace
6371 .update(cx, |workspace, cx| {
6372 workspace.open_path_preview(path_2.clone(), None, true, true, cx)
6373 })
6374 .await
6375 .unwrap();
6376
6377 pane.update(cx, |pane, cx| {
6378 assert_eq!(pane.items_len(), 1);
6379 assert_eq!(get_path(pane, 0, cx), path_2.clone());
6380 assert_eq!(
6381 pane.preview_item_id(),
6382 Some(pane.items().nth(0).unwrap().item_id())
6383 );
6384
6385 assert!(pane.can_navigate_backward());
6386 assert!(!pane.can_navigate_forward());
6387 });
6388
6389 right_pane.update(cx, |pane, cx| {
6390 assert_eq!(pane.items_len(), 2);
6391 assert_eq!(get_path(pane, 0, cx), path_1.clone());
6392 assert_eq!(get_path(pane, 1, cx), path_2.clone());
6393 assert_eq!(
6394 pane.preview_item_id(),
6395 Some(pane.items().nth(1).unwrap().item_id())
6396 );
6397
6398 assert!(pane.can_navigate_backward());
6399 assert!(!pane.can_navigate_forward());
6400 });
6401}