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