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