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