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