1use crate::{
2 db::{tests::TestDb, ProjectId, UserId},
3 rpc::{Executor, Server, Store},
4 AppState,
5};
6use ::rpc::Peer;
7use anyhow::anyhow;
8use call::{room, ParticipantLocation, Room};
9use client::{
10 self, test::FakeHttpClient, Channel, ChannelDetails, ChannelList, Client, Connection,
11 Credentials, EstablishConnectionError, User, UserStore, RECEIVE_TIMEOUT,
12};
13use collections::{BTreeMap, HashMap, HashSet};
14use editor::{
15 self, ConfirmCodeAction, ConfirmCompletion, ConfirmRename, Editor, Redo, Rename, ToOffset,
16 ToggleCodeActions, Undo,
17};
18use futures::{channel::mpsc, Future, StreamExt as _};
19use gpui::{
20 executor::{self, Deterministic},
21 geometry::vector::vec2f,
22 test::EmptyView,
23 ModelHandle, Task, TestAppContext, ViewHandle,
24};
25use language::{
26 range_to_lsp, tree_sitter_rust, Diagnostic, DiagnosticEntry, FakeLspAdapter, Language,
27 LanguageConfig, LanguageRegistry, LineEnding, OffsetRangeExt, Point, Rope,
28};
29use lsp::{self, FakeLanguageServer};
30use parking_lot::Mutex;
31use project::{
32 fs::{FakeFs, Fs as _},
33 search::SearchQuery,
34 worktree::WorktreeHandle,
35 DiagnosticSummary, Project, ProjectPath, ProjectStore, WorktreeId,
36};
37use rand::prelude::*;
38use rpc::PeerId;
39use serde_json::json;
40use settings::{Formatter, Settings};
41use sqlx::types::time::OffsetDateTime;
42use std::{
43 cell::{Cell, RefCell},
44 env, mem,
45 ops::Deref,
46 path::{Path, PathBuf},
47 rc::Rc,
48 sync::{
49 atomic::{AtomicBool, Ordering::SeqCst},
50 Arc,
51 },
52 time::Duration,
53};
54use theme::ThemeRegistry;
55use workspace::{Item, SplitDirection, ToggleFollow, Workspace};
56
57#[ctor::ctor]
58fn init_logger() {
59 if std::env::var("RUST_LOG").is_ok() {
60 env_logger::init();
61 }
62}
63
64#[gpui::test(iterations = 10)]
65async fn test_basic_calls(
66 deterministic: Arc<Deterministic>,
67 cx_a: &mut TestAppContext,
68 cx_b: &mut TestAppContext,
69 cx_b2: &mut TestAppContext,
70 cx_c: &mut TestAppContext,
71) {
72 deterministic.forbid_parking();
73 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
74 let client_a = server.create_client(cx_a, "user_a").await;
75 let client_b = server.create_client(cx_b, "user_b").await;
76 let client_c = server.create_client(cx_c, "user_c").await;
77 server
78 .make_contacts(&mut [(&client_a, cx_a), (&client_b, cx_b), (&client_c, cx_c)])
79 .await;
80
81 let room_a = cx_a
82 .update(|cx| Room::create(client_a.clone(), client_a.user_store.clone(), cx))
83 .await
84 .unwrap();
85 assert_eq!(
86 room_participants(&room_a, cx_a),
87 RoomParticipants {
88 remote: Default::default(),
89 pending: Default::default()
90 }
91 );
92
93 // Call user B from client A.
94 let mut incoming_call_b = client_b
95 .user_store
96 .update(cx_b, |user, _| user.incoming_call());
97 room_a
98 .update(cx_a, |room, cx| {
99 room.call(client_b.user_id().unwrap(), None, cx)
100 })
101 .await
102 .unwrap();
103
104 deterministic.run_until_parked();
105 assert_eq!(
106 room_participants(&room_a, cx_a),
107 RoomParticipants {
108 remote: Default::default(),
109 pending: vec!["user_b".to_string()]
110 }
111 );
112
113 // User B receives the call.
114 let call_b = incoming_call_b.next().await.unwrap().unwrap();
115
116 // User B connects via another client and also receives a ring on the newly-connected client.
117 let client_b2 = server.create_client(cx_b2, "user_b").await;
118 let mut incoming_call_b2 = client_b2
119 .user_store
120 .update(cx_b2, |user, _| user.incoming_call());
121 deterministic.run_until_parked();
122 let _call_b2 = incoming_call_b2.next().await.unwrap().unwrap();
123
124 // User B joins the room using the first client.
125 let room_b = cx_b
126 .update(|cx| Room::join(&call_b, client_b.clone(), client_b.user_store.clone(), cx))
127 .await
128 .unwrap();
129 assert!(incoming_call_b.next().await.unwrap().is_none());
130
131 deterministic.run_until_parked();
132 assert_eq!(
133 room_participants(&room_a, cx_a),
134 RoomParticipants {
135 remote: vec!["user_b".to_string()],
136 pending: Default::default()
137 }
138 );
139 assert_eq!(
140 room_participants(&room_b, cx_b),
141 RoomParticipants {
142 remote: vec!["user_a".to_string()],
143 pending: Default::default()
144 }
145 );
146
147 // Call user C from client B.
148 let mut incoming_call_c = client_c
149 .user_store
150 .update(cx_c, |user, _| user.incoming_call());
151 room_b
152 .update(cx_b, |room, cx| {
153 room.call(client_c.user_id().unwrap(), None, cx)
154 })
155 .await
156 .unwrap();
157
158 deterministic.run_until_parked();
159 assert_eq!(
160 room_participants(&room_a, cx_a),
161 RoomParticipants {
162 remote: vec!["user_b".to_string()],
163 pending: vec!["user_c".to_string()]
164 }
165 );
166 assert_eq!(
167 room_participants(&room_b, cx_b),
168 RoomParticipants {
169 remote: vec!["user_a".to_string()],
170 pending: vec!["user_c".to_string()]
171 }
172 );
173
174 // User C receives the call, but declines it.
175 let _call_c = incoming_call_c.next().await.unwrap().unwrap();
176 client_c
177 .user_store
178 .update(cx_c, |user, _| user.decline_call())
179 .unwrap();
180 assert!(incoming_call_c.next().await.unwrap().is_none());
181
182 deterministic.run_until_parked();
183 assert_eq!(
184 room_participants(&room_a, cx_a),
185 RoomParticipants {
186 remote: vec!["user_b".to_string()],
187 pending: Default::default()
188 }
189 );
190 assert_eq!(
191 room_participants(&room_b, cx_b),
192 RoomParticipants {
193 remote: vec!["user_a".to_string()],
194 pending: Default::default()
195 }
196 );
197
198 // User A leaves the room.
199 room_a.update(cx_a, |room, cx| room.leave(cx)).unwrap();
200 deterministic.run_until_parked();
201 assert_eq!(
202 room_participants(&room_a, cx_a),
203 RoomParticipants {
204 remote: Default::default(),
205 pending: Default::default()
206 }
207 );
208 assert_eq!(
209 room_participants(&room_b, cx_b),
210 RoomParticipants {
211 remote: Default::default(),
212 pending: Default::default()
213 }
214 );
215}
216
217#[gpui::test(iterations = 10)]
218async fn test_leaving_room_on_disconnection(
219 deterministic: Arc<Deterministic>,
220 cx_a: &mut TestAppContext,
221 cx_b: &mut TestAppContext,
222) {
223 deterministic.forbid_parking();
224 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
225 let client_a = server.create_client(cx_a, "user_a").await;
226 let client_b = server.create_client(cx_b, "user_b").await;
227 server
228 .make_contacts(&mut [(&client_a, cx_a), (&client_b, cx_b)])
229 .await;
230
231 let room_a = cx_a
232 .update(|cx| Room::create(client_a.clone(), client_a.user_store.clone(), cx))
233 .await
234 .unwrap();
235
236 // Call user B from client A.
237 let mut incoming_call_b = client_b
238 .user_store
239 .update(cx_b, |user, _| user.incoming_call());
240 room_a
241 .update(cx_a, |room, cx| {
242 room.call(client_b.user_id().unwrap(), None, cx)
243 })
244 .await
245 .unwrap();
246
247 // User B receives the call and joins the room.
248 let call_b = incoming_call_b.next().await.unwrap().unwrap();
249 let room_b = cx_b
250 .update(|cx| Room::join(&call_b, client_b.clone(), client_b.user_store.clone(), cx))
251 .await
252 .unwrap();
253 deterministic.run_until_parked();
254 assert_eq!(
255 room_participants(&room_a, cx_a),
256 RoomParticipants {
257 remote: vec!["user_b".to_string()],
258 pending: Default::default()
259 }
260 );
261 assert_eq!(
262 room_participants(&room_b, cx_b),
263 RoomParticipants {
264 remote: vec!["user_a".to_string()],
265 pending: Default::default()
266 }
267 );
268
269 server.disconnect_client(client_a.current_user_id(cx_a));
270 cx_a.foreground().advance_clock(rpc::RECEIVE_TIMEOUT);
271 assert_eq!(
272 room_participants(&room_a, cx_a),
273 RoomParticipants {
274 remote: Default::default(),
275 pending: Default::default()
276 }
277 );
278 assert_eq!(
279 room_participants(&room_b, cx_b),
280 RoomParticipants {
281 remote: Default::default(),
282 pending: Default::default()
283 }
284 );
285}
286
287#[gpui::test(iterations = 10)]
288async fn test_share_project(
289 deterministic: Arc<Deterministic>,
290 cx_a: &mut TestAppContext,
291 cx_b: &mut TestAppContext,
292) {
293 cx_a.foreground().forbid_parking();
294 let (_, window_b) = cx_b.add_window(|_| EmptyView);
295 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
296 let client_a = server.create_client(cx_a, "user_a").await;
297 let client_b = server.create_client(cx_b, "user_b").await;
298 let (room_id, _rooms) = server
299 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
300 .await;
301
302 client_a
303 .fs
304 .insert_tree(
305 "/a",
306 json!({
307 ".gitignore": "ignored-dir",
308 "a.txt": "a-contents",
309 "b.txt": "b-contents",
310 "ignored-dir": {
311 "c.txt": "",
312 "d.txt": "",
313 }
314 }),
315 )
316 .await;
317
318 let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
319 let project_id = project_a
320 .update(cx_a, |project, cx| project.share(room_id, cx))
321 .await
322 .unwrap();
323
324 // Join that project as client B
325 let client_b_peer_id = client_b.peer_id;
326 let project_b = client_b.build_remote_project(project_id, cx_b).await;
327 let replica_id_b = project_b.read_with(cx_b, |project, _| project.replica_id());
328
329 deterministic.run_until_parked();
330 project_a.read_with(cx_a, |project, _| {
331 let client_b_collaborator = project.collaborators().get(&client_b_peer_id).unwrap();
332 assert_eq!(client_b_collaborator.replica_id, replica_id_b);
333 });
334 project_b.read_with(cx_b, |project, cx| {
335 let worktree = project.worktrees(cx).next().unwrap().read(cx);
336 assert_eq!(
337 worktree.paths().map(AsRef::as_ref).collect::<Vec<_>>(),
338 [
339 Path::new(".gitignore"),
340 Path::new("a.txt"),
341 Path::new("b.txt"),
342 Path::new("ignored-dir"),
343 Path::new("ignored-dir/c.txt"),
344 Path::new("ignored-dir/d.txt"),
345 ]
346 );
347 });
348
349 // Open the same file as client B and client A.
350 let buffer_b = project_b
351 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "b.txt"), cx))
352 .await
353 .unwrap();
354 buffer_b.read_with(cx_b, |buf, _| assert_eq!(buf.text(), "b-contents"));
355 project_a.read_with(cx_a, |project, cx| {
356 assert!(project.has_open_buffer((worktree_id, "b.txt"), cx))
357 });
358 let buffer_a = project_a
359 .update(cx_a, |p, cx| p.open_buffer((worktree_id, "b.txt"), cx))
360 .await
361 .unwrap();
362
363 let editor_b = cx_b.add_view(&window_b, |cx| Editor::for_buffer(buffer_b, None, cx));
364
365 // TODO
366 // // Create a selection set as client B and see that selection set as client A.
367 // buffer_a
368 // .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 1)
369 // .await;
370
371 // Edit the buffer as client B and see that edit as client A.
372 editor_b.update(cx_b, |editor, cx| editor.handle_input("ok, ", cx));
373 buffer_a
374 .condition(cx_a, |buffer, _| buffer.text() == "ok, b-contents")
375 .await;
376
377 // TODO
378 // // Remove the selection set as client B, see those selections disappear as client A.
379 cx_b.update(move |_| drop(editor_b));
380 // buffer_a
381 // .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 0)
382 // .await;
383}
384
385#[gpui::test(iterations = 10)]
386async fn test_unshare_project(
387 deterministic: Arc<Deterministic>,
388 cx_a: &mut TestAppContext,
389 cx_b: &mut TestAppContext,
390 cx_c: &mut TestAppContext,
391) {
392 deterministic.forbid_parking();
393 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
394 let client_a = server.create_client(cx_a, "user_a").await;
395 let client_b = server.create_client(cx_b, "user_b").await;
396 let client_c = server.create_client(cx_c, "user_c").await;
397 let (room_id, mut rooms) = server
398 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b), (&client_c, cx_c)])
399 .await;
400
401 client_a
402 .fs
403 .insert_tree(
404 "/a",
405 json!({
406 "a.txt": "a-contents",
407 "b.txt": "b-contents",
408 }),
409 )
410 .await;
411
412 let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
413 let project_id = project_a
414 .update(cx_a, |project, cx| project.share(room_id, cx))
415 .await
416 .unwrap();
417 let worktree_a = project_a.read_with(cx_a, |project, cx| project.worktrees(cx).next().unwrap());
418 let project_b = client_b.build_remote_project(project_id, cx_b).await;
419 assert!(worktree_a.read_with(cx_a, |tree, _| tree.as_local().unwrap().is_shared()));
420
421 project_b
422 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
423 .await
424 .unwrap();
425
426 // When client B leaves the room, the project becomes read-only.
427 cx_b.update(|_| drop(rooms.remove(1)));
428 deterministic.run_until_parked();
429 assert!(project_b.read_with(cx_b, |project, _| project.is_read_only()));
430
431 // Client C opens the project.
432 let project_c = client_c.build_remote_project(project_id, cx_c).await;
433
434 // When client A unshares the project, client C's project becomes read-only.
435 project_a
436 .update(cx_a, |project, cx| project.unshare(cx))
437 .unwrap();
438 deterministic.run_until_parked();
439 assert!(worktree_a.read_with(cx_a, |tree, _| !tree.as_local().unwrap().is_shared()));
440 assert!(project_c.read_with(cx_c, |project, _| project.is_read_only()));
441
442 // Client C can open the project again after client A re-shares.
443 let project_id = project_a
444 .update(cx_a, |project, cx| project.share(room_id, cx))
445 .await
446 .unwrap();
447 let project_c2 = client_c.build_remote_project(project_id, cx_c).await;
448 assert!(worktree_a.read_with(cx_a, |tree, _| tree.as_local().unwrap().is_shared()));
449 project_c2
450 .update(cx_c, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
451 .await
452 .unwrap();
453
454 // When client A (the host) leaves the room, the project gets unshared and guests are notified.
455 cx_a.update(|_| drop(rooms.remove(0)));
456 deterministic.run_until_parked();
457 project_a.read_with(cx_a, |project, _| assert!(!project.is_shared()));
458 project_c2.read_with(cx_c, |project, _| {
459 assert!(project.is_read_only());
460 assert!(project.collaborators().is_empty());
461 });
462}
463
464#[gpui::test(iterations = 10)]
465async fn test_host_disconnect(
466 deterministic: Arc<Deterministic>,
467 cx_a: &mut TestAppContext,
468 cx_b: &mut TestAppContext,
469 cx_c: &mut TestAppContext,
470) {
471 cx_b.update(editor::init);
472 deterministic.forbid_parking();
473 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
474 let client_a = server.create_client(cx_a, "user_a").await;
475 let client_b = server.create_client(cx_b, "user_b").await;
476 let client_c = server.create_client(cx_c, "user_c").await;
477 let (room_id, _rooms) = server
478 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b), (&client_c, cx_c)])
479 .await;
480
481 client_a
482 .fs
483 .insert_tree(
484 "/a",
485 json!({
486 "a.txt": "a-contents",
487 "b.txt": "b-contents",
488 }),
489 )
490 .await;
491
492 let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
493 let worktree_a = project_a.read_with(cx_a, |project, cx| project.worktrees(cx).next().unwrap());
494 let project_id = project_a
495 .update(cx_a, |project, cx| project.share(room_id, cx))
496 .await
497 .unwrap();
498
499 let project_b = client_b.build_remote_project(project_id, cx_b).await;
500 assert!(worktree_a.read_with(cx_a, |tree, _| tree.as_local().unwrap().is_shared()));
501
502 let (_, workspace_b) =
503 cx_b.add_window(|cx| Workspace::new(project_b.clone(), |_, _| unimplemented!(), cx));
504 let editor_b = workspace_b
505 .update(cx_b, |workspace, cx| {
506 workspace.open_path((worktree_id, "b.txt"), true, cx)
507 })
508 .await
509 .unwrap()
510 .downcast::<Editor>()
511 .unwrap();
512 cx_b.read(|cx| {
513 assert_eq!(
514 cx.focused_view_id(workspace_b.window_id()),
515 Some(editor_b.id())
516 );
517 });
518 editor_b.update(cx_b, |editor, cx| editor.insert("X", cx));
519 assert!(cx_b.is_window_edited(workspace_b.window_id()));
520
521 // Drop client A's connection. Collaborators should disappear and the project should not be shown as shared.
522 server.disconnect_client(client_a.current_user_id(cx_a));
523 cx_a.foreground().advance_clock(rpc::RECEIVE_TIMEOUT);
524 project_a
525 .condition(cx_a, |project, _| project.collaborators().is_empty())
526 .await;
527 project_a.read_with(cx_a, |project, _| assert!(!project.is_shared()));
528 project_b
529 .condition(cx_b, |project, _| project.is_read_only())
530 .await;
531 assert!(worktree_a.read_with(cx_a, |tree, _| !tree.as_local().unwrap().is_shared()));
532
533 // Ensure client B's edited state is reset and that the whole window is blurred.
534 cx_b.read(|cx| {
535 assert_eq!(cx.focused_view_id(workspace_b.window_id()), None);
536 });
537 assert!(!cx_b.is_window_edited(workspace_b.window_id()));
538
539 // Ensure client B is not prompted to save edits when closing window after disconnecting.
540 workspace_b
541 .update(cx_b, |workspace, cx| {
542 workspace.close(&Default::default(), cx)
543 })
544 .unwrap()
545 .await
546 .unwrap();
547 assert_eq!(cx_b.window_ids().len(), 0);
548 cx_b.update(|_| {
549 drop(workspace_b);
550 drop(project_b);
551 });
552}
553
554#[gpui::test(iterations = 10)]
555async fn test_room_events(
556 deterministic: Arc<Deterministic>,
557 cx_a: &mut TestAppContext,
558 cx_b: &mut TestAppContext,
559) {
560 deterministic.forbid_parking();
561 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
562 let client_a = server.create_client(cx_a, "user_a").await;
563 let client_b = server.create_client(cx_b, "user_b").await;
564 client_a.fs.insert_tree("/a", json!({})).await;
565 client_b.fs.insert_tree("/b", json!({})).await;
566
567 let (project_a, _) = client_a.build_local_project("/a", cx_a).await;
568 let (project_b, _) = client_b.build_local_project("/b", cx_b).await;
569
570 let (room_id, mut rooms) = server
571 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
572 .await;
573
574 let room_a = rooms.remove(0);
575 let room_a_events = room_events(&room_a, cx_a);
576
577 let room_b = rooms.remove(0);
578 let room_b_events = room_events(&room_b, cx_b);
579
580 let project_a_id = project_a
581 .update(cx_a, |project, cx| project.share(room_id, cx))
582 .await
583 .unwrap();
584 deterministic.run_until_parked();
585 assert_eq!(mem::take(&mut *room_a_events.borrow_mut()), vec![]);
586 assert_eq!(
587 mem::take(&mut *room_b_events.borrow_mut()),
588 vec![room::Event::RemoteProjectShared {
589 owner: Arc::new(User {
590 id: client_a.user_id().unwrap(),
591 github_login: "user_a".to_string(),
592 avatar: None,
593 }),
594 project_id: project_a_id,
595 }]
596 );
597
598 let project_b_id = project_b
599 .update(cx_b, |project, cx| project.share(room_id, cx))
600 .await
601 .unwrap();
602 deterministic.run_until_parked();
603 assert_eq!(
604 mem::take(&mut *room_a_events.borrow_mut()),
605 vec![room::Event::RemoteProjectShared {
606 owner: Arc::new(User {
607 id: client_b.user_id().unwrap(),
608 github_login: "user_b".to_string(),
609 avatar: None,
610 }),
611 project_id: project_b_id,
612 }]
613 );
614 assert_eq!(mem::take(&mut *room_b_events.borrow_mut()), vec![]);
615
616 fn room_events(
617 room: &ModelHandle<Room>,
618 cx: &mut TestAppContext,
619 ) -> Rc<RefCell<Vec<room::Event>>> {
620 let events = Rc::new(RefCell::new(Vec::new()));
621 cx.update({
622 let events = events.clone();
623 |cx| {
624 cx.subscribe(room, move |_, event, _| {
625 events.borrow_mut().push(event.clone())
626 })
627 .detach()
628 }
629 });
630 events
631 }
632}
633
634#[gpui::test(iterations = 10)]
635async fn test_room_location(
636 deterministic: Arc<Deterministic>,
637 cx_a: &mut TestAppContext,
638 cx_b: &mut TestAppContext,
639) {
640 deterministic.forbid_parking();
641 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
642 let client_a = server.create_client(cx_a, "user_a").await;
643 let client_b = server.create_client(cx_b, "user_b").await;
644 client_a.fs.insert_tree("/a", json!({})).await;
645 client_b.fs.insert_tree("/b", json!({})).await;
646
647 let (project_a, _) = client_a.build_local_project("/a", cx_a).await;
648 let (project_b, _) = client_b.build_local_project("/b", cx_b).await;
649
650 let (room_id, mut rooms) = server
651 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
652 .await;
653
654 let room_a = rooms.remove(0);
655 let room_a_notified = Rc::new(Cell::new(false));
656 cx_a.update({
657 let room_a_notified = room_a_notified.clone();
658 |cx| {
659 cx.observe(&room_a, move |_, _| room_a_notified.set(true))
660 .detach()
661 }
662 });
663
664 let room_b = rooms.remove(0);
665 let room_b_notified = Rc::new(Cell::new(false));
666 cx_b.update({
667 let room_b_notified = room_b_notified.clone();
668 |cx| {
669 cx.observe(&room_b, move |_, _| room_b_notified.set(true))
670 .detach()
671 }
672 });
673
674 let project_a_id = project_a
675 .update(cx_a, |project, cx| project.share(room_id, cx))
676 .await
677 .unwrap();
678 deterministic.run_until_parked();
679 assert!(room_a_notified.take());
680 assert_eq!(
681 participant_locations(&room_a, cx_a),
682 vec![("user_b".to_string(), ParticipantLocation::External)]
683 );
684 assert!(room_b_notified.take());
685 assert_eq!(
686 participant_locations(&room_b, cx_b),
687 vec![("user_a".to_string(), ParticipantLocation::External)]
688 );
689
690 let project_b_id = project_b
691 .update(cx_b, |project, cx| project.share(room_id, cx))
692 .await
693 .unwrap();
694 deterministic.run_until_parked();
695 assert!(room_a_notified.take());
696 assert_eq!(
697 participant_locations(&room_a, cx_a),
698 vec![("user_b".to_string(), ParticipantLocation::External)]
699 );
700 assert!(room_b_notified.take());
701 assert_eq!(
702 participant_locations(&room_b, cx_b),
703 vec![("user_a".to_string(), ParticipantLocation::External)]
704 );
705
706 room_a
707 .update(cx_a, |room, cx| room.set_location(Some(&project_a), cx))
708 .await
709 .unwrap();
710 deterministic.run_until_parked();
711 assert!(room_a_notified.take());
712 assert_eq!(
713 participant_locations(&room_a, cx_a),
714 vec![("user_b".to_string(), ParticipantLocation::External)]
715 );
716 assert!(room_b_notified.take());
717 assert_eq!(
718 participant_locations(&room_b, cx_b),
719 vec![(
720 "user_a".to_string(),
721 ParticipantLocation::Project {
722 project_id: project_a_id
723 }
724 )]
725 );
726
727 room_b
728 .update(cx_b, |room, cx| room.set_location(Some(&project_b), cx))
729 .await
730 .unwrap();
731 deterministic.run_until_parked();
732 assert!(room_a_notified.take());
733 assert_eq!(
734 participant_locations(&room_a, cx_a),
735 vec![(
736 "user_b".to_string(),
737 ParticipantLocation::Project {
738 project_id: project_b_id
739 }
740 )]
741 );
742 assert!(room_b_notified.take());
743 assert_eq!(
744 participant_locations(&room_b, cx_b),
745 vec![(
746 "user_a".to_string(),
747 ParticipantLocation::Project {
748 project_id: project_a_id
749 }
750 )]
751 );
752
753 room_b
754 .update(cx_b, |room, cx| room.set_location(None, cx))
755 .await
756 .unwrap();
757 deterministic.run_until_parked();
758 assert!(room_a_notified.take());
759 assert_eq!(
760 participant_locations(&room_a, cx_a),
761 vec![("user_b".to_string(), ParticipantLocation::External)]
762 );
763 assert!(room_b_notified.take());
764 assert_eq!(
765 participant_locations(&room_b, cx_b),
766 vec![(
767 "user_a".to_string(),
768 ParticipantLocation::Project {
769 project_id: project_a_id
770 }
771 )]
772 );
773
774 fn participant_locations(
775 room: &ModelHandle<Room>,
776 cx: &TestAppContext,
777 ) -> Vec<(String, ParticipantLocation)> {
778 room.read_with(cx, |room, _| {
779 room.remote_participants()
780 .values()
781 .map(|participant| {
782 (
783 participant.user.github_login.to_string(),
784 participant.location,
785 )
786 })
787 .collect()
788 })
789 }
790}
791
792#[gpui::test(iterations = 10)]
793async fn test_propagate_saves_and_fs_changes(
794 cx_a: &mut TestAppContext,
795 cx_b: &mut TestAppContext,
796 cx_c: &mut TestAppContext,
797) {
798 cx_a.foreground().forbid_parking();
799 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
800 let client_a = server.create_client(cx_a, "user_a").await;
801 let client_b = server.create_client(cx_b, "user_b").await;
802 let client_c = server.create_client(cx_c, "user_c").await;
803 let (room_id, _rooms) = server
804 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b), (&client_c, cx_c)])
805 .await;
806
807 client_a
808 .fs
809 .insert_tree(
810 "/a",
811 json!({
812 "file1": "",
813 "file2": ""
814 }),
815 )
816 .await;
817 let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
818 let worktree_a = project_a.read_with(cx_a, |p, cx| p.worktrees(cx).next().unwrap());
819 let project_id = project_a
820 .update(cx_a, |project, cx| project.share(room_id, cx))
821 .await
822 .unwrap();
823
824 // Join that worktree as clients B and C.
825 let project_b = client_b.build_remote_project(project_id, cx_b).await;
826 let project_c = client_c.build_remote_project(project_id, cx_c).await;
827 let worktree_b = project_b.read_with(cx_b, |p, cx| p.worktrees(cx).next().unwrap());
828 let worktree_c = project_c.read_with(cx_c, |p, cx| p.worktrees(cx).next().unwrap());
829
830 // Open and edit a buffer as both guests B and C.
831 let buffer_b = project_b
832 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
833 .await
834 .unwrap();
835 let buffer_c = project_c
836 .update(cx_c, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
837 .await
838 .unwrap();
839 buffer_b.update(cx_b, |buf, cx| buf.edit([(0..0, "i-am-b, ")], None, cx));
840 buffer_c.update(cx_c, |buf, cx| buf.edit([(0..0, "i-am-c, ")], None, cx));
841
842 // Open and edit that buffer as the host.
843 let buffer_a = project_a
844 .update(cx_a, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
845 .await
846 .unwrap();
847
848 buffer_a
849 .condition(cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, ")
850 .await;
851 buffer_a.update(cx_a, |buf, cx| {
852 buf.edit([(buf.len()..buf.len(), "i-am-a")], None, cx)
853 });
854
855 // Wait for edits to propagate
856 buffer_a
857 .condition(cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
858 .await;
859 buffer_b
860 .condition(cx_b, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
861 .await;
862 buffer_c
863 .condition(cx_c, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
864 .await;
865
866 // Edit the buffer as the host and concurrently save as guest B.
867 let save_b = buffer_b.update(cx_b, |buf, cx| buf.save(cx));
868 buffer_a.update(cx_a, |buf, cx| buf.edit([(0..0, "hi-a, ")], None, cx));
869 save_b.await.unwrap();
870 assert_eq!(
871 client_a.fs.load("/a/file1".as_ref()).await.unwrap(),
872 "hi-a, i-am-c, i-am-b, i-am-a"
873 );
874 buffer_a.read_with(cx_a, |buf, _| assert!(!buf.is_dirty()));
875 buffer_b.read_with(cx_b, |buf, _| assert!(!buf.is_dirty()));
876 buffer_c.condition(cx_c, |buf, _| !buf.is_dirty()).await;
877
878 worktree_a.flush_fs_events(cx_a).await;
879
880 // Make changes on host's file system, see those changes on guest worktrees.
881 client_a
882 .fs
883 .rename(
884 "/a/file1".as_ref(),
885 "/a/file1-renamed".as_ref(),
886 Default::default(),
887 )
888 .await
889 .unwrap();
890
891 client_a
892 .fs
893 .rename("/a/file2".as_ref(), "/a/file3".as_ref(), Default::default())
894 .await
895 .unwrap();
896 client_a.fs.insert_file("/a/file4", "4".into()).await;
897
898 worktree_a
899 .condition(cx_a, |tree, _| {
900 tree.paths()
901 .map(|p| p.to_string_lossy())
902 .collect::<Vec<_>>()
903 == ["file1-renamed", "file3", "file4"]
904 })
905 .await;
906 worktree_b
907 .condition(cx_b, |tree, _| {
908 tree.paths()
909 .map(|p| p.to_string_lossy())
910 .collect::<Vec<_>>()
911 == ["file1-renamed", "file3", "file4"]
912 })
913 .await;
914 worktree_c
915 .condition(cx_c, |tree, _| {
916 tree.paths()
917 .map(|p| p.to_string_lossy())
918 .collect::<Vec<_>>()
919 == ["file1-renamed", "file3", "file4"]
920 })
921 .await;
922
923 // Ensure buffer files are updated as well.
924 buffer_a
925 .condition(cx_a, |buf, _| {
926 buf.file().unwrap().path().to_str() == Some("file1-renamed")
927 })
928 .await;
929 buffer_b
930 .condition(cx_b, |buf, _| {
931 buf.file().unwrap().path().to_str() == Some("file1-renamed")
932 })
933 .await;
934 buffer_c
935 .condition(cx_c, |buf, _| {
936 buf.file().unwrap().path().to_str() == Some("file1-renamed")
937 })
938 .await;
939}
940
941#[gpui::test(iterations = 10)]
942async fn test_fs_operations(
943 executor: Arc<Deterministic>,
944 cx_a: &mut TestAppContext,
945 cx_b: &mut TestAppContext,
946) {
947 executor.forbid_parking();
948 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
949 let client_a = server.create_client(cx_a, "user_a").await;
950 let client_b = server.create_client(cx_b, "user_b").await;
951 let (room_id, _rooms) = server
952 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
953 .await;
954
955 client_a
956 .fs
957 .insert_tree(
958 "/dir",
959 json!({
960 "a.txt": "a-contents",
961 "b.txt": "b-contents",
962 }),
963 )
964 .await;
965 let (project_a, worktree_id) = client_a.build_local_project("/dir", cx_a).await;
966 let project_id = project_a
967 .update(cx_a, |project, cx| project.share(room_id, cx))
968 .await
969 .unwrap();
970 let project_b = client_b.build_remote_project(project_id, cx_b).await;
971
972 let worktree_a = project_a.read_with(cx_a, |project, cx| project.worktrees(cx).next().unwrap());
973 let worktree_b = project_b.read_with(cx_b, |project, cx| project.worktrees(cx).next().unwrap());
974
975 let entry = project_b
976 .update(cx_b, |project, cx| {
977 project
978 .create_entry((worktree_id, "c.txt"), false, cx)
979 .unwrap()
980 })
981 .await
982 .unwrap();
983 worktree_a.read_with(cx_a, |worktree, _| {
984 assert_eq!(
985 worktree
986 .paths()
987 .map(|p| p.to_string_lossy())
988 .collect::<Vec<_>>(),
989 ["a.txt", "b.txt", "c.txt"]
990 );
991 });
992 worktree_b.read_with(cx_b, |worktree, _| {
993 assert_eq!(
994 worktree
995 .paths()
996 .map(|p| p.to_string_lossy())
997 .collect::<Vec<_>>(),
998 ["a.txt", "b.txt", "c.txt"]
999 );
1000 });
1001
1002 project_b
1003 .update(cx_b, |project, cx| {
1004 project.rename_entry(entry.id, Path::new("d.txt"), cx)
1005 })
1006 .unwrap()
1007 .await
1008 .unwrap();
1009 worktree_a.read_with(cx_a, |worktree, _| {
1010 assert_eq!(
1011 worktree
1012 .paths()
1013 .map(|p| p.to_string_lossy())
1014 .collect::<Vec<_>>(),
1015 ["a.txt", "b.txt", "d.txt"]
1016 );
1017 });
1018 worktree_b.read_with(cx_b, |worktree, _| {
1019 assert_eq!(
1020 worktree
1021 .paths()
1022 .map(|p| p.to_string_lossy())
1023 .collect::<Vec<_>>(),
1024 ["a.txt", "b.txt", "d.txt"]
1025 );
1026 });
1027
1028 let dir_entry = project_b
1029 .update(cx_b, |project, cx| {
1030 project
1031 .create_entry((worktree_id, "DIR"), true, cx)
1032 .unwrap()
1033 })
1034 .await
1035 .unwrap();
1036 worktree_a.read_with(cx_a, |worktree, _| {
1037 assert_eq!(
1038 worktree
1039 .paths()
1040 .map(|p| p.to_string_lossy())
1041 .collect::<Vec<_>>(),
1042 ["DIR", "a.txt", "b.txt", "d.txt"]
1043 );
1044 });
1045 worktree_b.read_with(cx_b, |worktree, _| {
1046 assert_eq!(
1047 worktree
1048 .paths()
1049 .map(|p| p.to_string_lossy())
1050 .collect::<Vec<_>>(),
1051 ["DIR", "a.txt", "b.txt", "d.txt"]
1052 );
1053 });
1054
1055 project_b
1056 .update(cx_b, |project, cx| {
1057 project
1058 .create_entry((worktree_id, "DIR/e.txt"), false, cx)
1059 .unwrap()
1060 })
1061 .await
1062 .unwrap();
1063 project_b
1064 .update(cx_b, |project, cx| {
1065 project
1066 .create_entry((worktree_id, "DIR/SUBDIR"), true, cx)
1067 .unwrap()
1068 })
1069 .await
1070 .unwrap();
1071 project_b
1072 .update(cx_b, |project, cx| {
1073 project
1074 .create_entry((worktree_id, "DIR/SUBDIR/f.txt"), false, cx)
1075 .unwrap()
1076 })
1077 .await
1078 .unwrap();
1079 worktree_a.read_with(cx_a, |worktree, _| {
1080 assert_eq!(
1081 worktree
1082 .paths()
1083 .map(|p| p.to_string_lossy())
1084 .collect::<Vec<_>>(),
1085 [
1086 "DIR",
1087 "DIR/SUBDIR",
1088 "DIR/SUBDIR/f.txt",
1089 "DIR/e.txt",
1090 "a.txt",
1091 "b.txt",
1092 "d.txt"
1093 ]
1094 );
1095 });
1096 worktree_b.read_with(cx_b, |worktree, _| {
1097 assert_eq!(
1098 worktree
1099 .paths()
1100 .map(|p| p.to_string_lossy())
1101 .collect::<Vec<_>>(),
1102 [
1103 "DIR",
1104 "DIR/SUBDIR",
1105 "DIR/SUBDIR/f.txt",
1106 "DIR/e.txt",
1107 "a.txt",
1108 "b.txt",
1109 "d.txt"
1110 ]
1111 );
1112 });
1113
1114 project_b
1115 .update(cx_b, |project, cx| {
1116 project
1117 .copy_entry(entry.id, Path::new("f.txt"), cx)
1118 .unwrap()
1119 })
1120 .await
1121 .unwrap();
1122 worktree_a.read_with(cx_a, |worktree, _| {
1123 assert_eq!(
1124 worktree
1125 .paths()
1126 .map(|p| p.to_string_lossy())
1127 .collect::<Vec<_>>(),
1128 [
1129 "DIR",
1130 "DIR/SUBDIR",
1131 "DIR/SUBDIR/f.txt",
1132 "DIR/e.txt",
1133 "a.txt",
1134 "b.txt",
1135 "d.txt",
1136 "f.txt"
1137 ]
1138 );
1139 });
1140 worktree_b.read_with(cx_b, |worktree, _| {
1141 assert_eq!(
1142 worktree
1143 .paths()
1144 .map(|p| p.to_string_lossy())
1145 .collect::<Vec<_>>(),
1146 [
1147 "DIR",
1148 "DIR/SUBDIR",
1149 "DIR/SUBDIR/f.txt",
1150 "DIR/e.txt",
1151 "a.txt",
1152 "b.txt",
1153 "d.txt",
1154 "f.txt"
1155 ]
1156 );
1157 });
1158
1159 project_b
1160 .update(cx_b, |project, cx| {
1161 project.delete_entry(dir_entry.id, cx).unwrap()
1162 })
1163 .await
1164 .unwrap();
1165 worktree_a.read_with(cx_a, |worktree, _| {
1166 assert_eq!(
1167 worktree
1168 .paths()
1169 .map(|p| p.to_string_lossy())
1170 .collect::<Vec<_>>(),
1171 ["a.txt", "b.txt", "d.txt", "f.txt"]
1172 );
1173 });
1174 worktree_b.read_with(cx_b, |worktree, _| {
1175 assert_eq!(
1176 worktree
1177 .paths()
1178 .map(|p| p.to_string_lossy())
1179 .collect::<Vec<_>>(),
1180 ["a.txt", "b.txt", "d.txt", "f.txt"]
1181 );
1182 });
1183
1184 project_b
1185 .update(cx_b, |project, cx| {
1186 project.delete_entry(entry.id, cx).unwrap()
1187 })
1188 .await
1189 .unwrap();
1190 worktree_a.read_with(cx_a, |worktree, _| {
1191 assert_eq!(
1192 worktree
1193 .paths()
1194 .map(|p| p.to_string_lossy())
1195 .collect::<Vec<_>>(),
1196 ["a.txt", "b.txt", "f.txt"]
1197 );
1198 });
1199 worktree_b.read_with(cx_b, |worktree, _| {
1200 assert_eq!(
1201 worktree
1202 .paths()
1203 .map(|p| p.to_string_lossy())
1204 .collect::<Vec<_>>(),
1205 ["a.txt", "b.txt", "f.txt"]
1206 );
1207 });
1208}
1209
1210#[gpui::test(iterations = 10)]
1211async fn test_buffer_conflict_after_save(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
1212 cx_a.foreground().forbid_parking();
1213 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1214 let client_a = server.create_client(cx_a, "user_a").await;
1215 let client_b = server.create_client(cx_b, "user_b").await;
1216 let (room_id, _rooms) = server
1217 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
1218 .await;
1219
1220 client_a
1221 .fs
1222 .insert_tree(
1223 "/dir",
1224 json!({
1225 "a.txt": "a-contents",
1226 }),
1227 )
1228 .await;
1229 let (project_a, worktree_id) = client_a.build_local_project("/dir", cx_a).await;
1230 let project_id = project_a
1231 .update(cx_a, |project, cx| project.share(room_id, cx))
1232 .await
1233 .unwrap();
1234 let project_b = client_b.build_remote_project(project_id, cx_b).await;
1235
1236 // Open a buffer as client B
1237 let buffer_b = project_b
1238 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1239 .await
1240 .unwrap();
1241
1242 buffer_b.update(cx_b, |buf, cx| buf.edit([(0..0, "world ")], None, cx));
1243 buffer_b.read_with(cx_b, |buf, _| {
1244 assert!(buf.is_dirty());
1245 assert!(!buf.has_conflict());
1246 });
1247
1248 buffer_b.update(cx_b, |buf, cx| buf.save(cx)).await.unwrap();
1249 buffer_b
1250 .condition(cx_b, |buffer_b, _| !buffer_b.is_dirty())
1251 .await;
1252 buffer_b.read_with(cx_b, |buf, _| {
1253 assert!(!buf.has_conflict());
1254 });
1255
1256 buffer_b.update(cx_b, |buf, cx| buf.edit([(0..0, "hello ")], None, cx));
1257 buffer_b.read_with(cx_b, |buf, _| {
1258 assert!(buf.is_dirty());
1259 assert!(!buf.has_conflict());
1260 });
1261}
1262
1263#[gpui::test(iterations = 10)]
1264async fn test_buffer_reloading(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
1265 cx_a.foreground().forbid_parking();
1266 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1267 let client_a = server.create_client(cx_a, "user_a").await;
1268 let client_b = server.create_client(cx_b, "user_b").await;
1269 let (room_id, _rooms) = server
1270 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
1271 .await;
1272
1273 client_a
1274 .fs
1275 .insert_tree(
1276 "/dir",
1277 json!({
1278 "a.txt": "a\nb\nc",
1279 }),
1280 )
1281 .await;
1282 let (project_a, worktree_id) = client_a.build_local_project("/dir", cx_a).await;
1283 let project_id = project_a
1284 .update(cx_a, |project, cx| project.share(room_id, cx))
1285 .await
1286 .unwrap();
1287 let project_b = client_b.build_remote_project(project_id, cx_b).await;
1288
1289 // Open a buffer as client B
1290 let buffer_b = project_b
1291 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1292 .await
1293 .unwrap();
1294 buffer_b.read_with(cx_b, |buf, _| {
1295 assert!(!buf.is_dirty());
1296 assert!(!buf.has_conflict());
1297 assert_eq!(buf.line_ending(), LineEnding::Unix);
1298 });
1299
1300 let new_contents = Rope::from("d\ne\nf");
1301 client_a
1302 .fs
1303 .save("/dir/a.txt".as_ref(), &new_contents, LineEnding::Windows)
1304 .await
1305 .unwrap();
1306 buffer_b
1307 .condition(cx_b, |buf, _| {
1308 buf.text() == new_contents.to_string() && !buf.is_dirty()
1309 })
1310 .await;
1311 buffer_b.read_with(cx_b, |buf, _| {
1312 assert!(!buf.is_dirty());
1313 assert!(!buf.has_conflict());
1314 assert_eq!(buf.line_ending(), LineEnding::Windows);
1315 });
1316}
1317
1318#[gpui::test(iterations = 10)]
1319async fn test_editing_while_guest_opens_buffer(
1320 cx_a: &mut TestAppContext,
1321 cx_b: &mut TestAppContext,
1322) {
1323 cx_a.foreground().forbid_parking();
1324 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1325 let client_a = server.create_client(cx_a, "user_a").await;
1326 let client_b = server.create_client(cx_b, "user_b").await;
1327 let (room_id, _rooms) = server
1328 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
1329 .await;
1330
1331 client_a
1332 .fs
1333 .insert_tree("/dir", json!({ "a.txt": "a-contents" }))
1334 .await;
1335 let (project_a, worktree_id) = client_a.build_local_project("/dir", cx_a).await;
1336 let project_id = project_a
1337 .update(cx_a, |project, cx| project.share(room_id, cx))
1338 .await
1339 .unwrap();
1340 let project_b = client_b.build_remote_project(project_id, cx_b).await;
1341
1342 // Open a buffer as client A
1343 let buffer_a = project_a
1344 .update(cx_a, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1345 .await
1346 .unwrap();
1347
1348 // Start opening the same buffer as client B
1349 let buffer_b = cx_b
1350 .background()
1351 .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx)));
1352
1353 // Edit the buffer as client A while client B is still opening it.
1354 cx_b.background().simulate_random_delay().await;
1355 buffer_a.update(cx_a, |buf, cx| buf.edit([(0..0, "X")], None, cx));
1356 cx_b.background().simulate_random_delay().await;
1357 buffer_a.update(cx_a, |buf, cx| buf.edit([(1..1, "Y")], None, cx));
1358
1359 let text = buffer_a.read_with(cx_a, |buf, _| buf.text());
1360 let buffer_b = buffer_b.await.unwrap();
1361 buffer_b.condition(cx_b, |buf, _| buf.text() == text).await;
1362}
1363
1364#[gpui::test(iterations = 10)]
1365async fn test_leaving_worktree_while_opening_buffer(
1366 cx_a: &mut TestAppContext,
1367 cx_b: &mut TestAppContext,
1368) {
1369 cx_a.foreground().forbid_parking();
1370 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1371 let client_a = server.create_client(cx_a, "user_a").await;
1372 let client_b = server.create_client(cx_b, "user_b").await;
1373 let (room_id, _rooms) = server
1374 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
1375 .await;
1376
1377 client_a
1378 .fs
1379 .insert_tree("/dir", json!({ "a.txt": "a-contents" }))
1380 .await;
1381 let (project_a, worktree_id) = client_a.build_local_project("/dir", cx_a).await;
1382 let project_id = project_a
1383 .update(cx_a, |project, cx| project.share(room_id, cx))
1384 .await
1385 .unwrap();
1386 let project_b = client_b.build_remote_project(project_id, cx_b).await;
1387
1388 // See that a guest has joined as client A.
1389 project_a
1390 .condition(cx_a, |p, _| p.collaborators().len() == 1)
1391 .await;
1392
1393 // Begin opening a buffer as client B, but leave the project before the open completes.
1394 let buffer_b = cx_b
1395 .background()
1396 .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx)));
1397 cx_b.update(|_| drop(project_b));
1398 drop(buffer_b);
1399
1400 // See that the guest has left.
1401 project_a
1402 .condition(cx_a, |p, _| p.collaborators().is_empty())
1403 .await;
1404}
1405
1406#[gpui::test(iterations = 10)]
1407async fn test_canceling_buffer_opening(
1408 deterministic: Arc<Deterministic>,
1409 cx_a: &mut TestAppContext,
1410 cx_b: &mut TestAppContext,
1411) {
1412 deterministic.forbid_parking();
1413
1414 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1415 let client_a = server.create_client(cx_a, "user_a").await;
1416 let client_b = server.create_client(cx_b, "user_b").await;
1417 let (room_id, _rooms) = server
1418 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
1419 .await;
1420
1421 client_a
1422 .fs
1423 .insert_tree(
1424 "/dir",
1425 json!({
1426 "a.txt": "abc",
1427 }),
1428 )
1429 .await;
1430 let (project_a, worktree_id) = client_a.build_local_project("/dir", cx_a).await;
1431 let project_id = project_a
1432 .update(cx_a, |project, cx| project.share(room_id, cx))
1433 .await
1434 .unwrap();
1435 let project_b = client_b.build_remote_project(project_id, cx_b).await;
1436
1437 let buffer_a = project_a
1438 .update(cx_a, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1439 .await
1440 .unwrap();
1441
1442 // Open a buffer as client B but cancel after a random amount of time.
1443 let buffer_b = project_b.update(cx_b, |p, cx| p.open_buffer_by_id(buffer_a.id() as u64, cx));
1444 deterministic.simulate_random_delay().await;
1445 drop(buffer_b);
1446
1447 // Try opening the same buffer again as client B, and ensure we can
1448 // still do it despite the cancellation above.
1449 let buffer_b = project_b
1450 .update(cx_b, |p, cx| p.open_buffer_by_id(buffer_a.id() as u64, cx))
1451 .await
1452 .unwrap();
1453 buffer_b.read_with(cx_b, |buf, _| assert_eq!(buf.text(), "abc"));
1454}
1455
1456#[gpui::test(iterations = 10)]
1457async fn test_leaving_project(
1458 deterministic: Arc<Deterministic>,
1459 cx_a: &mut TestAppContext,
1460 cx_b: &mut TestAppContext,
1461 cx_c: &mut TestAppContext,
1462) {
1463 deterministic.forbid_parking();
1464 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1465 let client_a = server.create_client(cx_a, "user_a").await;
1466 let client_b = server.create_client(cx_b, "user_b").await;
1467 let client_c = server.create_client(cx_c, "user_c").await;
1468 let (room_id, _rooms) = server
1469 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b), (&client_c, cx_c)])
1470 .await;
1471
1472 client_a
1473 .fs
1474 .insert_tree(
1475 "/a",
1476 json!({
1477 "a.txt": "a-contents",
1478 "b.txt": "b-contents",
1479 }),
1480 )
1481 .await;
1482 let (project_a, _) = client_a.build_local_project("/a", cx_a).await;
1483 let project_id = project_a
1484 .update(cx_a, |project, cx| project.share(room_id, cx))
1485 .await
1486 .unwrap();
1487 let project_b = client_b.build_remote_project(project_id, cx_b).await;
1488 let project_c = client_c.build_remote_project(project_id, cx_c).await;
1489
1490 // Client A sees that a guest has joined.
1491 deterministic.run_until_parked();
1492 project_a.read_with(cx_a, |project, _| {
1493 assert_eq!(project.collaborators().len(), 2);
1494 });
1495 project_b.read_with(cx_b, |project, _| {
1496 assert_eq!(project.collaborators().len(), 2);
1497 });
1498 project_c.read_with(cx_c, |project, _| {
1499 assert_eq!(project.collaborators().len(), 2);
1500 });
1501
1502 // Drop client B's connection and ensure client A and client C observe client B leaving the project.
1503 client_b.disconnect(&cx_b.to_async()).unwrap();
1504 deterministic.run_until_parked();
1505 project_a.read_with(cx_a, |project, _| {
1506 assert_eq!(project.collaborators().len(), 1);
1507 });
1508 project_b.read_with(cx_b, |project, _| {
1509 assert!(project.is_read_only());
1510 });
1511 project_c.read_with(cx_c, |project, _| {
1512 assert_eq!(project.collaborators().len(), 1);
1513 });
1514
1515 // Client B can't join the project, unless they re-join the room.
1516 cx_b.spawn(|cx| {
1517 Project::remote(
1518 project_id,
1519 client_b.client.clone(),
1520 client_b.user_store.clone(),
1521 client_b.project_store.clone(),
1522 client_b.language_registry.clone(),
1523 FakeFs::new(cx.background()),
1524 cx,
1525 )
1526 })
1527 .await
1528 .unwrap_err();
1529
1530 // Simulate connection loss for client C and ensure client A observes client C leaving the project.
1531 client_c.wait_for_current_user(cx_c).await;
1532 server.disconnect_client(client_c.current_user_id(cx_c));
1533 cx_a.foreground().advance_clock(rpc::RECEIVE_TIMEOUT);
1534 deterministic.run_until_parked();
1535 project_a.read_with(cx_a, |project, _| {
1536 assert_eq!(project.collaborators().len(), 0);
1537 });
1538 project_b.read_with(cx_b, |project, _| {
1539 assert!(project.is_read_only());
1540 });
1541 project_c.read_with(cx_c, |project, _| {
1542 assert!(project.is_read_only());
1543 });
1544}
1545
1546#[gpui::test(iterations = 10)]
1547async fn test_collaborating_with_diagnostics(
1548 deterministic: Arc<Deterministic>,
1549 cx_a: &mut TestAppContext,
1550 cx_b: &mut TestAppContext,
1551 cx_c: &mut TestAppContext,
1552) {
1553 deterministic.forbid_parking();
1554 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1555 let client_a = server.create_client(cx_a, "user_a").await;
1556 let client_b = server.create_client(cx_b, "user_b").await;
1557 let client_c = server.create_client(cx_c, "user_c").await;
1558 let (room_id, _rooms) = server
1559 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b), (&client_c, cx_c)])
1560 .await;
1561
1562 // Set up a fake language server.
1563 let mut language = Language::new(
1564 LanguageConfig {
1565 name: "Rust".into(),
1566 path_suffixes: vec!["rs".to_string()],
1567 ..Default::default()
1568 },
1569 Some(tree_sitter_rust::language()),
1570 );
1571 let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default()).await;
1572 client_a.language_registry.add(Arc::new(language));
1573
1574 // Share a project as client A
1575 client_a
1576 .fs
1577 .insert_tree(
1578 "/a",
1579 json!({
1580 "a.rs": "let one = two",
1581 "other.rs": "",
1582 }),
1583 )
1584 .await;
1585 let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
1586 let project_id = project_a
1587 .update(cx_a, |project, cx| project.share(room_id, cx))
1588 .await
1589 .unwrap();
1590
1591 // Cause the language server to start.
1592 let _buffer = cx_a
1593 .background()
1594 .spawn(project_a.update(cx_a, |project, cx| {
1595 project.open_buffer(
1596 ProjectPath {
1597 worktree_id,
1598 path: Path::new("other.rs").into(),
1599 },
1600 cx,
1601 )
1602 }))
1603 .await
1604 .unwrap();
1605
1606 // Join the worktree as client B.
1607 let project_b = client_b.build_remote_project(project_id, cx_b).await;
1608
1609 // Simulate a language server reporting errors for a file.
1610 let mut fake_language_server = fake_language_servers.next().await.unwrap();
1611 fake_language_server
1612 .receive_notification::<lsp::notification::DidOpenTextDocument>()
1613 .await;
1614 fake_language_server.notify::<lsp::notification::PublishDiagnostics>(
1615 lsp::PublishDiagnosticsParams {
1616 uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
1617 version: None,
1618 diagnostics: vec![lsp::Diagnostic {
1619 severity: Some(lsp::DiagnosticSeverity::ERROR),
1620 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
1621 message: "message 1".to_string(),
1622 ..Default::default()
1623 }],
1624 },
1625 );
1626
1627 // Wait for server to see the diagnostics update.
1628 deterministic.run_until_parked();
1629 {
1630 let store = server.store.lock().await;
1631 let project = store.project(ProjectId::from_proto(project_id)).unwrap();
1632 let worktree = project.worktrees.get(&worktree_id.to_proto()).unwrap();
1633 assert!(!worktree.diagnostic_summaries.is_empty());
1634 }
1635
1636 // Ensure client B observes the new diagnostics.
1637 project_b.read_with(cx_b, |project, cx| {
1638 assert_eq!(
1639 project.diagnostic_summaries(cx).collect::<Vec<_>>(),
1640 &[(
1641 ProjectPath {
1642 worktree_id,
1643 path: Arc::from(Path::new("a.rs")),
1644 },
1645 DiagnosticSummary {
1646 error_count: 1,
1647 warning_count: 0,
1648 ..Default::default()
1649 },
1650 )]
1651 )
1652 });
1653
1654 // Join project as client C and observe the diagnostics.
1655 let project_c = client_c.build_remote_project(project_id, cx_c).await;
1656 deterministic.run_until_parked();
1657 project_c.read_with(cx_c, |project, cx| {
1658 assert_eq!(
1659 project.diagnostic_summaries(cx).collect::<Vec<_>>(),
1660 &[(
1661 ProjectPath {
1662 worktree_id,
1663 path: Arc::from(Path::new("a.rs")),
1664 },
1665 DiagnosticSummary {
1666 error_count: 1,
1667 warning_count: 0,
1668 ..Default::default()
1669 },
1670 )]
1671 )
1672 });
1673
1674 // Simulate a language server reporting more errors for a file.
1675 fake_language_server.notify::<lsp::notification::PublishDiagnostics>(
1676 lsp::PublishDiagnosticsParams {
1677 uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
1678 version: None,
1679 diagnostics: vec![
1680 lsp::Diagnostic {
1681 severity: Some(lsp::DiagnosticSeverity::ERROR),
1682 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
1683 message: "message 1".to_string(),
1684 ..Default::default()
1685 },
1686 lsp::Diagnostic {
1687 severity: Some(lsp::DiagnosticSeverity::WARNING),
1688 range: lsp::Range::new(lsp::Position::new(0, 10), lsp::Position::new(0, 13)),
1689 message: "message 2".to_string(),
1690 ..Default::default()
1691 },
1692 ],
1693 },
1694 );
1695
1696 // Clients B and C get the updated summaries
1697 deterministic.run_until_parked();
1698 project_b.read_with(cx_b, |project, cx| {
1699 assert_eq!(
1700 project.diagnostic_summaries(cx).collect::<Vec<_>>(),
1701 [(
1702 ProjectPath {
1703 worktree_id,
1704 path: Arc::from(Path::new("a.rs")),
1705 },
1706 DiagnosticSummary {
1707 error_count: 1,
1708 warning_count: 1,
1709 ..Default::default()
1710 },
1711 )]
1712 );
1713 });
1714 project_c.read_with(cx_c, |project, cx| {
1715 assert_eq!(
1716 project.diagnostic_summaries(cx).collect::<Vec<_>>(),
1717 [(
1718 ProjectPath {
1719 worktree_id,
1720 path: Arc::from(Path::new("a.rs")),
1721 },
1722 DiagnosticSummary {
1723 error_count: 1,
1724 warning_count: 1,
1725 ..Default::default()
1726 },
1727 )]
1728 );
1729 });
1730
1731 // Open the file with the errors on client B. They should be present.
1732 let buffer_b = cx_b
1733 .background()
1734 .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
1735 .await
1736 .unwrap();
1737
1738 buffer_b.read_with(cx_b, |buffer, _| {
1739 assert_eq!(
1740 buffer
1741 .snapshot()
1742 .diagnostics_in_range::<_, Point>(0..buffer.len(), false)
1743 .collect::<Vec<_>>(),
1744 &[
1745 DiagnosticEntry {
1746 range: Point::new(0, 4)..Point::new(0, 7),
1747 diagnostic: Diagnostic {
1748 group_id: 1,
1749 message: "message 1".to_string(),
1750 severity: lsp::DiagnosticSeverity::ERROR,
1751 is_primary: true,
1752 ..Default::default()
1753 }
1754 },
1755 DiagnosticEntry {
1756 range: Point::new(0, 10)..Point::new(0, 13),
1757 diagnostic: Diagnostic {
1758 group_id: 2,
1759 severity: lsp::DiagnosticSeverity::WARNING,
1760 message: "message 2".to_string(),
1761 is_primary: true,
1762 ..Default::default()
1763 }
1764 }
1765 ]
1766 );
1767 });
1768
1769 // Simulate a language server reporting no errors for a file.
1770 fake_language_server.notify::<lsp::notification::PublishDiagnostics>(
1771 lsp::PublishDiagnosticsParams {
1772 uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
1773 version: None,
1774 diagnostics: vec![],
1775 },
1776 );
1777 deterministic.run_until_parked();
1778 project_a.read_with(cx_a, |project, cx| {
1779 assert_eq!(project.diagnostic_summaries(cx).collect::<Vec<_>>(), [])
1780 });
1781 project_b.read_with(cx_b, |project, cx| {
1782 assert_eq!(project.diagnostic_summaries(cx).collect::<Vec<_>>(), [])
1783 });
1784 project_c.read_with(cx_c, |project, cx| {
1785 assert_eq!(project.diagnostic_summaries(cx).collect::<Vec<_>>(), [])
1786 });
1787}
1788
1789#[gpui::test(iterations = 10)]
1790async fn test_collaborating_with_completion(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
1791 cx_a.foreground().forbid_parking();
1792 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1793 let client_a = server.create_client(cx_a, "user_a").await;
1794 let client_b = server.create_client(cx_b, "user_b").await;
1795 let (room_id, _rooms) = server
1796 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
1797 .await;
1798
1799 // Set up a fake language server.
1800 let mut language = Language::new(
1801 LanguageConfig {
1802 name: "Rust".into(),
1803 path_suffixes: vec!["rs".to_string()],
1804 ..Default::default()
1805 },
1806 Some(tree_sitter_rust::language()),
1807 );
1808 let mut fake_language_servers = language
1809 .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
1810 capabilities: lsp::ServerCapabilities {
1811 completion_provider: Some(lsp::CompletionOptions {
1812 trigger_characters: Some(vec![".".to_string()]),
1813 ..Default::default()
1814 }),
1815 ..Default::default()
1816 },
1817 ..Default::default()
1818 }))
1819 .await;
1820 client_a.language_registry.add(Arc::new(language));
1821
1822 client_a
1823 .fs
1824 .insert_tree(
1825 "/a",
1826 json!({
1827 "main.rs": "fn main() { a }",
1828 "other.rs": "",
1829 }),
1830 )
1831 .await;
1832 let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
1833 let project_id = project_a
1834 .update(cx_a, |project, cx| project.share(room_id, cx))
1835 .await
1836 .unwrap();
1837 let project_b = client_b.build_remote_project(project_id, cx_b).await;
1838
1839 // Open a file in an editor as the guest.
1840 let buffer_b = project_b
1841 .update(cx_b, |p, cx| p.open_buffer((worktree_id, "main.rs"), cx))
1842 .await
1843 .unwrap();
1844 let (_, window_b) = cx_b.add_window(|_| EmptyView);
1845 let editor_b = cx_b.add_view(&window_b, |cx| {
1846 Editor::for_buffer(buffer_b.clone(), Some(project_b.clone()), cx)
1847 });
1848
1849 let fake_language_server = fake_language_servers.next().await.unwrap();
1850 buffer_b
1851 .condition(cx_b, |buffer, _| !buffer.completion_triggers().is_empty())
1852 .await;
1853
1854 // Type a completion trigger character as the guest.
1855 editor_b.update(cx_b, |editor, cx| {
1856 editor.change_selections(None, cx, |s| s.select_ranges([13..13]));
1857 editor.handle_input(".", cx);
1858 cx.focus(&editor_b);
1859 });
1860
1861 // Receive a completion request as the host's language server.
1862 // Return some completions from the host's language server.
1863 cx_a.foreground().start_waiting();
1864 fake_language_server
1865 .handle_request::<lsp::request::Completion, _, _>(|params, _| async move {
1866 assert_eq!(
1867 params.text_document_position.text_document.uri,
1868 lsp::Url::from_file_path("/a/main.rs").unwrap(),
1869 );
1870 assert_eq!(
1871 params.text_document_position.position,
1872 lsp::Position::new(0, 14),
1873 );
1874
1875 Ok(Some(lsp::CompletionResponse::Array(vec![
1876 lsp::CompletionItem {
1877 label: "first_method(…)".into(),
1878 detail: Some("fn(&mut self, B) -> C".into()),
1879 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1880 new_text: "first_method($1)".to_string(),
1881 range: lsp::Range::new(
1882 lsp::Position::new(0, 14),
1883 lsp::Position::new(0, 14),
1884 ),
1885 })),
1886 insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
1887 ..Default::default()
1888 },
1889 lsp::CompletionItem {
1890 label: "second_method(…)".into(),
1891 detail: Some("fn(&mut self, C) -> D<E>".into()),
1892 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1893 new_text: "second_method()".to_string(),
1894 range: lsp::Range::new(
1895 lsp::Position::new(0, 14),
1896 lsp::Position::new(0, 14),
1897 ),
1898 })),
1899 insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
1900 ..Default::default()
1901 },
1902 ])))
1903 })
1904 .next()
1905 .await
1906 .unwrap();
1907 cx_a.foreground().finish_waiting();
1908
1909 // Open the buffer on the host.
1910 let buffer_a = project_a
1911 .update(cx_a, |p, cx| p.open_buffer((worktree_id, "main.rs"), cx))
1912 .await
1913 .unwrap();
1914 buffer_a
1915 .condition(cx_a, |buffer, _| buffer.text() == "fn main() { a. }")
1916 .await;
1917
1918 // Confirm a completion on the guest.
1919 editor_b
1920 .condition(cx_b, |editor, _| editor.context_menu_visible())
1921 .await;
1922 editor_b.update(cx_b, |editor, cx| {
1923 editor.confirm_completion(&ConfirmCompletion { item_ix: Some(0) }, cx);
1924 assert_eq!(editor.text(cx), "fn main() { a.first_method() }");
1925 });
1926
1927 // Return a resolved completion from the host's language server.
1928 // The resolved completion has an additional text edit.
1929 fake_language_server.handle_request::<lsp::request::ResolveCompletionItem, _, _>(
1930 |params, _| async move {
1931 assert_eq!(params.label, "first_method(…)");
1932 Ok(lsp::CompletionItem {
1933 label: "first_method(…)".into(),
1934 detail: Some("fn(&mut self, B) -> C".into()),
1935 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
1936 new_text: "first_method($1)".to_string(),
1937 range: lsp::Range::new(lsp::Position::new(0, 14), lsp::Position::new(0, 14)),
1938 })),
1939 additional_text_edits: Some(vec![lsp::TextEdit {
1940 new_text: "use d::SomeTrait;\n".to_string(),
1941 range: lsp::Range::new(lsp::Position::new(0, 0), lsp::Position::new(0, 0)),
1942 }]),
1943 insert_text_format: Some(lsp::InsertTextFormat::SNIPPET),
1944 ..Default::default()
1945 })
1946 },
1947 );
1948
1949 // The additional edit is applied.
1950 buffer_a
1951 .condition(cx_a, |buffer, _| {
1952 buffer.text() == "use d::SomeTrait;\nfn main() { a.first_method() }"
1953 })
1954 .await;
1955 buffer_b
1956 .condition(cx_b, |buffer, _| {
1957 buffer.text() == "use d::SomeTrait;\nfn main() { a.first_method() }"
1958 })
1959 .await;
1960}
1961
1962#[gpui::test(iterations = 10)]
1963async fn test_reloading_buffer_manually(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
1964 cx_a.foreground().forbid_parking();
1965 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
1966 let client_a = server.create_client(cx_a, "user_a").await;
1967 let client_b = server.create_client(cx_b, "user_b").await;
1968 let (room_id, _rooms) = server
1969 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
1970 .await;
1971
1972 client_a
1973 .fs
1974 .insert_tree("/a", json!({ "a.rs": "let one = 1;" }))
1975 .await;
1976 let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
1977 let buffer_a = project_a
1978 .update(cx_a, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx))
1979 .await
1980 .unwrap();
1981 let project_id = project_a
1982 .update(cx_a, |project, cx| project.share(room_id, cx))
1983 .await
1984 .unwrap();
1985
1986 let project_b = client_b.build_remote_project(project_id, cx_b).await;
1987
1988 let buffer_b = cx_b
1989 .background()
1990 .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
1991 .await
1992 .unwrap();
1993 buffer_b.update(cx_b, |buffer, cx| {
1994 buffer.edit([(4..7, "six")], None, cx);
1995 buffer.edit([(10..11, "6")], None, cx);
1996 assert_eq!(buffer.text(), "let six = 6;");
1997 assert!(buffer.is_dirty());
1998 assert!(!buffer.has_conflict());
1999 });
2000 buffer_a
2001 .condition(cx_a, |buffer, _| buffer.text() == "let six = 6;")
2002 .await;
2003
2004 client_a
2005 .fs
2006 .save(
2007 "/a/a.rs".as_ref(),
2008 &Rope::from("let seven = 7;"),
2009 LineEnding::Unix,
2010 )
2011 .await
2012 .unwrap();
2013 buffer_a
2014 .condition(cx_a, |buffer, _| buffer.has_conflict())
2015 .await;
2016 buffer_b
2017 .condition(cx_b, |buffer, _| buffer.has_conflict())
2018 .await;
2019
2020 project_b
2021 .update(cx_b, |project, cx| {
2022 project.reload_buffers(HashSet::from_iter([buffer_b.clone()]), true, cx)
2023 })
2024 .await
2025 .unwrap();
2026 buffer_a.read_with(cx_a, |buffer, _| {
2027 assert_eq!(buffer.text(), "let seven = 7;");
2028 assert!(!buffer.is_dirty());
2029 assert!(!buffer.has_conflict());
2030 });
2031 buffer_b.read_with(cx_b, |buffer, _| {
2032 assert_eq!(buffer.text(), "let seven = 7;");
2033 assert!(!buffer.is_dirty());
2034 assert!(!buffer.has_conflict());
2035 });
2036
2037 buffer_a.update(cx_a, |buffer, cx| {
2038 // Undoing on the host is a no-op when the reload was initiated by the guest.
2039 buffer.undo(cx);
2040 assert_eq!(buffer.text(), "let seven = 7;");
2041 assert!(!buffer.is_dirty());
2042 assert!(!buffer.has_conflict());
2043 });
2044 buffer_b.update(cx_b, |buffer, cx| {
2045 // Undoing on the guest rolls back the buffer to before it was reloaded but the conflict gets cleared.
2046 buffer.undo(cx);
2047 assert_eq!(buffer.text(), "let six = 6;");
2048 assert!(buffer.is_dirty());
2049 assert!(!buffer.has_conflict());
2050 });
2051}
2052
2053#[gpui::test(iterations = 10)]
2054async fn test_formatting_buffer(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
2055 use project::FormatTrigger;
2056
2057 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
2058 let client_a = server.create_client(cx_a, "user_a").await;
2059 let client_b = server.create_client(cx_b, "user_b").await;
2060 let (room_id, _rooms) = server
2061 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
2062 .await;
2063
2064 // Set up a fake language server.
2065 let mut language = Language::new(
2066 LanguageConfig {
2067 name: "Rust".into(),
2068 path_suffixes: vec!["rs".to_string()],
2069 ..Default::default()
2070 },
2071 Some(tree_sitter_rust::language()),
2072 );
2073 let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default()).await;
2074 client_a.language_registry.add(Arc::new(language));
2075
2076 // Here we insert a fake tree with a directory that exists on disk. This is needed
2077 // because later we'll invoke a command, which requires passing a working directory
2078 // that points to a valid location on disk.
2079 let directory = env::current_dir().unwrap();
2080 client_a
2081 .fs
2082 .insert_tree(&directory, json!({ "a.rs": "let one = \"two\"" }))
2083 .await;
2084 let (project_a, worktree_id) = client_a.build_local_project(&directory, cx_a).await;
2085 let project_id = project_a
2086 .update(cx_a, |project, cx| project.share(room_id, cx))
2087 .await
2088 .unwrap();
2089 let project_b = client_b.build_remote_project(project_id, cx_b).await;
2090
2091 let buffer_b = cx_b
2092 .background()
2093 .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
2094 .await
2095 .unwrap();
2096
2097 let fake_language_server = fake_language_servers.next().await.unwrap();
2098 fake_language_server.handle_request::<lsp::request::Formatting, _, _>(|_, _| async move {
2099 Ok(Some(vec![
2100 lsp::TextEdit {
2101 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 4)),
2102 new_text: "h".to_string(),
2103 },
2104 lsp::TextEdit {
2105 range: lsp::Range::new(lsp::Position::new(0, 7), lsp::Position::new(0, 7)),
2106 new_text: "y".to_string(),
2107 },
2108 ]))
2109 });
2110
2111 project_b
2112 .update(cx_b, |project, cx| {
2113 project.format(
2114 HashSet::from_iter([buffer_b.clone()]),
2115 true,
2116 FormatTrigger::Save,
2117 cx,
2118 )
2119 })
2120 .await
2121 .unwrap();
2122 assert_eq!(
2123 buffer_b.read_with(cx_b, |buffer, _| buffer.text()),
2124 "let honey = \"two\""
2125 );
2126
2127 // Ensure buffer can be formatted using an external command. Notice how the
2128 // host's configuration is honored as opposed to using the guest's settings.
2129 cx_a.update(|cx| {
2130 cx.update_global(|settings: &mut Settings, _| {
2131 settings.editor_defaults.formatter = Some(Formatter::External {
2132 command: "awk".to_string(),
2133 arguments: vec!["{sub(/two/,\"{buffer_path}\")}1".to_string()],
2134 });
2135 });
2136 });
2137 project_b
2138 .update(cx_b, |project, cx| {
2139 project.format(
2140 HashSet::from_iter([buffer_b.clone()]),
2141 true,
2142 FormatTrigger::Save,
2143 cx,
2144 )
2145 })
2146 .await
2147 .unwrap();
2148 assert_eq!(
2149 buffer_b.read_with(cx_b, |buffer, _| buffer.text()),
2150 format!("let honey = \"{}/a.rs\"\n", directory.to_str().unwrap())
2151 );
2152}
2153
2154#[gpui::test(iterations = 10)]
2155async fn test_definition(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
2156 cx_a.foreground().forbid_parking();
2157 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
2158 let client_a = server.create_client(cx_a, "user_a").await;
2159 let client_b = server.create_client(cx_b, "user_b").await;
2160 let (room_id, _rooms) = server
2161 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
2162 .await;
2163
2164 // Set up a fake language server.
2165 let mut language = Language::new(
2166 LanguageConfig {
2167 name: "Rust".into(),
2168 path_suffixes: vec!["rs".to_string()],
2169 ..Default::default()
2170 },
2171 Some(tree_sitter_rust::language()),
2172 );
2173 let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default()).await;
2174 client_a.language_registry.add(Arc::new(language));
2175
2176 client_a
2177 .fs
2178 .insert_tree(
2179 "/root",
2180 json!({
2181 "dir-1": {
2182 "a.rs": "const ONE: usize = b::TWO + b::THREE;",
2183 },
2184 "dir-2": {
2185 "b.rs": "const TWO: c::T2 = 2;\nconst THREE: usize = 3;",
2186 "c.rs": "type T2 = usize;",
2187 }
2188 }),
2189 )
2190 .await;
2191 let (project_a, worktree_id) = client_a.build_local_project("/root/dir-1", cx_a).await;
2192 let project_id = project_a
2193 .update(cx_a, |project, cx| project.share(room_id, cx))
2194 .await
2195 .unwrap();
2196 let project_b = client_b.build_remote_project(project_id, cx_b).await;
2197
2198 // Open the file on client B.
2199 let buffer_b = cx_b
2200 .background()
2201 .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
2202 .await
2203 .unwrap();
2204
2205 // Request the definition of a symbol as the guest.
2206 let fake_language_server = fake_language_servers.next().await.unwrap();
2207 fake_language_server.handle_request::<lsp::request::GotoDefinition, _, _>(|_, _| async move {
2208 Ok(Some(lsp::GotoDefinitionResponse::Scalar(
2209 lsp::Location::new(
2210 lsp::Url::from_file_path("/root/dir-2/b.rs").unwrap(),
2211 lsp::Range::new(lsp::Position::new(0, 6), lsp::Position::new(0, 9)),
2212 ),
2213 )))
2214 });
2215
2216 let definitions_1 = project_b
2217 .update(cx_b, |p, cx| p.definition(&buffer_b, 23, cx))
2218 .await
2219 .unwrap();
2220 cx_b.read(|cx| {
2221 assert_eq!(definitions_1.len(), 1);
2222 assert_eq!(project_b.read(cx).worktrees(cx).count(), 2);
2223 let target_buffer = definitions_1[0].target.buffer.read(cx);
2224 assert_eq!(
2225 target_buffer.text(),
2226 "const TWO: c::T2 = 2;\nconst THREE: usize = 3;"
2227 );
2228 assert_eq!(
2229 definitions_1[0].target.range.to_point(target_buffer),
2230 Point::new(0, 6)..Point::new(0, 9)
2231 );
2232 });
2233
2234 // Try getting more definitions for the same buffer, ensuring the buffer gets reused from
2235 // the previous call to `definition`.
2236 fake_language_server.handle_request::<lsp::request::GotoDefinition, _, _>(|_, _| async move {
2237 Ok(Some(lsp::GotoDefinitionResponse::Scalar(
2238 lsp::Location::new(
2239 lsp::Url::from_file_path("/root/dir-2/b.rs").unwrap(),
2240 lsp::Range::new(lsp::Position::new(1, 6), lsp::Position::new(1, 11)),
2241 ),
2242 )))
2243 });
2244
2245 let definitions_2 = project_b
2246 .update(cx_b, |p, cx| p.definition(&buffer_b, 33, cx))
2247 .await
2248 .unwrap();
2249 cx_b.read(|cx| {
2250 assert_eq!(definitions_2.len(), 1);
2251 assert_eq!(project_b.read(cx).worktrees(cx).count(), 2);
2252 let target_buffer = definitions_2[0].target.buffer.read(cx);
2253 assert_eq!(
2254 target_buffer.text(),
2255 "const TWO: c::T2 = 2;\nconst THREE: usize = 3;"
2256 );
2257 assert_eq!(
2258 definitions_2[0].target.range.to_point(target_buffer),
2259 Point::new(1, 6)..Point::new(1, 11)
2260 );
2261 });
2262 assert_eq!(
2263 definitions_1[0].target.buffer,
2264 definitions_2[0].target.buffer
2265 );
2266
2267 fake_language_server.handle_request::<lsp::request::GotoTypeDefinition, _, _>(
2268 |req, _| async move {
2269 assert_eq!(
2270 req.text_document_position_params.position,
2271 lsp::Position::new(0, 7)
2272 );
2273 Ok(Some(lsp::GotoDefinitionResponse::Scalar(
2274 lsp::Location::new(
2275 lsp::Url::from_file_path("/root/dir-2/c.rs").unwrap(),
2276 lsp::Range::new(lsp::Position::new(0, 5), lsp::Position::new(0, 7)),
2277 ),
2278 )))
2279 },
2280 );
2281
2282 let type_definitions = project_b
2283 .update(cx_b, |p, cx| p.type_definition(&buffer_b, 7, cx))
2284 .await
2285 .unwrap();
2286 cx_b.read(|cx| {
2287 assert_eq!(type_definitions.len(), 1);
2288 let target_buffer = type_definitions[0].target.buffer.read(cx);
2289 assert_eq!(target_buffer.text(), "type T2 = usize;");
2290 assert_eq!(
2291 type_definitions[0].target.range.to_point(target_buffer),
2292 Point::new(0, 5)..Point::new(0, 7)
2293 );
2294 });
2295}
2296
2297#[gpui::test(iterations = 10)]
2298async fn test_references(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
2299 cx_a.foreground().forbid_parking();
2300 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
2301 let client_a = server.create_client(cx_a, "user_a").await;
2302 let client_b = server.create_client(cx_b, "user_b").await;
2303 let (room_id, _rooms) = server
2304 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
2305 .await;
2306
2307 // Set up a fake language server.
2308 let mut language = Language::new(
2309 LanguageConfig {
2310 name: "Rust".into(),
2311 path_suffixes: vec!["rs".to_string()],
2312 ..Default::default()
2313 },
2314 Some(tree_sitter_rust::language()),
2315 );
2316 let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default()).await;
2317 client_a.language_registry.add(Arc::new(language));
2318
2319 client_a
2320 .fs
2321 .insert_tree(
2322 "/root",
2323 json!({
2324 "dir-1": {
2325 "one.rs": "const ONE: usize = 1;",
2326 "two.rs": "const TWO: usize = one::ONE + one::ONE;",
2327 },
2328 "dir-2": {
2329 "three.rs": "const THREE: usize = two::TWO + one::ONE;",
2330 }
2331 }),
2332 )
2333 .await;
2334 let (project_a, worktree_id) = client_a.build_local_project("/root/dir-1", cx_a).await;
2335 let project_id = project_a
2336 .update(cx_a, |project, cx| project.share(room_id, cx))
2337 .await
2338 .unwrap();
2339 let project_b = client_b.build_remote_project(project_id, cx_b).await;
2340
2341 // Open the file on client B.
2342 let buffer_b = cx_b
2343 .background()
2344 .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "one.rs"), cx)))
2345 .await
2346 .unwrap();
2347
2348 // Request references to a symbol as the guest.
2349 let fake_language_server = fake_language_servers.next().await.unwrap();
2350 fake_language_server.handle_request::<lsp::request::References, _, _>(|params, _| async move {
2351 assert_eq!(
2352 params.text_document_position.text_document.uri.as_str(),
2353 "file:///root/dir-1/one.rs"
2354 );
2355 Ok(Some(vec![
2356 lsp::Location {
2357 uri: lsp::Url::from_file_path("/root/dir-1/two.rs").unwrap(),
2358 range: lsp::Range::new(lsp::Position::new(0, 24), lsp::Position::new(0, 27)),
2359 },
2360 lsp::Location {
2361 uri: lsp::Url::from_file_path("/root/dir-1/two.rs").unwrap(),
2362 range: lsp::Range::new(lsp::Position::new(0, 35), lsp::Position::new(0, 38)),
2363 },
2364 lsp::Location {
2365 uri: lsp::Url::from_file_path("/root/dir-2/three.rs").unwrap(),
2366 range: lsp::Range::new(lsp::Position::new(0, 37), lsp::Position::new(0, 40)),
2367 },
2368 ]))
2369 });
2370
2371 let references = project_b
2372 .update(cx_b, |p, cx| p.references(&buffer_b, 7, cx))
2373 .await
2374 .unwrap();
2375 cx_b.read(|cx| {
2376 assert_eq!(references.len(), 3);
2377 assert_eq!(project_b.read(cx).worktrees(cx).count(), 2);
2378
2379 let two_buffer = references[0].buffer.read(cx);
2380 let three_buffer = references[2].buffer.read(cx);
2381 assert_eq!(
2382 two_buffer.file().unwrap().path().as_ref(),
2383 Path::new("two.rs")
2384 );
2385 assert_eq!(references[1].buffer, references[0].buffer);
2386 assert_eq!(
2387 three_buffer.file().unwrap().full_path(cx),
2388 Path::new("three.rs")
2389 );
2390
2391 assert_eq!(references[0].range.to_offset(two_buffer), 24..27);
2392 assert_eq!(references[1].range.to_offset(two_buffer), 35..38);
2393 assert_eq!(references[2].range.to_offset(three_buffer), 37..40);
2394 });
2395}
2396
2397#[gpui::test(iterations = 10)]
2398async fn test_project_search(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
2399 cx_a.foreground().forbid_parking();
2400 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
2401 let client_a = server.create_client(cx_a, "user_a").await;
2402 let client_b = server.create_client(cx_b, "user_b").await;
2403 let (room_id, _rooms) = server
2404 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
2405 .await;
2406
2407 client_a
2408 .fs
2409 .insert_tree(
2410 "/root",
2411 json!({
2412 "dir-1": {
2413 "a": "hello world",
2414 "b": "goodnight moon",
2415 "c": "a world of goo",
2416 "d": "world champion of clown world",
2417 },
2418 "dir-2": {
2419 "e": "disney world is fun",
2420 }
2421 }),
2422 )
2423 .await;
2424 let (project_a, _) = client_a.build_local_project("/root/dir-1", cx_a).await;
2425 let (worktree_2, _) = project_a
2426 .update(cx_a, |p, cx| {
2427 p.find_or_create_local_worktree("/root/dir-2", true, cx)
2428 })
2429 .await
2430 .unwrap();
2431 worktree_2
2432 .read_with(cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2433 .await;
2434 let project_id = project_a
2435 .update(cx_a, |project, cx| project.share(room_id, cx))
2436 .await
2437 .unwrap();
2438
2439 let project_b = client_b.build_remote_project(project_id, cx_b).await;
2440
2441 // Perform a search as the guest.
2442 let results = project_b
2443 .update(cx_b, |project, cx| {
2444 project.search(SearchQuery::text("world", false, false), cx)
2445 })
2446 .await
2447 .unwrap();
2448
2449 let mut ranges_by_path = results
2450 .into_iter()
2451 .map(|(buffer, ranges)| {
2452 buffer.read_with(cx_b, |buffer, cx| {
2453 let path = buffer.file().unwrap().full_path(cx);
2454 let offset_ranges = ranges
2455 .into_iter()
2456 .map(|range| range.to_offset(buffer))
2457 .collect::<Vec<_>>();
2458 (path, offset_ranges)
2459 })
2460 })
2461 .collect::<Vec<_>>();
2462 ranges_by_path.sort_by_key(|(path, _)| path.clone());
2463
2464 assert_eq!(
2465 ranges_by_path,
2466 &[
2467 (PathBuf::from("dir-1/a"), vec![6..11]),
2468 (PathBuf::from("dir-1/c"), vec![2..7]),
2469 (PathBuf::from("dir-1/d"), vec![0..5, 24..29]),
2470 (PathBuf::from("dir-2/e"), vec![7..12]),
2471 ]
2472 );
2473}
2474
2475#[gpui::test(iterations = 10)]
2476async fn test_document_highlights(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
2477 cx_a.foreground().forbid_parking();
2478 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
2479 let client_a = server.create_client(cx_a, "user_a").await;
2480 let client_b = server.create_client(cx_b, "user_b").await;
2481 let (room_id, _rooms) = server
2482 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
2483 .await;
2484
2485 client_a
2486 .fs
2487 .insert_tree(
2488 "/root-1",
2489 json!({
2490 "main.rs": "fn double(number: i32) -> i32 { number + number }",
2491 }),
2492 )
2493 .await;
2494
2495 // Set up a fake language server.
2496 let mut language = Language::new(
2497 LanguageConfig {
2498 name: "Rust".into(),
2499 path_suffixes: vec!["rs".to_string()],
2500 ..Default::default()
2501 },
2502 Some(tree_sitter_rust::language()),
2503 );
2504 let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default()).await;
2505 client_a.language_registry.add(Arc::new(language));
2506
2507 let (project_a, worktree_id) = client_a.build_local_project("/root-1", cx_a).await;
2508 let project_id = project_a
2509 .update(cx_a, |project, cx| project.share(room_id, cx))
2510 .await
2511 .unwrap();
2512 let project_b = client_b.build_remote_project(project_id, cx_b).await;
2513
2514 // Open the file on client B.
2515 let buffer_b = cx_b
2516 .background()
2517 .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "main.rs"), cx)))
2518 .await
2519 .unwrap();
2520
2521 // Request document highlights as the guest.
2522 let fake_language_server = fake_language_servers.next().await.unwrap();
2523 fake_language_server.handle_request::<lsp::request::DocumentHighlightRequest, _, _>(
2524 |params, _| async move {
2525 assert_eq!(
2526 params
2527 .text_document_position_params
2528 .text_document
2529 .uri
2530 .as_str(),
2531 "file:///root-1/main.rs"
2532 );
2533 assert_eq!(
2534 params.text_document_position_params.position,
2535 lsp::Position::new(0, 34)
2536 );
2537 Ok(Some(vec![
2538 lsp::DocumentHighlight {
2539 kind: Some(lsp::DocumentHighlightKind::WRITE),
2540 range: lsp::Range::new(lsp::Position::new(0, 10), lsp::Position::new(0, 16)),
2541 },
2542 lsp::DocumentHighlight {
2543 kind: Some(lsp::DocumentHighlightKind::READ),
2544 range: lsp::Range::new(lsp::Position::new(0, 32), lsp::Position::new(0, 38)),
2545 },
2546 lsp::DocumentHighlight {
2547 kind: Some(lsp::DocumentHighlightKind::READ),
2548 range: lsp::Range::new(lsp::Position::new(0, 41), lsp::Position::new(0, 47)),
2549 },
2550 ]))
2551 },
2552 );
2553
2554 let highlights = project_b
2555 .update(cx_b, |p, cx| p.document_highlights(&buffer_b, 34, cx))
2556 .await
2557 .unwrap();
2558 buffer_b.read_with(cx_b, |buffer, _| {
2559 let snapshot = buffer.snapshot();
2560
2561 let highlights = highlights
2562 .into_iter()
2563 .map(|highlight| (highlight.kind, highlight.range.to_offset(&snapshot)))
2564 .collect::<Vec<_>>();
2565 assert_eq!(
2566 highlights,
2567 &[
2568 (lsp::DocumentHighlightKind::WRITE, 10..16),
2569 (lsp::DocumentHighlightKind::READ, 32..38),
2570 (lsp::DocumentHighlightKind::READ, 41..47)
2571 ]
2572 )
2573 });
2574}
2575
2576#[gpui::test(iterations = 10)]
2577async fn test_lsp_hover(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
2578 cx_a.foreground().forbid_parking();
2579 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
2580 let client_a = server.create_client(cx_a, "user_a").await;
2581 let client_b = server.create_client(cx_b, "user_b").await;
2582 let (room_id, _rooms) = server
2583 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
2584 .await;
2585
2586 client_a
2587 .fs
2588 .insert_tree(
2589 "/root-1",
2590 json!({
2591 "main.rs": "use std::collections::HashMap;",
2592 }),
2593 )
2594 .await;
2595
2596 // Set up a fake language server.
2597 let mut language = Language::new(
2598 LanguageConfig {
2599 name: "Rust".into(),
2600 path_suffixes: vec!["rs".to_string()],
2601 ..Default::default()
2602 },
2603 Some(tree_sitter_rust::language()),
2604 );
2605 let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default()).await;
2606 client_a.language_registry.add(Arc::new(language));
2607
2608 let (project_a, worktree_id) = client_a.build_local_project("/root-1", cx_a).await;
2609 let project_id = project_a
2610 .update(cx_a, |project, cx| project.share(room_id, cx))
2611 .await
2612 .unwrap();
2613 let project_b = client_b.build_remote_project(project_id, cx_b).await;
2614
2615 // Open the file as the guest
2616 let buffer_b = cx_b
2617 .background()
2618 .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "main.rs"), cx)))
2619 .await
2620 .unwrap();
2621
2622 // Request hover information as the guest.
2623 let fake_language_server = fake_language_servers.next().await.unwrap();
2624 fake_language_server.handle_request::<lsp::request::HoverRequest, _, _>(
2625 |params, _| async move {
2626 assert_eq!(
2627 params
2628 .text_document_position_params
2629 .text_document
2630 .uri
2631 .as_str(),
2632 "file:///root-1/main.rs"
2633 );
2634 assert_eq!(
2635 params.text_document_position_params.position,
2636 lsp::Position::new(0, 22)
2637 );
2638 Ok(Some(lsp::Hover {
2639 contents: lsp::HoverContents::Array(vec![
2640 lsp::MarkedString::String("Test hover content.".to_string()),
2641 lsp::MarkedString::LanguageString(lsp::LanguageString {
2642 language: "Rust".to_string(),
2643 value: "let foo = 42;".to_string(),
2644 }),
2645 ]),
2646 range: Some(lsp::Range::new(
2647 lsp::Position::new(0, 22),
2648 lsp::Position::new(0, 29),
2649 )),
2650 }))
2651 },
2652 );
2653
2654 let hover_info = project_b
2655 .update(cx_b, |p, cx| p.hover(&buffer_b, 22, cx))
2656 .await
2657 .unwrap()
2658 .unwrap();
2659 buffer_b.read_with(cx_b, |buffer, _| {
2660 let snapshot = buffer.snapshot();
2661 assert_eq!(hover_info.range.unwrap().to_offset(&snapshot), 22..29);
2662 assert_eq!(
2663 hover_info.contents,
2664 vec![
2665 project::HoverBlock {
2666 text: "Test hover content.".to_string(),
2667 language: None,
2668 },
2669 project::HoverBlock {
2670 text: "let foo = 42;".to_string(),
2671 language: Some("Rust".to_string()),
2672 }
2673 ]
2674 );
2675 });
2676}
2677
2678#[gpui::test(iterations = 10)]
2679async fn test_project_symbols(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
2680 cx_a.foreground().forbid_parking();
2681 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
2682 let client_a = server.create_client(cx_a, "user_a").await;
2683 let client_b = server.create_client(cx_b, "user_b").await;
2684 let (room_id, _rooms) = server
2685 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
2686 .await;
2687
2688 // Set up a fake language server.
2689 let mut language = Language::new(
2690 LanguageConfig {
2691 name: "Rust".into(),
2692 path_suffixes: vec!["rs".to_string()],
2693 ..Default::default()
2694 },
2695 Some(tree_sitter_rust::language()),
2696 );
2697 let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default()).await;
2698 client_a.language_registry.add(Arc::new(language));
2699
2700 client_a
2701 .fs
2702 .insert_tree(
2703 "/code",
2704 json!({
2705 "crate-1": {
2706 "one.rs": "const ONE: usize = 1;",
2707 },
2708 "crate-2": {
2709 "two.rs": "const TWO: usize = 2; const THREE: usize = 3;",
2710 },
2711 "private": {
2712 "passwords.txt": "the-password",
2713 }
2714 }),
2715 )
2716 .await;
2717 let (project_a, worktree_id) = client_a.build_local_project("/code/crate-1", cx_a).await;
2718 let project_id = project_a
2719 .update(cx_a, |project, cx| project.share(room_id, cx))
2720 .await
2721 .unwrap();
2722 let project_b = client_b.build_remote_project(project_id, cx_b).await;
2723
2724 // Cause the language server to start.
2725 let _buffer = cx_b
2726 .background()
2727 .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "one.rs"), cx)))
2728 .await
2729 .unwrap();
2730
2731 let fake_language_server = fake_language_servers.next().await.unwrap();
2732 fake_language_server.handle_request::<lsp::request::WorkspaceSymbol, _, _>(|_, _| async move {
2733 #[allow(deprecated)]
2734 Ok(Some(vec![lsp::SymbolInformation {
2735 name: "TWO".into(),
2736 location: lsp::Location {
2737 uri: lsp::Url::from_file_path("/code/crate-2/two.rs").unwrap(),
2738 range: lsp::Range::new(lsp::Position::new(0, 6), lsp::Position::new(0, 9)),
2739 },
2740 kind: lsp::SymbolKind::CONSTANT,
2741 tags: None,
2742 container_name: None,
2743 deprecated: None,
2744 }]))
2745 });
2746
2747 // Request the definition of a symbol as the guest.
2748 let symbols = project_b
2749 .update(cx_b, |p, cx| p.symbols("two", cx))
2750 .await
2751 .unwrap();
2752 assert_eq!(symbols.len(), 1);
2753 assert_eq!(symbols[0].name, "TWO");
2754
2755 // Open one of the returned symbols.
2756 let buffer_b_2 = project_b
2757 .update(cx_b, |project, cx| {
2758 project.open_buffer_for_symbol(&symbols[0], cx)
2759 })
2760 .await
2761 .unwrap();
2762 buffer_b_2.read_with(cx_b, |buffer, _| {
2763 assert_eq!(
2764 buffer.file().unwrap().path().as_ref(),
2765 Path::new("../crate-2/two.rs")
2766 );
2767 });
2768
2769 // Attempt to craft a symbol and violate host's privacy by opening an arbitrary file.
2770 let mut fake_symbol = symbols[0].clone();
2771 fake_symbol.path.path = Path::new("/code/secrets").into();
2772 let error = project_b
2773 .update(cx_b, |project, cx| {
2774 project.open_buffer_for_symbol(&fake_symbol, cx)
2775 })
2776 .await
2777 .unwrap_err();
2778 assert!(error.to_string().contains("invalid symbol signature"));
2779}
2780
2781#[gpui::test(iterations = 10)]
2782async fn test_open_buffer_while_getting_definition_pointing_to_it(
2783 cx_a: &mut TestAppContext,
2784 cx_b: &mut TestAppContext,
2785 mut rng: StdRng,
2786) {
2787 cx_a.foreground().forbid_parking();
2788 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
2789 let client_a = server.create_client(cx_a, "user_a").await;
2790 let client_b = server.create_client(cx_b, "user_b").await;
2791 let (room_id, _rooms) = server
2792 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
2793 .await;
2794
2795 // Set up a fake language server.
2796 let mut language = Language::new(
2797 LanguageConfig {
2798 name: "Rust".into(),
2799 path_suffixes: vec!["rs".to_string()],
2800 ..Default::default()
2801 },
2802 Some(tree_sitter_rust::language()),
2803 );
2804 let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default()).await;
2805 client_a.language_registry.add(Arc::new(language));
2806
2807 client_a
2808 .fs
2809 .insert_tree(
2810 "/root",
2811 json!({
2812 "a.rs": "const ONE: usize = b::TWO;",
2813 "b.rs": "const TWO: usize = 2",
2814 }),
2815 )
2816 .await;
2817 let (project_a, worktree_id) = client_a.build_local_project("/root", cx_a).await;
2818 let project_id = project_a
2819 .update(cx_a, |project, cx| project.share(room_id, cx))
2820 .await
2821 .unwrap();
2822 let project_b = client_b.build_remote_project(project_id, cx_b).await;
2823
2824 let buffer_b1 = cx_b
2825 .background()
2826 .spawn(project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
2827 .await
2828 .unwrap();
2829
2830 let fake_language_server = fake_language_servers.next().await.unwrap();
2831 fake_language_server.handle_request::<lsp::request::GotoDefinition, _, _>(|_, _| async move {
2832 Ok(Some(lsp::GotoDefinitionResponse::Scalar(
2833 lsp::Location::new(
2834 lsp::Url::from_file_path("/root/b.rs").unwrap(),
2835 lsp::Range::new(lsp::Position::new(0, 6), lsp::Position::new(0, 9)),
2836 ),
2837 )))
2838 });
2839
2840 let definitions;
2841 let buffer_b2;
2842 if rng.gen() {
2843 definitions = project_b.update(cx_b, |p, cx| p.definition(&buffer_b1, 23, cx));
2844 buffer_b2 = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "b.rs"), cx));
2845 } else {
2846 buffer_b2 = project_b.update(cx_b, |p, cx| p.open_buffer((worktree_id, "b.rs"), cx));
2847 definitions = project_b.update(cx_b, |p, cx| p.definition(&buffer_b1, 23, cx));
2848 }
2849
2850 let buffer_b2 = buffer_b2.await.unwrap();
2851 let definitions = definitions.await.unwrap();
2852 assert_eq!(definitions.len(), 1);
2853 assert_eq!(definitions[0].target.buffer, buffer_b2);
2854}
2855
2856#[gpui::test(iterations = 10)]
2857async fn test_collaborating_with_code_actions(
2858 cx_a: &mut TestAppContext,
2859 cx_b: &mut TestAppContext,
2860) {
2861 cx_a.foreground().forbid_parking();
2862 cx_b.update(editor::init);
2863 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
2864 let client_a = server.create_client(cx_a, "user_a").await;
2865 let client_b = server.create_client(cx_b, "user_b").await;
2866 let (room_id, _rooms) = server
2867 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
2868 .await;
2869
2870 // Set up a fake language server.
2871 let mut language = Language::new(
2872 LanguageConfig {
2873 name: "Rust".into(),
2874 path_suffixes: vec!["rs".to_string()],
2875 ..Default::default()
2876 },
2877 Some(tree_sitter_rust::language()),
2878 );
2879 let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default()).await;
2880 client_a.language_registry.add(Arc::new(language));
2881
2882 client_a
2883 .fs
2884 .insert_tree(
2885 "/a",
2886 json!({
2887 "main.rs": "mod other;\nfn main() { let foo = other::foo(); }",
2888 "other.rs": "pub fn foo() -> usize { 4 }",
2889 }),
2890 )
2891 .await;
2892 let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
2893 let project_id = project_a
2894 .update(cx_a, |project, cx| project.share(room_id, cx))
2895 .await
2896 .unwrap();
2897
2898 // Join the project as client B.
2899 let project_b = client_b.build_remote_project(project_id, cx_b).await;
2900 let (_window_b, workspace_b) =
2901 cx_b.add_window(|cx| Workspace::new(project_b.clone(), |_, _| unimplemented!(), cx));
2902 let editor_b = workspace_b
2903 .update(cx_b, |workspace, cx| {
2904 workspace.open_path((worktree_id, "main.rs"), true, cx)
2905 })
2906 .await
2907 .unwrap()
2908 .downcast::<Editor>()
2909 .unwrap();
2910
2911 let mut fake_language_server = fake_language_servers.next().await.unwrap();
2912 fake_language_server
2913 .handle_request::<lsp::request::CodeActionRequest, _, _>(|params, _| async move {
2914 assert_eq!(
2915 params.text_document.uri,
2916 lsp::Url::from_file_path("/a/main.rs").unwrap(),
2917 );
2918 assert_eq!(params.range.start, lsp::Position::new(0, 0));
2919 assert_eq!(params.range.end, lsp::Position::new(0, 0));
2920 Ok(None)
2921 })
2922 .next()
2923 .await;
2924
2925 // Move cursor to a location that contains code actions.
2926 editor_b.update(cx_b, |editor, cx| {
2927 editor.change_selections(None, cx, |s| {
2928 s.select_ranges([Point::new(1, 31)..Point::new(1, 31)])
2929 });
2930 cx.focus(&editor_b);
2931 });
2932
2933 fake_language_server
2934 .handle_request::<lsp::request::CodeActionRequest, _, _>(|params, _| async move {
2935 assert_eq!(
2936 params.text_document.uri,
2937 lsp::Url::from_file_path("/a/main.rs").unwrap(),
2938 );
2939 assert_eq!(params.range.start, lsp::Position::new(1, 31));
2940 assert_eq!(params.range.end, lsp::Position::new(1, 31));
2941
2942 Ok(Some(vec![lsp::CodeActionOrCommand::CodeAction(
2943 lsp::CodeAction {
2944 title: "Inline into all callers".to_string(),
2945 edit: Some(lsp::WorkspaceEdit {
2946 changes: Some(
2947 [
2948 (
2949 lsp::Url::from_file_path("/a/main.rs").unwrap(),
2950 vec![lsp::TextEdit::new(
2951 lsp::Range::new(
2952 lsp::Position::new(1, 22),
2953 lsp::Position::new(1, 34),
2954 ),
2955 "4".to_string(),
2956 )],
2957 ),
2958 (
2959 lsp::Url::from_file_path("/a/other.rs").unwrap(),
2960 vec![lsp::TextEdit::new(
2961 lsp::Range::new(
2962 lsp::Position::new(0, 0),
2963 lsp::Position::new(0, 27),
2964 ),
2965 "".to_string(),
2966 )],
2967 ),
2968 ]
2969 .into_iter()
2970 .collect(),
2971 ),
2972 ..Default::default()
2973 }),
2974 data: Some(json!({
2975 "codeActionParams": {
2976 "range": {
2977 "start": {"line": 1, "column": 31},
2978 "end": {"line": 1, "column": 31},
2979 }
2980 }
2981 })),
2982 ..Default::default()
2983 },
2984 )]))
2985 })
2986 .next()
2987 .await;
2988
2989 // Toggle code actions and wait for them to display.
2990 editor_b.update(cx_b, |editor, cx| {
2991 editor.toggle_code_actions(
2992 &ToggleCodeActions {
2993 deployed_from_indicator: false,
2994 },
2995 cx,
2996 );
2997 });
2998 editor_b
2999 .condition(cx_b, |editor, _| editor.context_menu_visible())
3000 .await;
3001
3002 fake_language_server.remove_request_handler::<lsp::request::CodeActionRequest>();
3003
3004 // Confirming the code action will trigger a resolve request.
3005 let confirm_action = workspace_b
3006 .update(cx_b, |workspace, cx| {
3007 Editor::confirm_code_action(workspace, &ConfirmCodeAction { item_ix: Some(0) }, cx)
3008 })
3009 .unwrap();
3010 fake_language_server.handle_request::<lsp::request::CodeActionResolveRequest, _, _>(
3011 |_, _| async move {
3012 Ok(lsp::CodeAction {
3013 title: "Inline into all callers".to_string(),
3014 edit: Some(lsp::WorkspaceEdit {
3015 changes: Some(
3016 [
3017 (
3018 lsp::Url::from_file_path("/a/main.rs").unwrap(),
3019 vec![lsp::TextEdit::new(
3020 lsp::Range::new(
3021 lsp::Position::new(1, 22),
3022 lsp::Position::new(1, 34),
3023 ),
3024 "4".to_string(),
3025 )],
3026 ),
3027 (
3028 lsp::Url::from_file_path("/a/other.rs").unwrap(),
3029 vec![lsp::TextEdit::new(
3030 lsp::Range::new(
3031 lsp::Position::new(0, 0),
3032 lsp::Position::new(0, 27),
3033 ),
3034 "".to_string(),
3035 )],
3036 ),
3037 ]
3038 .into_iter()
3039 .collect(),
3040 ),
3041 ..Default::default()
3042 }),
3043 ..Default::default()
3044 })
3045 },
3046 );
3047
3048 // After the action is confirmed, an editor containing both modified files is opened.
3049 confirm_action.await.unwrap();
3050 let code_action_editor = workspace_b.read_with(cx_b, |workspace, cx| {
3051 workspace
3052 .active_item(cx)
3053 .unwrap()
3054 .downcast::<Editor>()
3055 .unwrap()
3056 });
3057 code_action_editor.update(cx_b, |editor, cx| {
3058 assert_eq!(editor.text(cx), "mod other;\nfn main() { let foo = 4; }\n");
3059 editor.undo(&Undo, cx);
3060 assert_eq!(
3061 editor.text(cx),
3062 "mod other;\nfn main() { let foo = other::foo(); }\npub fn foo() -> usize { 4 }"
3063 );
3064 editor.redo(&Redo, cx);
3065 assert_eq!(editor.text(cx), "mod other;\nfn main() { let foo = 4; }\n");
3066 });
3067}
3068
3069#[gpui::test(iterations = 10)]
3070async fn test_collaborating_with_renames(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
3071 cx_a.foreground().forbid_parking();
3072 cx_b.update(editor::init);
3073 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
3074 let client_a = server.create_client(cx_a, "user_a").await;
3075 let client_b = server.create_client(cx_b, "user_b").await;
3076 let (room_id, _rooms) = server
3077 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
3078 .await;
3079
3080 // Set up a fake language server.
3081 let mut language = Language::new(
3082 LanguageConfig {
3083 name: "Rust".into(),
3084 path_suffixes: vec!["rs".to_string()],
3085 ..Default::default()
3086 },
3087 Some(tree_sitter_rust::language()),
3088 );
3089 let mut fake_language_servers = language
3090 .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
3091 capabilities: lsp::ServerCapabilities {
3092 rename_provider: Some(lsp::OneOf::Right(lsp::RenameOptions {
3093 prepare_provider: Some(true),
3094 work_done_progress_options: Default::default(),
3095 })),
3096 ..Default::default()
3097 },
3098 ..Default::default()
3099 }))
3100 .await;
3101 client_a.language_registry.add(Arc::new(language));
3102
3103 client_a
3104 .fs
3105 .insert_tree(
3106 "/dir",
3107 json!({
3108 "one.rs": "const ONE: usize = 1;",
3109 "two.rs": "const TWO: usize = one::ONE + one::ONE;"
3110 }),
3111 )
3112 .await;
3113 let (project_a, worktree_id) = client_a.build_local_project("/dir", cx_a).await;
3114 let project_id = project_a
3115 .update(cx_a, |project, cx| project.share(room_id, cx))
3116 .await
3117 .unwrap();
3118 let project_b = client_b.build_remote_project(project_id, cx_b).await;
3119
3120 let (_window_b, workspace_b) =
3121 cx_b.add_window(|cx| Workspace::new(project_b.clone(), |_, _| unimplemented!(), cx));
3122 let editor_b = workspace_b
3123 .update(cx_b, |workspace, cx| {
3124 workspace.open_path((worktree_id, "one.rs"), true, cx)
3125 })
3126 .await
3127 .unwrap()
3128 .downcast::<Editor>()
3129 .unwrap();
3130 let fake_language_server = fake_language_servers.next().await.unwrap();
3131
3132 // Move cursor to a location that can be renamed.
3133 let prepare_rename = editor_b.update(cx_b, |editor, cx| {
3134 editor.change_selections(None, cx, |s| s.select_ranges([7..7]));
3135 editor.rename(&Rename, cx).unwrap()
3136 });
3137
3138 fake_language_server
3139 .handle_request::<lsp::request::PrepareRenameRequest, _, _>(|params, _| async move {
3140 assert_eq!(params.text_document.uri.as_str(), "file:///dir/one.rs");
3141 assert_eq!(params.position, lsp::Position::new(0, 7));
3142 Ok(Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(
3143 lsp::Position::new(0, 6),
3144 lsp::Position::new(0, 9),
3145 ))))
3146 })
3147 .next()
3148 .await
3149 .unwrap();
3150 prepare_rename.await.unwrap();
3151 editor_b.update(cx_b, |editor, cx| {
3152 let rename = editor.pending_rename().unwrap();
3153 let buffer = editor.buffer().read(cx).snapshot(cx);
3154 assert_eq!(
3155 rename.range.start.to_offset(&buffer)..rename.range.end.to_offset(&buffer),
3156 6..9
3157 );
3158 rename.editor.update(cx, |rename_editor, cx| {
3159 rename_editor.buffer().update(cx, |rename_buffer, cx| {
3160 rename_buffer.edit([(0..3, "THREE")], None, cx);
3161 });
3162 });
3163 });
3164
3165 let confirm_rename = workspace_b.update(cx_b, |workspace, cx| {
3166 Editor::confirm_rename(workspace, &ConfirmRename, cx).unwrap()
3167 });
3168 fake_language_server
3169 .handle_request::<lsp::request::Rename, _, _>(|params, _| async move {
3170 assert_eq!(
3171 params.text_document_position.text_document.uri.as_str(),
3172 "file:///dir/one.rs"
3173 );
3174 assert_eq!(
3175 params.text_document_position.position,
3176 lsp::Position::new(0, 6)
3177 );
3178 assert_eq!(params.new_name, "THREE");
3179 Ok(Some(lsp::WorkspaceEdit {
3180 changes: Some(
3181 [
3182 (
3183 lsp::Url::from_file_path("/dir/one.rs").unwrap(),
3184 vec![lsp::TextEdit::new(
3185 lsp::Range::new(lsp::Position::new(0, 6), lsp::Position::new(0, 9)),
3186 "THREE".to_string(),
3187 )],
3188 ),
3189 (
3190 lsp::Url::from_file_path("/dir/two.rs").unwrap(),
3191 vec![
3192 lsp::TextEdit::new(
3193 lsp::Range::new(
3194 lsp::Position::new(0, 24),
3195 lsp::Position::new(0, 27),
3196 ),
3197 "THREE".to_string(),
3198 ),
3199 lsp::TextEdit::new(
3200 lsp::Range::new(
3201 lsp::Position::new(0, 35),
3202 lsp::Position::new(0, 38),
3203 ),
3204 "THREE".to_string(),
3205 ),
3206 ],
3207 ),
3208 ]
3209 .into_iter()
3210 .collect(),
3211 ),
3212 ..Default::default()
3213 }))
3214 })
3215 .next()
3216 .await
3217 .unwrap();
3218 confirm_rename.await.unwrap();
3219
3220 let rename_editor = workspace_b.read_with(cx_b, |workspace, cx| {
3221 workspace
3222 .active_item(cx)
3223 .unwrap()
3224 .downcast::<Editor>()
3225 .unwrap()
3226 });
3227 rename_editor.update(cx_b, |editor, cx| {
3228 assert_eq!(
3229 editor.text(cx),
3230 "const THREE: usize = 1;\nconst TWO: usize = one::THREE + one::THREE;"
3231 );
3232 editor.undo(&Undo, cx);
3233 assert_eq!(
3234 editor.text(cx),
3235 "const ONE: usize = 1;\nconst TWO: usize = one::ONE + one::ONE;"
3236 );
3237 editor.redo(&Redo, cx);
3238 assert_eq!(
3239 editor.text(cx),
3240 "const THREE: usize = 1;\nconst TWO: usize = one::THREE + one::THREE;"
3241 );
3242 });
3243
3244 // Ensure temporary rename edits cannot be undone/redone.
3245 editor_b.update(cx_b, |editor, cx| {
3246 editor.undo(&Undo, cx);
3247 assert_eq!(editor.text(cx), "const ONE: usize = 1;");
3248 editor.undo(&Undo, cx);
3249 assert_eq!(editor.text(cx), "const ONE: usize = 1;");
3250 editor.redo(&Redo, cx);
3251 assert_eq!(editor.text(cx), "const THREE: usize = 1;");
3252 })
3253}
3254
3255#[gpui::test(iterations = 10)]
3256async fn test_language_server_statuses(
3257 deterministic: Arc<Deterministic>,
3258 cx_a: &mut TestAppContext,
3259 cx_b: &mut TestAppContext,
3260) {
3261 deterministic.forbid_parking();
3262
3263 cx_b.update(editor::init);
3264 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
3265 let client_a = server.create_client(cx_a, "user_a").await;
3266 let client_b = server.create_client(cx_b, "user_b").await;
3267 let (room_id, _rooms) = server
3268 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
3269 .await;
3270
3271 // Set up a fake language server.
3272 let mut language = Language::new(
3273 LanguageConfig {
3274 name: "Rust".into(),
3275 path_suffixes: vec!["rs".to_string()],
3276 ..Default::default()
3277 },
3278 Some(tree_sitter_rust::language()),
3279 );
3280 let mut fake_language_servers = language
3281 .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
3282 name: "the-language-server",
3283 ..Default::default()
3284 }))
3285 .await;
3286 client_a.language_registry.add(Arc::new(language));
3287
3288 client_a
3289 .fs
3290 .insert_tree(
3291 "/dir",
3292 json!({
3293 "main.rs": "const ONE: usize = 1;",
3294 }),
3295 )
3296 .await;
3297 let (project_a, worktree_id) = client_a.build_local_project("/dir", cx_a).await;
3298
3299 let _buffer_a = project_a
3300 .update(cx_a, |p, cx| p.open_buffer((worktree_id, "main.rs"), cx))
3301 .await
3302 .unwrap();
3303
3304 let fake_language_server = fake_language_servers.next().await.unwrap();
3305 fake_language_server.start_progress("the-token").await;
3306 fake_language_server.notify::<lsp::notification::Progress>(lsp::ProgressParams {
3307 token: lsp::NumberOrString::String("the-token".to_string()),
3308 value: lsp::ProgressParamsValue::WorkDone(lsp::WorkDoneProgress::Report(
3309 lsp::WorkDoneProgressReport {
3310 message: Some("the-message".to_string()),
3311 ..Default::default()
3312 },
3313 )),
3314 });
3315 deterministic.run_until_parked();
3316 project_a.read_with(cx_a, |project, _| {
3317 let status = project.language_server_statuses().next().unwrap();
3318 assert_eq!(status.name, "the-language-server");
3319 assert_eq!(status.pending_work.len(), 1);
3320 assert_eq!(
3321 status.pending_work["the-token"].message.as_ref().unwrap(),
3322 "the-message"
3323 );
3324 });
3325
3326 let project_id = project_a
3327 .update(cx_a, |project, cx| project.share(room_id, cx))
3328 .await
3329 .unwrap();
3330 let project_b = client_b.build_remote_project(project_id, cx_b).await;
3331 project_b.read_with(cx_b, |project, _| {
3332 let status = project.language_server_statuses().next().unwrap();
3333 assert_eq!(status.name, "the-language-server");
3334 });
3335
3336 fake_language_server.notify::<lsp::notification::Progress>(lsp::ProgressParams {
3337 token: lsp::NumberOrString::String("the-token".to_string()),
3338 value: lsp::ProgressParamsValue::WorkDone(lsp::WorkDoneProgress::Report(
3339 lsp::WorkDoneProgressReport {
3340 message: Some("the-message-2".to_string()),
3341 ..Default::default()
3342 },
3343 )),
3344 });
3345 deterministic.run_until_parked();
3346 project_a.read_with(cx_a, |project, _| {
3347 let status = project.language_server_statuses().next().unwrap();
3348 assert_eq!(status.name, "the-language-server");
3349 assert_eq!(status.pending_work.len(), 1);
3350 assert_eq!(
3351 status.pending_work["the-token"].message.as_ref().unwrap(),
3352 "the-message-2"
3353 );
3354 });
3355 project_b.read_with(cx_b, |project, _| {
3356 let status = project.language_server_statuses().next().unwrap();
3357 assert_eq!(status.name, "the-language-server");
3358 assert_eq!(status.pending_work.len(), 1);
3359 assert_eq!(
3360 status.pending_work["the-token"].message.as_ref().unwrap(),
3361 "the-message-2"
3362 );
3363 });
3364}
3365
3366#[gpui::test(iterations = 10)]
3367async fn test_basic_chat(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
3368 cx_a.foreground().forbid_parking();
3369 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
3370 let client_a = server.create_client(cx_a, "user_a").await;
3371 let client_b = server.create_client(cx_b, "user_b").await;
3372
3373 // Create an org that includes these 2 users.
3374 let db = &server.app_state.db;
3375 let org_id = db.create_org("Test Org", "test-org").await.unwrap();
3376 db.add_org_member(org_id, client_a.current_user_id(cx_a), false)
3377 .await
3378 .unwrap();
3379 db.add_org_member(org_id, client_b.current_user_id(cx_b), false)
3380 .await
3381 .unwrap();
3382
3383 // Create a channel that includes all the users.
3384 let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
3385 db.add_channel_member(channel_id, client_a.current_user_id(cx_a), false)
3386 .await
3387 .unwrap();
3388 db.add_channel_member(channel_id, client_b.current_user_id(cx_b), false)
3389 .await
3390 .unwrap();
3391 db.create_channel_message(
3392 channel_id,
3393 client_b.current_user_id(cx_b),
3394 "hello A, it's B.",
3395 OffsetDateTime::now_utc(),
3396 1,
3397 )
3398 .await
3399 .unwrap();
3400
3401 let channels_a =
3402 cx_a.add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
3403 channels_a
3404 .condition(cx_a, |list, _| list.available_channels().is_some())
3405 .await;
3406 channels_a.read_with(cx_a, |list, _| {
3407 assert_eq!(
3408 list.available_channels().unwrap(),
3409 &[ChannelDetails {
3410 id: channel_id.to_proto(),
3411 name: "test-channel".to_string()
3412 }]
3413 )
3414 });
3415 let channel_a = channels_a.update(cx_a, |this, cx| {
3416 this.get_channel(channel_id.to_proto(), cx).unwrap()
3417 });
3418 channel_a.read_with(cx_a, |channel, _| assert!(channel.messages().is_empty()));
3419 channel_a
3420 .condition(cx_a, |channel, _| {
3421 channel_messages(channel)
3422 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
3423 })
3424 .await;
3425
3426 let channels_b =
3427 cx_b.add_model(|cx| ChannelList::new(client_b.user_store.clone(), client_b.clone(), cx));
3428 channels_b
3429 .condition(cx_b, |list, _| list.available_channels().is_some())
3430 .await;
3431 channels_b.read_with(cx_b, |list, _| {
3432 assert_eq!(
3433 list.available_channels().unwrap(),
3434 &[ChannelDetails {
3435 id: channel_id.to_proto(),
3436 name: "test-channel".to_string()
3437 }]
3438 )
3439 });
3440
3441 let channel_b = channels_b.update(cx_b, |this, cx| {
3442 this.get_channel(channel_id.to_proto(), cx).unwrap()
3443 });
3444 channel_b.read_with(cx_b, |channel, _| assert!(channel.messages().is_empty()));
3445 channel_b
3446 .condition(cx_b, |channel, _| {
3447 channel_messages(channel)
3448 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
3449 })
3450 .await;
3451
3452 channel_a
3453 .update(cx_a, |channel, cx| {
3454 channel
3455 .send_message("oh, hi B.".to_string(), cx)
3456 .unwrap()
3457 .detach();
3458 let task = channel.send_message("sup".to_string(), cx).unwrap();
3459 assert_eq!(
3460 channel_messages(channel),
3461 &[
3462 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3463 ("user_a".to_string(), "oh, hi B.".to_string(), true),
3464 ("user_a".to_string(), "sup".to_string(), true)
3465 ]
3466 );
3467 task
3468 })
3469 .await
3470 .unwrap();
3471
3472 channel_b
3473 .condition(cx_b, |channel, _| {
3474 channel_messages(channel)
3475 == [
3476 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3477 ("user_a".to_string(), "oh, hi B.".to_string(), false),
3478 ("user_a".to_string(), "sup".to_string(), false),
3479 ]
3480 })
3481 .await;
3482
3483 assert_eq!(
3484 server
3485 .store()
3486 .await
3487 .channel(channel_id)
3488 .unwrap()
3489 .connection_ids
3490 .len(),
3491 2
3492 );
3493 cx_b.update(|_| drop(channel_b));
3494 server
3495 .condition(|state| state.channel(channel_id).unwrap().connection_ids.len() == 1)
3496 .await;
3497
3498 cx_a.update(|_| drop(channel_a));
3499 server
3500 .condition(|state| state.channel(channel_id).is_none())
3501 .await;
3502}
3503
3504#[gpui::test(iterations = 10)]
3505async fn test_chat_message_validation(cx_a: &mut TestAppContext) {
3506 cx_a.foreground().forbid_parking();
3507 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
3508 let client_a = server.create_client(cx_a, "user_a").await;
3509
3510 let db = &server.app_state.db;
3511 let org_id = db.create_org("Test Org", "test-org").await.unwrap();
3512 let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
3513 db.add_org_member(org_id, client_a.current_user_id(cx_a), false)
3514 .await
3515 .unwrap();
3516 db.add_channel_member(channel_id, client_a.current_user_id(cx_a), false)
3517 .await
3518 .unwrap();
3519
3520 let channels_a =
3521 cx_a.add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
3522 channels_a
3523 .condition(cx_a, |list, _| list.available_channels().is_some())
3524 .await;
3525 let channel_a = channels_a.update(cx_a, |this, cx| {
3526 this.get_channel(channel_id.to_proto(), cx).unwrap()
3527 });
3528
3529 // Messages aren't allowed to be too long.
3530 channel_a
3531 .update(cx_a, |channel, cx| {
3532 let long_body = "this is long.\n".repeat(1024);
3533 channel.send_message(long_body, cx).unwrap()
3534 })
3535 .await
3536 .unwrap_err();
3537
3538 // Messages aren't allowed to be blank.
3539 channel_a.update(cx_a, |channel, cx| {
3540 channel.send_message(String::new(), cx).unwrap_err()
3541 });
3542
3543 // Leading and trailing whitespace are trimmed.
3544 channel_a
3545 .update(cx_a, |channel, cx| {
3546 channel
3547 .send_message("\n surrounded by whitespace \n".to_string(), cx)
3548 .unwrap()
3549 })
3550 .await
3551 .unwrap();
3552 assert_eq!(
3553 db.get_channel_messages(channel_id, 10, None)
3554 .await
3555 .unwrap()
3556 .iter()
3557 .map(|m| &m.body)
3558 .collect::<Vec<_>>(),
3559 &["surrounded by whitespace"]
3560 );
3561}
3562
3563#[gpui::test(iterations = 10)]
3564async fn test_chat_reconnection(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
3565 cx_a.foreground().forbid_parking();
3566 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
3567 let client_a = server.create_client(cx_a, "user_a").await;
3568 let client_b = server.create_client(cx_b, "user_b").await;
3569
3570 let mut status_b = client_b.status();
3571
3572 // Create an org that includes these 2 users.
3573 let db = &server.app_state.db;
3574 let org_id = db.create_org("Test Org", "test-org").await.unwrap();
3575 db.add_org_member(org_id, client_a.current_user_id(cx_a), false)
3576 .await
3577 .unwrap();
3578 db.add_org_member(org_id, client_b.current_user_id(cx_b), false)
3579 .await
3580 .unwrap();
3581
3582 // Create a channel that includes all the users.
3583 let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
3584 db.add_channel_member(channel_id, client_a.current_user_id(cx_a), false)
3585 .await
3586 .unwrap();
3587 db.add_channel_member(channel_id, client_b.current_user_id(cx_b), false)
3588 .await
3589 .unwrap();
3590 db.create_channel_message(
3591 channel_id,
3592 client_b.current_user_id(cx_b),
3593 "hello A, it's B.",
3594 OffsetDateTime::now_utc(),
3595 2,
3596 )
3597 .await
3598 .unwrap();
3599
3600 let channels_a =
3601 cx_a.add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
3602 channels_a
3603 .condition(cx_a, |list, _| list.available_channels().is_some())
3604 .await;
3605
3606 channels_a.read_with(cx_a, |list, _| {
3607 assert_eq!(
3608 list.available_channels().unwrap(),
3609 &[ChannelDetails {
3610 id: channel_id.to_proto(),
3611 name: "test-channel".to_string()
3612 }]
3613 )
3614 });
3615 let channel_a = channels_a.update(cx_a, |this, cx| {
3616 this.get_channel(channel_id.to_proto(), cx).unwrap()
3617 });
3618 channel_a.read_with(cx_a, |channel, _| assert!(channel.messages().is_empty()));
3619 channel_a
3620 .condition(cx_a, |channel, _| {
3621 channel_messages(channel)
3622 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
3623 })
3624 .await;
3625
3626 let channels_b =
3627 cx_b.add_model(|cx| ChannelList::new(client_b.user_store.clone(), client_b.clone(), cx));
3628 channels_b
3629 .condition(cx_b, |list, _| list.available_channels().is_some())
3630 .await;
3631 channels_b.read_with(cx_b, |list, _| {
3632 assert_eq!(
3633 list.available_channels().unwrap(),
3634 &[ChannelDetails {
3635 id: channel_id.to_proto(),
3636 name: "test-channel".to_string()
3637 }]
3638 )
3639 });
3640
3641 let channel_b = channels_b.update(cx_b, |this, cx| {
3642 this.get_channel(channel_id.to_proto(), cx).unwrap()
3643 });
3644 channel_b.read_with(cx_b, |channel, _| assert!(channel.messages().is_empty()));
3645 channel_b
3646 .condition(cx_b, |channel, _| {
3647 channel_messages(channel)
3648 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
3649 })
3650 .await;
3651
3652 // Disconnect client B, ensuring we can still access its cached channel data.
3653 server.forbid_connections();
3654 server.disconnect_client(client_b.current_user_id(cx_b));
3655 cx_b.foreground().advance_clock(rpc::RECEIVE_TIMEOUT);
3656 while !matches!(
3657 status_b.next().await,
3658 Some(client::Status::ReconnectionError { .. })
3659 ) {}
3660
3661 channels_b.read_with(cx_b, |channels, _| {
3662 assert_eq!(
3663 channels.available_channels().unwrap(),
3664 [ChannelDetails {
3665 id: channel_id.to_proto(),
3666 name: "test-channel".to_string()
3667 }]
3668 )
3669 });
3670 channel_b.read_with(cx_b, |channel, _| {
3671 assert_eq!(
3672 channel_messages(channel),
3673 [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
3674 )
3675 });
3676
3677 // Send a message from client B while it is disconnected.
3678 channel_b
3679 .update(cx_b, |channel, cx| {
3680 let task = channel
3681 .send_message("can you see this?".to_string(), cx)
3682 .unwrap();
3683 assert_eq!(
3684 channel_messages(channel),
3685 &[
3686 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3687 ("user_b".to_string(), "can you see this?".to_string(), true)
3688 ]
3689 );
3690 task
3691 })
3692 .await
3693 .unwrap_err();
3694
3695 // Send a message from client A while B is disconnected.
3696 channel_a
3697 .update(cx_a, |channel, cx| {
3698 channel
3699 .send_message("oh, hi B.".to_string(), cx)
3700 .unwrap()
3701 .detach();
3702 let task = channel.send_message("sup".to_string(), cx).unwrap();
3703 assert_eq!(
3704 channel_messages(channel),
3705 &[
3706 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3707 ("user_a".to_string(), "oh, hi B.".to_string(), true),
3708 ("user_a".to_string(), "sup".to_string(), true)
3709 ]
3710 );
3711 task
3712 })
3713 .await
3714 .unwrap();
3715
3716 // Give client B a chance to reconnect.
3717 server.allow_connections();
3718 cx_b.foreground().advance_clock(Duration::from_secs(10));
3719
3720 // Verify that B sees the new messages upon reconnection, as well as the message client B
3721 // sent while offline.
3722 channel_b
3723 .condition(cx_b, |channel, _| {
3724 channel_messages(channel)
3725 == [
3726 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3727 ("user_a".to_string(), "oh, hi B.".to_string(), false),
3728 ("user_a".to_string(), "sup".to_string(), false),
3729 ("user_b".to_string(), "can you see this?".to_string(), false),
3730 ]
3731 })
3732 .await;
3733
3734 // Ensure client A and B can communicate normally after reconnection.
3735 channel_a
3736 .update(cx_a, |channel, cx| {
3737 channel.send_message("you online?".to_string(), cx).unwrap()
3738 })
3739 .await
3740 .unwrap();
3741 channel_b
3742 .condition(cx_b, |channel, _| {
3743 channel_messages(channel)
3744 == [
3745 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3746 ("user_a".to_string(), "oh, hi B.".to_string(), false),
3747 ("user_a".to_string(), "sup".to_string(), false),
3748 ("user_b".to_string(), "can you see this?".to_string(), false),
3749 ("user_a".to_string(), "you online?".to_string(), false),
3750 ]
3751 })
3752 .await;
3753
3754 channel_b
3755 .update(cx_b, |channel, cx| {
3756 channel.send_message("yep".to_string(), cx).unwrap()
3757 })
3758 .await
3759 .unwrap();
3760 channel_a
3761 .condition(cx_a, |channel, _| {
3762 channel_messages(channel)
3763 == [
3764 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
3765 ("user_a".to_string(), "oh, hi B.".to_string(), false),
3766 ("user_a".to_string(), "sup".to_string(), false),
3767 ("user_b".to_string(), "can you see this?".to_string(), false),
3768 ("user_a".to_string(), "you online?".to_string(), false),
3769 ("user_b".to_string(), "yep".to_string(), false),
3770 ]
3771 })
3772 .await;
3773}
3774
3775#[gpui::test(iterations = 10)]
3776async fn test_contacts(
3777 deterministic: Arc<Deterministic>,
3778 cx_a: &mut TestAppContext,
3779 cx_b: &mut TestAppContext,
3780 cx_c: &mut TestAppContext,
3781) {
3782 cx_a.foreground().forbid_parking();
3783 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
3784 let client_a = server.create_client(cx_a, "user_a").await;
3785 let client_b = server.create_client(cx_b, "user_b").await;
3786 let client_c = server.create_client(cx_c, "user_c").await;
3787 server
3788 .make_contacts(&mut [(&client_a, cx_a), (&client_b, cx_b), (&client_c, cx_c)])
3789 .await;
3790
3791 deterministic.run_until_parked();
3792 assert_eq!(
3793 contacts(&client_a, cx_a),
3794 [("user_b".to_string(), true), ("user_c".to_string(), true)]
3795 );
3796 assert_eq!(
3797 contacts(&client_b, cx_b),
3798 [("user_a".to_string(), true), ("user_c".to_string(), true)]
3799 );
3800 assert_eq!(
3801 contacts(&client_c, cx_c),
3802 [("user_a".to_string(), true), ("user_b".to_string(), true)]
3803 );
3804
3805 server.disconnect_client(client_c.current_user_id(cx_c));
3806 server.forbid_connections();
3807 deterministic.advance_clock(rpc::RECEIVE_TIMEOUT);
3808 assert_eq!(
3809 contacts(&client_a, cx_a),
3810 [("user_b".to_string(), true), ("user_c".to_string(), false)]
3811 );
3812 assert_eq!(
3813 contacts(&client_b, cx_b),
3814 [("user_a".to_string(), true), ("user_c".to_string(), false)]
3815 );
3816 assert_eq!(contacts(&client_c, cx_c), []);
3817
3818 server.allow_connections();
3819 client_c
3820 .authenticate_and_connect(false, &cx_c.to_async())
3821 .await
3822 .unwrap();
3823
3824 deterministic.run_until_parked();
3825 assert_eq!(
3826 contacts(&client_a, cx_a),
3827 [("user_b".to_string(), true), ("user_c".to_string(), true)]
3828 );
3829 assert_eq!(
3830 contacts(&client_b, cx_b),
3831 [("user_a".to_string(), true), ("user_c".to_string(), true)]
3832 );
3833 assert_eq!(
3834 contacts(&client_c, cx_c),
3835 [("user_a".to_string(), true), ("user_b".to_string(), true)]
3836 );
3837
3838 #[allow(clippy::type_complexity)]
3839 fn contacts(client: &TestClient, cx: &TestAppContext) -> Vec<(String, bool)> {
3840 client.user_store.read_with(cx, |store, _| {
3841 store
3842 .contacts()
3843 .iter()
3844 .map(|contact| (contact.user.github_login.clone(), contact.online))
3845 .collect()
3846 })
3847 }
3848}
3849
3850#[gpui::test(iterations = 10)]
3851async fn test_contact_requests(
3852 executor: Arc<Deterministic>,
3853 cx_a: &mut TestAppContext,
3854 cx_a2: &mut TestAppContext,
3855 cx_b: &mut TestAppContext,
3856 cx_b2: &mut TestAppContext,
3857 cx_c: &mut TestAppContext,
3858 cx_c2: &mut TestAppContext,
3859) {
3860 cx_a.foreground().forbid_parking();
3861
3862 // Connect to a server as 3 clients.
3863 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
3864 let client_a = server.create_client(cx_a, "user_a").await;
3865 let client_a2 = server.create_client(cx_a2, "user_a").await;
3866 let client_b = server.create_client(cx_b, "user_b").await;
3867 let client_b2 = server.create_client(cx_b2, "user_b").await;
3868 let client_c = server.create_client(cx_c, "user_c").await;
3869 let client_c2 = server.create_client(cx_c2, "user_c").await;
3870
3871 assert_eq!(client_a.user_id().unwrap(), client_a2.user_id().unwrap());
3872 assert_eq!(client_b.user_id().unwrap(), client_b2.user_id().unwrap());
3873 assert_eq!(client_c.user_id().unwrap(), client_c2.user_id().unwrap());
3874
3875 // User A and User C request that user B become their contact.
3876 client_a
3877 .user_store
3878 .update(cx_a, |store, cx| {
3879 store.request_contact(client_b.user_id().unwrap(), cx)
3880 })
3881 .await
3882 .unwrap();
3883 client_c
3884 .user_store
3885 .update(cx_c, |store, cx| {
3886 store.request_contact(client_b.user_id().unwrap(), cx)
3887 })
3888 .await
3889 .unwrap();
3890 executor.run_until_parked();
3891
3892 // All users see the pending request appear in all their clients.
3893 assert_eq!(
3894 client_a.summarize_contacts(cx_a).outgoing_requests,
3895 &["user_b"]
3896 );
3897 assert_eq!(
3898 client_a2.summarize_contacts(cx_a2).outgoing_requests,
3899 &["user_b"]
3900 );
3901 assert_eq!(
3902 client_b.summarize_contacts(cx_b).incoming_requests,
3903 &["user_a", "user_c"]
3904 );
3905 assert_eq!(
3906 client_b2.summarize_contacts(cx_b2).incoming_requests,
3907 &["user_a", "user_c"]
3908 );
3909 assert_eq!(
3910 client_c.summarize_contacts(cx_c).outgoing_requests,
3911 &["user_b"]
3912 );
3913 assert_eq!(
3914 client_c2.summarize_contacts(cx_c2).outgoing_requests,
3915 &["user_b"]
3916 );
3917
3918 // Contact requests are present upon connecting (tested here via disconnect/reconnect)
3919 disconnect_and_reconnect(&client_a, cx_a).await;
3920 disconnect_and_reconnect(&client_b, cx_b).await;
3921 disconnect_and_reconnect(&client_c, cx_c).await;
3922 executor.run_until_parked();
3923 assert_eq!(
3924 client_a.summarize_contacts(cx_a).outgoing_requests,
3925 &["user_b"]
3926 );
3927 assert_eq!(
3928 client_b.summarize_contacts(cx_b).incoming_requests,
3929 &["user_a", "user_c"]
3930 );
3931 assert_eq!(
3932 client_c.summarize_contacts(cx_c).outgoing_requests,
3933 &["user_b"]
3934 );
3935
3936 // User B accepts the request from user A.
3937 client_b
3938 .user_store
3939 .update(cx_b, |store, cx| {
3940 store.respond_to_contact_request(client_a.user_id().unwrap(), true, cx)
3941 })
3942 .await
3943 .unwrap();
3944
3945 executor.run_until_parked();
3946
3947 // User B sees user A as their contact now in all client, and the incoming request from them is removed.
3948 let contacts_b = client_b.summarize_contacts(cx_b);
3949 assert_eq!(contacts_b.current, &["user_a"]);
3950 assert_eq!(contacts_b.incoming_requests, &["user_c"]);
3951 let contacts_b2 = client_b2.summarize_contacts(cx_b2);
3952 assert_eq!(contacts_b2.current, &["user_a"]);
3953 assert_eq!(contacts_b2.incoming_requests, &["user_c"]);
3954
3955 // User A sees user B as their contact now in all clients, and the outgoing request to them is removed.
3956 let contacts_a = client_a.summarize_contacts(cx_a);
3957 assert_eq!(contacts_a.current, &["user_b"]);
3958 assert!(contacts_a.outgoing_requests.is_empty());
3959 let contacts_a2 = client_a2.summarize_contacts(cx_a2);
3960 assert_eq!(contacts_a2.current, &["user_b"]);
3961 assert!(contacts_a2.outgoing_requests.is_empty());
3962
3963 // Contacts are present upon connecting (tested here via disconnect/reconnect)
3964 disconnect_and_reconnect(&client_a, cx_a).await;
3965 disconnect_and_reconnect(&client_b, cx_b).await;
3966 disconnect_and_reconnect(&client_c, cx_c).await;
3967 executor.run_until_parked();
3968 assert_eq!(client_a.summarize_contacts(cx_a).current, &["user_b"]);
3969 assert_eq!(client_b.summarize_contacts(cx_b).current, &["user_a"]);
3970 assert_eq!(
3971 client_b.summarize_contacts(cx_b).incoming_requests,
3972 &["user_c"]
3973 );
3974 assert!(client_c.summarize_contacts(cx_c).current.is_empty());
3975 assert_eq!(
3976 client_c.summarize_contacts(cx_c).outgoing_requests,
3977 &["user_b"]
3978 );
3979
3980 // User B rejects the request from user C.
3981 client_b
3982 .user_store
3983 .update(cx_b, |store, cx| {
3984 store.respond_to_contact_request(client_c.user_id().unwrap(), false, cx)
3985 })
3986 .await
3987 .unwrap();
3988
3989 executor.run_until_parked();
3990
3991 // User B doesn't see user C as their contact, and the incoming request from them is removed.
3992 let contacts_b = client_b.summarize_contacts(cx_b);
3993 assert_eq!(contacts_b.current, &["user_a"]);
3994 assert!(contacts_b.incoming_requests.is_empty());
3995 let contacts_b2 = client_b2.summarize_contacts(cx_b2);
3996 assert_eq!(contacts_b2.current, &["user_a"]);
3997 assert!(contacts_b2.incoming_requests.is_empty());
3998
3999 // User C doesn't see user B as their contact, and the outgoing request to them is removed.
4000 let contacts_c = client_c.summarize_contacts(cx_c);
4001 assert!(contacts_c.current.is_empty());
4002 assert!(contacts_c.outgoing_requests.is_empty());
4003 let contacts_c2 = client_c2.summarize_contacts(cx_c2);
4004 assert!(contacts_c2.current.is_empty());
4005 assert!(contacts_c2.outgoing_requests.is_empty());
4006
4007 // Incoming/outgoing requests are not present upon connecting (tested here via disconnect/reconnect)
4008 disconnect_and_reconnect(&client_a, cx_a).await;
4009 disconnect_and_reconnect(&client_b, cx_b).await;
4010 disconnect_and_reconnect(&client_c, cx_c).await;
4011 executor.run_until_parked();
4012 assert_eq!(client_a.summarize_contacts(cx_a).current, &["user_b"]);
4013 assert_eq!(client_b.summarize_contacts(cx_b).current, &["user_a"]);
4014 assert!(client_b
4015 .summarize_contacts(cx_b)
4016 .incoming_requests
4017 .is_empty());
4018 assert!(client_c.summarize_contacts(cx_c).current.is_empty());
4019 assert!(client_c
4020 .summarize_contacts(cx_c)
4021 .outgoing_requests
4022 .is_empty());
4023
4024 async fn disconnect_and_reconnect(client: &TestClient, cx: &mut TestAppContext) {
4025 client.disconnect(&cx.to_async()).unwrap();
4026 client.clear_contacts(cx).await;
4027 client
4028 .authenticate_and_connect(false, &cx.to_async())
4029 .await
4030 .unwrap();
4031 }
4032}
4033
4034#[gpui::test(iterations = 10)]
4035async fn test_following(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
4036 cx_a.foreground().forbid_parking();
4037 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
4038 let client_a = server.create_client(cx_a, "user_a").await;
4039 let client_b = server.create_client(cx_b, "user_b").await;
4040 let (room_id, _rooms) = server
4041 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
4042 .await;
4043 cx_a.update(editor::init);
4044 cx_b.update(editor::init);
4045
4046 client_a
4047 .fs
4048 .insert_tree(
4049 "/a",
4050 json!({
4051 "1.txt": "one",
4052 "2.txt": "two",
4053 "3.txt": "three",
4054 }),
4055 )
4056 .await;
4057 let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
4058 let project_id = project_a
4059 .update(cx_a, |project, cx| project.share(room_id, cx))
4060 .await
4061 .unwrap();
4062 let project_b = client_b.build_remote_project(project_id, cx_b).await;
4063
4064 // Client A opens some editors.
4065 let workspace_a = client_a.build_workspace(&project_a, cx_a);
4066 let pane_a = workspace_a.read_with(cx_a, |workspace, _| workspace.active_pane().clone());
4067 let editor_a1 = workspace_a
4068 .update(cx_a, |workspace, cx| {
4069 workspace.open_path((worktree_id, "1.txt"), true, cx)
4070 })
4071 .await
4072 .unwrap()
4073 .downcast::<Editor>()
4074 .unwrap();
4075 let editor_a2 = workspace_a
4076 .update(cx_a, |workspace, cx| {
4077 workspace.open_path((worktree_id, "2.txt"), true, cx)
4078 })
4079 .await
4080 .unwrap()
4081 .downcast::<Editor>()
4082 .unwrap();
4083
4084 // Client B opens an editor.
4085 let workspace_b = client_b.build_workspace(&project_b, cx_b);
4086 let editor_b1 = workspace_b
4087 .update(cx_b, |workspace, cx| {
4088 workspace.open_path((worktree_id, "1.txt"), true, cx)
4089 })
4090 .await
4091 .unwrap()
4092 .downcast::<Editor>()
4093 .unwrap();
4094
4095 let client_a_id = project_b.read_with(cx_b, |project, _| {
4096 project.collaborators().values().next().unwrap().peer_id
4097 });
4098 let client_b_id = project_a.read_with(cx_a, |project, _| {
4099 project.collaborators().values().next().unwrap().peer_id
4100 });
4101
4102 // When client B starts following client A, all visible view states are replicated to client B.
4103 editor_a1.update(cx_a, |editor, cx| {
4104 editor.change_selections(None, cx, |s| s.select_ranges([0..1]))
4105 });
4106 editor_a2.update(cx_a, |editor, cx| {
4107 editor.change_selections(None, cx, |s| s.select_ranges([2..3]))
4108 });
4109 workspace_b
4110 .update(cx_b, |workspace, cx| {
4111 workspace
4112 .toggle_follow(&ToggleFollow(client_a_id), cx)
4113 .unwrap()
4114 })
4115 .await
4116 .unwrap();
4117
4118 let editor_b2 = workspace_b.read_with(cx_b, |workspace, cx| {
4119 workspace
4120 .active_item(cx)
4121 .unwrap()
4122 .downcast::<Editor>()
4123 .unwrap()
4124 });
4125 assert!(cx_b.read(|cx| editor_b2.is_focused(cx)));
4126 assert_eq!(
4127 editor_b2.read_with(cx_b, |editor, cx| editor.project_path(cx)),
4128 Some((worktree_id, "2.txt").into())
4129 );
4130 assert_eq!(
4131 editor_b2.read_with(cx_b, |editor, cx| editor.selections.ranges(cx)),
4132 vec![2..3]
4133 );
4134 assert_eq!(
4135 editor_b1.read_with(cx_b, |editor, cx| editor.selections.ranges(cx)),
4136 vec![0..1]
4137 );
4138
4139 // When client A activates a different editor, client B does so as well.
4140 workspace_a.update(cx_a, |workspace, cx| {
4141 workspace.activate_item(&editor_a1, cx)
4142 });
4143 workspace_b
4144 .condition(cx_b, |workspace, cx| {
4145 workspace.active_item(cx).unwrap().id() == editor_b1.id()
4146 })
4147 .await;
4148
4149 // When client A navigates back and forth, client B does so as well.
4150 workspace_a
4151 .update(cx_a, |workspace, cx| {
4152 workspace::Pane::go_back(workspace, None, cx)
4153 })
4154 .await;
4155 workspace_b
4156 .condition(cx_b, |workspace, cx| {
4157 workspace.active_item(cx).unwrap().id() == editor_b2.id()
4158 })
4159 .await;
4160
4161 workspace_a
4162 .update(cx_a, |workspace, cx| {
4163 workspace::Pane::go_forward(workspace, None, cx)
4164 })
4165 .await;
4166 workspace_b
4167 .condition(cx_b, |workspace, cx| {
4168 workspace.active_item(cx).unwrap().id() == editor_b1.id()
4169 })
4170 .await;
4171
4172 // Changes to client A's editor are reflected on client B.
4173 editor_a1.update(cx_a, |editor, cx| {
4174 editor.change_selections(None, cx, |s| s.select_ranges([1..1, 2..2]));
4175 });
4176 editor_b1
4177 .condition(cx_b, |editor, cx| {
4178 editor.selections.ranges(cx) == vec![1..1, 2..2]
4179 })
4180 .await;
4181
4182 editor_a1.update(cx_a, |editor, cx| editor.set_text("TWO", cx));
4183 editor_b1
4184 .condition(cx_b, |editor, cx| editor.text(cx) == "TWO")
4185 .await;
4186
4187 editor_a1.update(cx_a, |editor, cx| {
4188 editor.change_selections(None, cx, |s| s.select_ranges([3..3]));
4189 editor.set_scroll_position(vec2f(0., 100.), cx);
4190 });
4191 editor_b1
4192 .condition(cx_b, |editor, cx| {
4193 editor.selections.ranges(cx) == vec![3..3]
4194 })
4195 .await;
4196
4197 // After unfollowing, client B stops receiving updates from client A.
4198 workspace_b.update(cx_b, |workspace, cx| {
4199 workspace.unfollow(&workspace.active_pane().clone(), cx)
4200 });
4201 workspace_a.update(cx_a, |workspace, cx| {
4202 workspace.activate_item(&editor_a2, cx)
4203 });
4204 cx_a.foreground().run_until_parked();
4205 assert_eq!(
4206 workspace_b.read_with(cx_b, |workspace, cx| workspace
4207 .active_item(cx)
4208 .unwrap()
4209 .id()),
4210 editor_b1.id()
4211 );
4212
4213 // Client A starts following client B.
4214 workspace_a
4215 .update(cx_a, |workspace, cx| {
4216 workspace
4217 .toggle_follow(&ToggleFollow(client_b_id), cx)
4218 .unwrap()
4219 })
4220 .await
4221 .unwrap();
4222 assert_eq!(
4223 workspace_a.read_with(cx_a, |workspace, _| workspace.leader_for_pane(&pane_a)),
4224 Some(client_b_id)
4225 );
4226 assert_eq!(
4227 workspace_a.read_with(cx_a, |workspace, cx| workspace
4228 .active_item(cx)
4229 .unwrap()
4230 .id()),
4231 editor_a1.id()
4232 );
4233
4234 // Following interrupts when client B disconnects.
4235 client_b.disconnect(&cx_b.to_async()).unwrap();
4236 cx_a.foreground().run_until_parked();
4237 assert_eq!(
4238 workspace_a.read_with(cx_a, |workspace, _| workspace.leader_for_pane(&pane_a)),
4239 None
4240 );
4241}
4242
4243#[gpui::test(iterations = 10)]
4244async fn test_peers_following_each_other(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
4245 cx_a.foreground().forbid_parking();
4246 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
4247 let client_a = server.create_client(cx_a, "user_a").await;
4248 let client_b = server.create_client(cx_b, "user_b").await;
4249 let (room_id, _rooms) = server
4250 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
4251 .await;
4252 cx_a.update(editor::init);
4253 cx_b.update(editor::init);
4254
4255 // Client A shares a project.
4256 client_a
4257 .fs
4258 .insert_tree(
4259 "/a",
4260 json!({
4261 "1.txt": "one",
4262 "2.txt": "two",
4263 "3.txt": "three",
4264 "4.txt": "four",
4265 }),
4266 )
4267 .await;
4268 let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
4269 let project_id = project_a
4270 .update(cx_a, |project, cx| project.share(room_id, cx))
4271 .await
4272 .unwrap();
4273
4274 // Client B joins the project.
4275 let project_b = client_b.build_remote_project(project_id, cx_b).await;
4276
4277 // Client A opens some editors.
4278 let workspace_a = client_a.build_workspace(&project_a, cx_a);
4279 let pane_a1 = workspace_a.read_with(cx_a, |workspace, _| workspace.active_pane().clone());
4280 let _editor_a1 = workspace_a
4281 .update(cx_a, |workspace, cx| {
4282 workspace.open_path((worktree_id, "1.txt"), true, cx)
4283 })
4284 .await
4285 .unwrap()
4286 .downcast::<Editor>()
4287 .unwrap();
4288
4289 // Client B opens an editor.
4290 let workspace_b = client_b.build_workspace(&project_b, cx_b);
4291 let pane_b1 = workspace_b.read_with(cx_b, |workspace, _| workspace.active_pane().clone());
4292 let _editor_b1 = workspace_b
4293 .update(cx_b, |workspace, cx| {
4294 workspace.open_path((worktree_id, "2.txt"), true, cx)
4295 })
4296 .await
4297 .unwrap()
4298 .downcast::<Editor>()
4299 .unwrap();
4300
4301 // Clients A and B follow each other in split panes
4302 workspace_a.update(cx_a, |workspace, cx| {
4303 workspace.split_pane(workspace.active_pane().clone(), SplitDirection::Right, cx);
4304 let pane_a1 = pane_a1.clone();
4305 cx.defer(move |workspace, _| {
4306 assert_ne!(*workspace.active_pane(), pane_a1);
4307 });
4308 });
4309 workspace_a
4310 .update(cx_a, |workspace, cx| {
4311 let leader_id = *project_a.read(cx).collaborators().keys().next().unwrap();
4312 workspace
4313 .toggle_follow(&workspace::ToggleFollow(leader_id), cx)
4314 .unwrap()
4315 })
4316 .await
4317 .unwrap();
4318 workspace_b.update(cx_b, |workspace, cx| {
4319 workspace.split_pane(workspace.active_pane().clone(), SplitDirection::Right, cx);
4320 let pane_b1 = pane_b1.clone();
4321 cx.defer(move |workspace, _| {
4322 assert_ne!(*workspace.active_pane(), pane_b1);
4323 });
4324 });
4325 workspace_b
4326 .update(cx_b, |workspace, cx| {
4327 let leader_id = *project_b.read(cx).collaborators().keys().next().unwrap();
4328 workspace
4329 .toggle_follow(&workspace::ToggleFollow(leader_id), cx)
4330 .unwrap()
4331 })
4332 .await
4333 .unwrap();
4334
4335 workspace_a.update(cx_a, |workspace, cx| {
4336 workspace.activate_next_pane(cx);
4337 });
4338 // Wait for focus effects to be fully flushed
4339 workspace_a.update(cx_a, |workspace, _| {
4340 assert_eq!(*workspace.active_pane(), pane_a1);
4341 });
4342
4343 workspace_a
4344 .update(cx_a, |workspace, cx| {
4345 workspace.open_path((worktree_id, "3.txt"), true, cx)
4346 })
4347 .await
4348 .unwrap();
4349 workspace_b.update(cx_b, |workspace, cx| {
4350 workspace.activate_next_pane(cx);
4351 });
4352
4353 workspace_b
4354 .update(cx_b, |workspace, cx| {
4355 assert_eq!(*workspace.active_pane(), pane_b1);
4356 workspace.open_path((worktree_id, "4.txt"), true, cx)
4357 })
4358 .await
4359 .unwrap();
4360 cx_a.foreground().run_until_parked();
4361
4362 // Ensure leader updates don't change the active pane of followers
4363 workspace_a.read_with(cx_a, |workspace, _| {
4364 assert_eq!(*workspace.active_pane(), pane_a1);
4365 });
4366 workspace_b.read_with(cx_b, |workspace, _| {
4367 assert_eq!(*workspace.active_pane(), pane_b1);
4368 });
4369
4370 // Ensure peers following each other doesn't cause an infinite loop.
4371 assert_eq!(
4372 workspace_a.read_with(cx_a, |workspace, cx| workspace
4373 .active_item(cx)
4374 .unwrap()
4375 .project_path(cx)),
4376 Some((worktree_id, "3.txt").into())
4377 );
4378 workspace_a.update(cx_a, |workspace, cx| {
4379 assert_eq!(
4380 workspace.active_item(cx).unwrap().project_path(cx),
4381 Some((worktree_id, "3.txt").into())
4382 );
4383 workspace.activate_next_pane(cx);
4384 });
4385
4386 workspace_a.update(cx_a, |workspace, cx| {
4387 assert_eq!(
4388 workspace.active_item(cx).unwrap().project_path(cx),
4389 Some((worktree_id, "4.txt").into())
4390 );
4391 });
4392
4393 workspace_b.update(cx_b, |workspace, cx| {
4394 assert_eq!(
4395 workspace.active_item(cx).unwrap().project_path(cx),
4396 Some((worktree_id, "4.txt").into())
4397 );
4398 workspace.activate_next_pane(cx);
4399 });
4400
4401 workspace_b.update(cx_b, |workspace, cx| {
4402 assert_eq!(
4403 workspace.active_item(cx).unwrap().project_path(cx),
4404 Some((worktree_id, "3.txt").into())
4405 );
4406 });
4407}
4408
4409#[gpui::test(iterations = 10)]
4410async fn test_auto_unfollowing(cx_a: &mut TestAppContext, cx_b: &mut TestAppContext) {
4411 cx_a.foreground().forbid_parking();
4412
4413 // 2 clients connect to a server.
4414 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
4415 let client_a = server.create_client(cx_a, "user_a").await;
4416 let client_b = server.create_client(cx_b, "user_b").await;
4417 let (room_id, _rooms) = server
4418 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
4419 .await;
4420 cx_a.update(editor::init);
4421 cx_b.update(editor::init);
4422
4423 // Client A shares a project.
4424 client_a
4425 .fs
4426 .insert_tree(
4427 "/a",
4428 json!({
4429 "1.txt": "one",
4430 "2.txt": "two",
4431 "3.txt": "three",
4432 }),
4433 )
4434 .await;
4435 let (project_a, worktree_id) = client_a.build_local_project("/a", cx_a).await;
4436 let project_id = project_a
4437 .update(cx_a, |project, cx| project.share(room_id, cx))
4438 .await
4439 .unwrap();
4440 let project_b = client_b.build_remote_project(project_id, cx_b).await;
4441
4442 // Client A opens some editors.
4443 let workspace_a = client_a.build_workspace(&project_a, cx_a);
4444 let _editor_a1 = workspace_a
4445 .update(cx_a, |workspace, cx| {
4446 workspace.open_path((worktree_id, "1.txt"), true, cx)
4447 })
4448 .await
4449 .unwrap()
4450 .downcast::<Editor>()
4451 .unwrap();
4452
4453 // Client B starts following client A.
4454 let workspace_b = client_b.build_workspace(&project_b, cx_b);
4455 let pane_b = workspace_b.read_with(cx_b, |workspace, _| workspace.active_pane().clone());
4456 let leader_id = project_b.read_with(cx_b, |project, _| {
4457 project.collaborators().values().next().unwrap().peer_id
4458 });
4459 workspace_b
4460 .update(cx_b, |workspace, cx| {
4461 workspace
4462 .toggle_follow(&ToggleFollow(leader_id), cx)
4463 .unwrap()
4464 })
4465 .await
4466 .unwrap();
4467 assert_eq!(
4468 workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
4469 Some(leader_id)
4470 );
4471 let editor_b2 = workspace_b.read_with(cx_b, |workspace, cx| {
4472 workspace
4473 .active_item(cx)
4474 .unwrap()
4475 .downcast::<Editor>()
4476 .unwrap()
4477 });
4478
4479 // When client B moves, it automatically stops following client A.
4480 editor_b2.update(cx_b, |editor, cx| editor.move_right(&editor::MoveRight, cx));
4481 assert_eq!(
4482 workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
4483 None
4484 );
4485
4486 workspace_b
4487 .update(cx_b, |workspace, cx| {
4488 workspace
4489 .toggle_follow(&ToggleFollow(leader_id), cx)
4490 .unwrap()
4491 })
4492 .await
4493 .unwrap();
4494 assert_eq!(
4495 workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
4496 Some(leader_id)
4497 );
4498
4499 // When client B edits, it automatically stops following client A.
4500 editor_b2.update(cx_b, |editor, cx| editor.insert("X", cx));
4501 assert_eq!(
4502 workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
4503 None
4504 );
4505
4506 workspace_b
4507 .update(cx_b, |workspace, cx| {
4508 workspace
4509 .toggle_follow(&ToggleFollow(leader_id), cx)
4510 .unwrap()
4511 })
4512 .await
4513 .unwrap();
4514 assert_eq!(
4515 workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
4516 Some(leader_id)
4517 );
4518
4519 // When client B scrolls, it automatically stops following client A.
4520 editor_b2.update(cx_b, |editor, cx| {
4521 editor.set_scroll_position(vec2f(0., 3.), cx)
4522 });
4523 assert_eq!(
4524 workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
4525 None
4526 );
4527
4528 workspace_b
4529 .update(cx_b, |workspace, cx| {
4530 workspace
4531 .toggle_follow(&ToggleFollow(leader_id), cx)
4532 .unwrap()
4533 })
4534 .await
4535 .unwrap();
4536 assert_eq!(
4537 workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
4538 Some(leader_id)
4539 );
4540
4541 // When client B activates a different pane, it continues following client A in the original pane.
4542 workspace_b.update(cx_b, |workspace, cx| {
4543 workspace.split_pane(pane_b.clone(), SplitDirection::Right, cx)
4544 });
4545 assert_eq!(
4546 workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
4547 Some(leader_id)
4548 );
4549
4550 workspace_b.update(cx_b, |workspace, cx| workspace.activate_next_pane(cx));
4551 assert_eq!(
4552 workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
4553 Some(leader_id)
4554 );
4555
4556 // When client B activates a different item in the original pane, it automatically stops following client A.
4557 workspace_b
4558 .update(cx_b, |workspace, cx| {
4559 workspace.open_path((worktree_id, "2.txt"), true, cx)
4560 })
4561 .await
4562 .unwrap();
4563 assert_eq!(
4564 workspace_b.read_with(cx_b, |workspace, _| workspace.leader_for_pane(&pane_b)),
4565 None
4566 );
4567}
4568
4569#[gpui::test(iterations = 10)]
4570async fn test_peers_simultaneously_following_each_other(
4571 deterministic: Arc<Deterministic>,
4572 cx_a: &mut TestAppContext,
4573 cx_b: &mut TestAppContext,
4574) {
4575 deterministic.forbid_parking();
4576
4577 let mut server = TestServer::start(cx_a.foreground(), cx_a.background()).await;
4578 let client_a = server.create_client(cx_a, "user_a").await;
4579 let client_b = server.create_client(cx_b, "user_b").await;
4580 let (room_id, _rooms) = server
4581 .create_rooms(&mut [(&client_a, cx_a), (&client_b, cx_b)])
4582 .await;
4583 cx_a.update(editor::init);
4584 cx_b.update(editor::init);
4585
4586 client_a.fs.insert_tree("/a", json!({})).await;
4587 let (project_a, _) = client_a.build_local_project("/a", cx_a).await;
4588 let workspace_a = client_a.build_workspace(&project_a, cx_a);
4589 let project_id = project_a
4590 .update(cx_a, |project, cx| project.share(room_id, cx))
4591 .await
4592 .unwrap();
4593
4594 let project_b = client_b.build_remote_project(project_id, cx_b).await;
4595 let workspace_b = client_b.build_workspace(&project_b, cx_b);
4596
4597 deterministic.run_until_parked();
4598 let client_a_id = project_b.read_with(cx_b, |project, _| {
4599 project.collaborators().values().next().unwrap().peer_id
4600 });
4601 let client_b_id = project_a.read_with(cx_a, |project, _| {
4602 project.collaborators().values().next().unwrap().peer_id
4603 });
4604
4605 let a_follow_b = workspace_a.update(cx_a, |workspace, cx| {
4606 workspace
4607 .toggle_follow(&ToggleFollow(client_b_id), cx)
4608 .unwrap()
4609 });
4610 let b_follow_a = workspace_b.update(cx_b, |workspace, cx| {
4611 workspace
4612 .toggle_follow(&ToggleFollow(client_a_id), cx)
4613 .unwrap()
4614 });
4615
4616 futures::try_join!(a_follow_b, b_follow_a).unwrap();
4617 workspace_a.read_with(cx_a, |workspace, _| {
4618 assert_eq!(
4619 workspace.leader_for_pane(workspace.active_pane()),
4620 Some(client_b_id)
4621 );
4622 });
4623 workspace_b.read_with(cx_b, |workspace, _| {
4624 assert_eq!(
4625 workspace.leader_for_pane(workspace.active_pane()),
4626 Some(client_a_id)
4627 );
4628 });
4629}
4630
4631#[gpui::test(iterations = 100)]
4632async fn test_random_collaboration(
4633 cx: &mut TestAppContext,
4634 deterministic: Arc<Deterministic>,
4635 rng: StdRng,
4636) {
4637 deterministic.forbid_parking();
4638 let max_peers = env::var("MAX_PEERS")
4639 .map(|i| i.parse().expect("invalid `MAX_PEERS` variable"))
4640 .unwrap_or(5);
4641 assert!(max_peers <= 5);
4642
4643 let max_operations = env::var("OPERATIONS")
4644 .map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
4645 .unwrap_or(10);
4646
4647 let rng = Arc::new(Mutex::new(rng));
4648
4649 let guest_lang_registry = Arc::new(LanguageRegistry::test());
4650 let host_language_registry = Arc::new(LanguageRegistry::test());
4651
4652 let fs = FakeFs::new(cx.background());
4653 fs.insert_tree("/_collab", json!({"init": ""})).await;
4654
4655 let mut server = TestServer::start(cx.foreground(), cx.background()).await;
4656 let db = server.app_state.db.clone();
4657
4658 let room_creator_user_id = db.create_user("room-creator", None, false).await.unwrap();
4659 let mut available_guests = vec![
4660 "guest-1".to_string(),
4661 "guest-2".to_string(),
4662 "guest-3".to_string(),
4663 "guest-4".to_string(),
4664 ];
4665
4666 for username in Some(&"host".to_string())
4667 .into_iter()
4668 .chain(&available_guests)
4669 {
4670 let user_id = db.create_user(username, None, false).await.unwrap();
4671 server
4672 .app_state
4673 .db
4674 .send_contact_request(user_id, room_creator_user_id)
4675 .await
4676 .unwrap();
4677 server
4678 .app_state
4679 .db
4680 .respond_to_contact_request(room_creator_user_id, user_id, true)
4681 .await
4682 .unwrap();
4683 }
4684
4685 let client = server.create_client(cx, "room-creator").await;
4686 let room = cx
4687 .update(|cx| Room::create(client.client.clone(), client.user_store.clone(), cx))
4688 .await
4689 .unwrap();
4690 let room_id = room.read_with(cx, |room, _| room.id());
4691
4692 let mut clients = Vec::new();
4693 let mut user_ids = Vec::new();
4694 let mut op_start_signals = Vec::new();
4695
4696 let mut next_entity_id = 100000;
4697 let mut host_cx = TestAppContext::new(
4698 cx.foreground_platform(),
4699 cx.platform(),
4700 deterministic.build_foreground(next_entity_id),
4701 deterministic.build_background(),
4702 cx.font_cache(),
4703 cx.leak_detector(),
4704 next_entity_id,
4705 );
4706 let host = server.create_client(&mut host_cx, "host").await;
4707 let host_project = host_cx.update(|cx| {
4708 Project::local(
4709 host.client.clone(),
4710 host.user_store.clone(),
4711 host.project_store.clone(),
4712 host_language_registry.clone(),
4713 fs.clone(),
4714 cx,
4715 )
4716 });
4717
4718 let (collab_worktree, _) = host_project
4719 .update(&mut host_cx, |project, cx| {
4720 project.find_or_create_local_worktree("/_collab", true, cx)
4721 })
4722 .await
4723 .unwrap();
4724 collab_worktree
4725 .read_with(&host_cx, |tree, _| tree.as_local().unwrap().scan_complete())
4726 .await;
4727
4728 // Set up fake language servers.
4729 let mut language = Language::new(
4730 LanguageConfig {
4731 name: "Rust".into(),
4732 path_suffixes: vec!["rs".to_string()],
4733 ..Default::default()
4734 },
4735 None,
4736 );
4737 let _fake_servers = language
4738 .set_fake_lsp_adapter(Arc::new(FakeLspAdapter {
4739 name: "the-fake-language-server",
4740 capabilities: lsp::LanguageServer::full_capabilities(),
4741 initializer: Some(Box::new({
4742 let rng = rng.clone();
4743 let fs = fs.clone();
4744 let project = host_project.downgrade();
4745 move |fake_server: &mut FakeLanguageServer| {
4746 fake_server.handle_request::<lsp::request::Completion, _, _>(
4747 |_, _| async move {
4748 Ok(Some(lsp::CompletionResponse::Array(vec![
4749 lsp::CompletionItem {
4750 text_edit: Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
4751 range: lsp::Range::new(
4752 lsp::Position::new(0, 0),
4753 lsp::Position::new(0, 0),
4754 ),
4755 new_text: "the-new-text".to_string(),
4756 })),
4757 ..Default::default()
4758 },
4759 ])))
4760 },
4761 );
4762
4763 fake_server.handle_request::<lsp::request::CodeActionRequest, _, _>(
4764 |_, _| async move {
4765 Ok(Some(vec![lsp::CodeActionOrCommand::CodeAction(
4766 lsp::CodeAction {
4767 title: "the-code-action".to_string(),
4768 ..Default::default()
4769 },
4770 )]))
4771 },
4772 );
4773
4774 fake_server.handle_request::<lsp::request::PrepareRenameRequest, _, _>(
4775 |params, _| async move {
4776 Ok(Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(
4777 params.position,
4778 params.position,
4779 ))))
4780 },
4781 );
4782
4783 fake_server.handle_request::<lsp::request::GotoDefinition, _, _>({
4784 let fs = fs.clone();
4785 let rng = rng.clone();
4786 move |_, _| {
4787 let fs = fs.clone();
4788 let rng = rng.clone();
4789 async move {
4790 let files = fs.files().await;
4791 let mut rng = rng.lock();
4792 let count = rng.gen_range::<usize, _>(1..3);
4793 let files = (0..count)
4794 .map(|_| files.choose(&mut *rng).unwrap())
4795 .collect::<Vec<_>>();
4796 log::info!("LSP: Returning definitions in files {:?}", &files);
4797 Ok(Some(lsp::GotoDefinitionResponse::Array(
4798 files
4799 .into_iter()
4800 .map(|file| lsp::Location {
4801 uri: lsp::Url::from_file_path(file).unwrap(),
4802 range: Default::default(),
4803 })
4804 .collect(),
4805 )))
4806 }
4807 }
4808 });
4809
4810 fake_server.handle_request::<lsp::request::DocumentHighlightRequest, _, _>({
4811 let rng = rng.clone();
4812 let project = project;
4813 move |params, mut cx| {
4814 let highlights = if let Some(project) = project.upgrade(&cx) {
4815 project.update(&mut cx, |project, cx| {
4816 let path = params
4817 .text_document_position_params
4818 .text_document
4819 .uri
4820 .to_file_path()
4821 .unwrap();
4822 let (worktree, relative_path) =
4823 project.find_local_worktree(&path, cx)?;
4824 let project_path =
4825 ProjectPath::from((worktree.read(cx).id(), relative_path));
4826 let buffer =
4827 project.get_open_buffer(&project_path, cx)?.read(cx);
4828
4829 let mut highlights = Vec::new();
4830 let highlight_count = rng.lock().gen_range(1..=5);
4831 let mut prev_end = 0;
4832 for _ in 0..highlight_count {
4833 let range =
4834 buffer.random_byte_range(prev_end, &mut *rng.lock());
4835
4836 highlights.push(lsp::DocumentHighlight {
4837 range: range_to_lsp(range.to_point_utf16(buffer)),
4838 kind: Some(lsp::DocumentHighlightKind::READ),
4839 });
4840 prev_end = range.end;
4841 }
4842 Some(highlights)
4843 })
4844 } else {
4845 None
4846 };
4847 async move { Ok(highlights) }
4848 }
4849 });
4850 }
4851 })),
4852 ..Default::default()
4853 }))
4854 .await;
4855 host_language_registry.add(Arc::new(language));
4856
4857 let host_user_id = host.current_user_id(&host_cx);
4858 room.update(cx, |room, cx| room.call(host_user_id.to_proto(), None, cx))
4859 .await
4860 .unwrap();
4861 deterministic.run_until_parked();
4862 let call = host
4863 .user_store
4864 .read_with(&host_cx, |user_store, _| user_store.incoming_call());
4865 let host_room = host_cx
4866 .update(|cx| {
4867 Room::join(
4868 call.borrow().as_ref().unwrap(),
4869 host.client.clone(),
4870 host.user_store.clone(),
4871 cx,
4872 )
4873 })
4874 .await
4875 .unwrap();
4876
4877 let host_project_id = host_project
4878 .update(&mut host_cx, |project, cx| project.share(room_id, cx))
4879 .await
4880 .unwrap();
4881
4882 let op_start_signal = futures::channel::mpsc::unbounded();
4883 user_ids.push(host_user_id);
4884 op_start_signals.push(op_start_signal.0);
4885 clients.push(host_cx.foreground().spawn(host.simulate_host(
4886 host_room,
4887 host_project,
4888 op_start_signal.1,
4889 rng.clone(),
4890 host_cx,
4891 )));
4892
4893 let disconnect_host_at = if rng.lock().gen_bool(0.2) {
4894 rng.lock().gen_range(0..max_operations)
4895 } else {
4896 max_operations
4897 };
4898
4899 let mut operations = 0;
4900 while operations < max_operations {
4901 if operations == disconnect_host_at {
4902 server.disconnect_client(user_ids[0]);
4903 deterministic.advance_clock(RECEIVE_TIMEOUT);
4904 drop(op_start_signals);
4905
4906 deterministic.start_waiting();
4907 let mut clients = futures::future::join_all(clients).await;
4908 deterministic.finish_waiting();
4909 deterministic.run_until_parked();
4910
4911 let (host, host_room, host_project, mut host_cx, host_err) = clients.remove(0);
4912 if let Some(host_err) = host_err {
4913 log::error!("host error - {:?}", host_err);
4914 }
4915 host_project.read_with(&host_cx, |project, _| assert!(!project.is_shared()));
4916 for (guest, guest_room, guest_project, mut guest_cx, guest_err) in clients {
4917 if let Some(guest_err) = guest_err {
4918 log::error!("{} error - {:?}", guest.username, guest_err);
4919 }
4920
4921 guest_project.read_with(&guest_cx, |project, _| assert!(project.is_read_only()));
4922 guest_cx.update(|_| drop((guest, guest_room, guest_project)));
4923 }
4924 host_cx.update(|_| drop((host, host_room, host_project)));
4925
4926 return;
4927 }
4928
4929 let distribution = rng.lock().gen_range(0..100);
4930 match distribution {
4931 0..=19 if !available_guests.is_empty() => {
4932 let guest_ix = rng.lock().gen_range(0..available_guests.len());
4933 let guest_username = available_guests.remove(guest_ix);
4934 log::info!("Adding new connection for {}", guest_username);
4935 next_entity_id += 100000;
4936 let mut guest_cx = TestAppContext::new(
4937 cx.foreground_platform(),
4938 cx.platform(),
4939 deterministic.build_foreground(next_entity_id),
4940 deterministic.build_background(),
4941 cx.font_cache(),
4942 cx.leak_detector(),
4943 next_entity_id,
4944 );
4945
4946 deterministic.start_waiting();
4947 let guest = server.create_client(&mut guest_cx, &guest_username).await;
4948 let guest_user_id = guest.current_user_id(&guest_cx);
4949
4950 room.update(cx, |room, cx| room.call(guest_user_id.to_proto(), None, cx))
4951 .await
4952 .unwrap();
4953 deterministic.run_until_parked();
4954 let call = guest
4955 .user_store
4956 .read_with(&guest_cx, |user_store, _| user_store.incoming_call());
4957
4958 let guest_room = guest_cx
4959 .update(|cx| {
4960 Room::join(
4961 call.borrow().as_ref().unwrap(),
4962 guest.client.clone(),
4963 guest.user_store.clone(),
4964 cx,
4965 )
4966 })
4967 .await
4968 .unwrap();
4969
4970 let guest_project = Project::remote(
4971 host_project_id,
4972 guest.client.clone(),
4973 guest.user_store.clone(),
4974 guest.project_store.clone(),
4975 guest_lang_registry.clone(),
4976 FakeFs::new(cx.background()),
4977 guest_cx.to_async(),
4978 )
4979 .await
4980 .unwrap();
4981 deterministic.finish_waiting();
4982
4983 let op_start_signal = futures::channel::mpsc::unbounded();
4984 user_ids.push(guest_user_id);
4985 op_start_signals.push(op_start_signal.0);
4986 clients.push(guest_cx.foreground().spawn(guest.simulate_guest(
4987 guest_username.clone(),
4988 guest_room,
4989 guest_project,
4990 op_start_signal.1,
4991 rng.clone(),
4992 guest_cx,
4993 )));
4994
4995 log::info!("Added connection for {}", guest_username);
4996 operations += 1;
4997 }
4998 20..=29 if clients.len() > 1 => {
4999 let guest_ix = rng.lock().gen_range(1..clients.len());
5000 log::info!("Removing guest {}", user_ids[guest_ix]);
5001 let removed_guest_id = user_ids.remove(guest_ix);
5002 let guest = clients.remove(guest_ix);
5003 op_start_signals.remove(guest_ix);
5004 server.forbid_connections();
5005 server.disconnect_client(removed_guest_id);
5006 deterministic.advance_clock(RECEIVE_TIMEOUT);
5007 deterministic.start_waiting();
5008 log::info!("Waiting for guest {} to exit...", removed_guest_id);
5009 let (guest, guest_room, guest_project, mut guest_cx, guest_err) = guest.await;
5010 deterministic.finish_waiting();
5011 server.allow_connections();
5012
5013 if let Some(guest_err) = guest_err {
5014 log::error!("{} error - {:?}", guest.username, guest_err);
5015 }
5016 guest_project.read_with(&guest_cx, |project, _| assert!(project.is_read_only()));
5017 for user_id in &user_ids {
5018 let contacts = server.app_state.db.get_contacts(*user_id).await.unwrap();
5019 let contacts = server
5020 .store
5021 .lock()
5022 .await
5023 .build_initial_contacts_update(contacts)
5024 .contacts;
5025 for contact in contacts {
5026 if contact.online {
5027 assert_ne!(
5028 contact.user_id, removed_guest_id.0 as u64,
5029 "removed guest is still a contact of another peer"
5030 );
5031 }
5032 }
5033 }
5034
5035 log::info!("{} removed", guest.username);
5036 available_guests.push(guest.username.clone());
5037 guest_cx.update(|_| drop((guest, guest_room, guest_project)));
5038
5039 operations += 1;
5040 }
5041 _ => {
5042 while operations < max_operations && rng.lock().gen_bool(0.7) {
5043 op_start_signals
5044 .choose(&mut *rng.lock())
5045 .unwrap()
5046 .unbounded_send(())
5047 .unwrap();
5048 operations += 1;
5049 }
5050
5051 if rng.lock().gen_bool(0.8) {
5052 deterministic.run_until_parked();
5053 }
5054 }
5055 }
5056 }
5057
5058 drop(op_start_signals);
5059 deterministic.start_waiting();
5060 let mut clients = futures::future::join_all(clients).await;
5061 deterministic.finish_waiting();
5062 deterministic.run_until_parked();
5063
5064 let (host_client, host_room, host_project, mut host_cx, host_err) = clients.remove(0);
5065 if let Some(host_err) = host_err {
5066 panic!("host error - {:?}", host_err);
5067 }
5068 let host_worktree_snapshots = host_project.read_with(&host_cx, |project, cx| {
5069 project
5070 .worktrees(cx)
5071 .map(|worktree| {
5072 let snapshot = worktree.read(cx).snapshot();
5073 (snapshot.id(), snapshot)
5074 })
5075 .collect::<BTreeMap<_, _>>()
5076 });
5077
5078 host_project.read_with(&host_cx, |project, cx| project.check_invariants(cx));
5079
5080 for (guest_client, guest_room, guest_project, mut guest_cx, guest_err) in clients.into_iter() {
5081 if let Some(guest_err) = guest_err {
5082 panic!("{} error - {:?}", guest_client.username, guest_err);
5083 }
5084 let worktree_snapshots = guest_project.read_with(&guest_cx, |project, cx| {
5085 project
5086 .worktrees(cx)
5087 .map(|worktree| {
5088 let worktree = worktree.read(cx);
5089 (worktree.id(), worktree.snapshot())
5090 })
5091 .collect::<BTreeMap<_, _>>()
5092 });
5093
5094 assert_eq!(
5095 worktree_snapshots.keys().collect::<Vec<_>>(),
5096 host_worktree_snapshots.keys().collect::<Vec<_>>(),
5097 "{} has different worktrees than the host",
5098 guest_client.username
5099 );
5100 for (id, host_snapshot) in &host_worktree_snapshots {
5101 let guest_snapshot = &worktree_snapshots[id];
5102 assert_eq!(
5103 guest_snapshot.root_name(),
5104 host_snapshot.root_name(),
5105 "{} has different root name than the host for worktree {}",
5106 guest_client.username,
5107 id
5108 );
5109 assert_eq!(
5110 guest_snapshot.entries(false).collect::<Vec<_>>(),
5111 host_snapshot.entries(false).collect::<Vec<_>>(),
5112 "{} has different snapshot than the host for worktree {}",
5113 guest_client.username,
5114 id
5115 );
5116 assert_eq!(guest_snapshot.scan_id(), host_snapshot.scan_id());
5117 }
5118
5119 guest_project.read_with(&guest_cx, |project, cx| project.check_invariants(cx));
5120
5121 for guest_buffer in &guest_client.buffers {
5122 let buffer_id = guest_buffer.read_with(&guest_cx, |buffer, _| buffer.remote_id());
5123 let host_buffer = host_project.read_with(&host_cx, |project, cx| {
5124 project.buffer_for_id(buffer_id, cx).unwrap_or_else(|| {
5125 panic!(
5126 "host does not have buffer for guest:{}, peer:{}, id:{}",
5127 guest_client.username, guest_client.peer_id, buffer_id
5128 )
5129 })
5130 });
5131 let path =
5132 host_buffer.read_with(&host_cx, |buffer, cx| buffer.file().unwrap().full_path(cx));
5133
5134 assert_eq!(
5135 guest_buffer.read_with(&guest_cx, |buffer, _| buffer.deferred_ops_len()),
5136 0,
5137 "{}, buffer {}, path {:?} has deferred operations",
5138 guest_client.username,
5139 buffer_id,
5140 path,
5141 );
5142 assert_eq!(
5143 guest_buffer.read_with(&guest_cx, |buffer, _| buffer.text()),
5144 host_buffer.read_with(&host_cx, |buffer, _| buffer.text()),
5145 "{}, buffer {}, path {:?}, differs from the host's buffer",
5146 guest_client.username,
5147 buffer_id,
5148 path
5149 );
5150 }
5151
5152 guest_cx.update(|_| drop((guest_room, guest_project, guest_client)));
5153 }
5154
5155 host_cx.update(|_| drop((host_client, host_room, host_project)));
5156}
5157
5158struct TestServer {
5159 peer: Arc<Peer>,
5160 app_state: Arc<AppState>,
5161 server: Arc<Server>,
5162 foreground: Rc<executor::Foreground>,
5163 notifications: mpsc::UnboundedReceiver<()>,
5164 connection_killers: Arc<Mutex<HashMap<UserId, Arc<AtomicBool>>>>,
5165 forbid_connections: Arc<AtomicBool>,
5166 _test_db: TestDb,
5167}
5168
5169impl TestServer {
5170 async fn start(
5171 foreground: Rc<executor::Foreground>,
5172 background: Arc<executor::Background>,
5173 ) -> Self {
5174 let test_db = TestDb::fake(background.clone());
5175 let app_state = Self::build_app_state(&test_db).await;
5176 let peer = Peer::new();
5177 let notifications = mpsc::unbounded();
5178 let server = Server::new(app_state.clone(), Some(notifications.0));
5179 Self {
5180 peer,
5181 app_state,
5182 server,
5183 foreground,
5184 notifications: notifications.1,
5185 connection_killers: Default::default(),
5186 forbid_connections: Default::default(),
5187 _test_db: test_db,
5188 }
5189 }
5190
5191 async fn create_client(&mut self, cx: &mut TestAppContext, name: &str) -> TestClient {
5192 cx.update(|cx| {
5193 let mut settings = Settings::test(cx);
5194 settings.projects_online_by_default = false;
5195 cx.set_global(settings);
5196 });
5197
5198 let http = FakeHttpClient::with_404_response();
5199 let user_id = if let Ok(Some(user)) = self.app_state.db.get_user_by_github_login(name).await
5200 {
5201 user.id
5202 } else {
5203 self.app_state
5204 .db
5205 .create_user(name, None, false)
5206 .await
5207 .unwrap()
5208 };
5209 let client_name = name.to_string();
5210 let mut client = Client::new(http.clone());
5211 let server = self.server.clone();
5212 let db = self.app_state.db.clone();
5213 let connection_killers = self.connection_killers.clone();
5214 let forbid_connections = self.forbid_connections.clone();
5215 let (connection_id_tx, mut connection_id_rx) = mpsc::channel(16);
5216
5217 Arc::get_mut(&mut client)
5218 .unwrap()
5219 .set_id(user_id.0 as usize)
5220 .override_authenticate(move |cx| {
5221 cx.spawn(|_| async move {
5222 let access_token = "the-token".to_string();
5223 Ok(Credentials {
5224 user_id: user_id.0 as u64,
5225 access_token,
5226 })
5227 })
5228 })
5229 .override_establish_connection(move |credentials, cx| {
5230 assert_eq!(credentials.user_id, user_id.0 as u64);
5231 assert_eq!(credentials.access_token, "the-token");
5232
5233 let server = server.clone();
5234 let db = db.clone();
5235 let connection_killers = connection_killers.clone();
5236 let forbid_connections = forbid_connections.clone();
5237 let client_name = client_name.clone();
5238 let connection_id_tx = connection_id_tx.clone();
5239 cx.spawn(move |cx| async move {
5240 if forbid_connections.load(SeqCst) {
5241 Err(EstablishConnectionError::other(anyhow!(
5242 "server is forbidding connections"
5243 )))
5244 } else {
5245 let (client_conn, server_conn, killed) =
5246 Connection::in_memory(cx.background());
5247 connection_killers.lock().insert(user_id, killed);
5248 let user = db.get_user_by_id(user_id).await.unwrap().unwrap();
5249 cx.background()
5250 .spawn(server.handle_connection(
5251 server_conn,
5252 client_name,
5253 user,
5254 Some(connection_id_tx),
5255 cx.background(),
5256 ))
5257 .detach();
5258 Ok(client_conn)
5259 }
5260 })
5261 });
5262
5263 let fs = FakeFs::new(cx.background());
5264 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http, cx));
5265 let project_store = cx.add_model(|_| ProjectStore::new());
5266 let app_state = Arc::new(workspace::AppState {
5267 client: client.clone(),
5268 user_store: user_store.clone(),
5269 project_store: project_store.clone(),
5270 languages: Arc::new(LanguageRegistry::new(Task::ready(()))),
5271 themes: ThemeRegistry::new((), cx.font_cache()),
5272 fs: fs.clone(),
5273 build_window_options: Default::default,
5274 initialize_workspace: |_, _, _| unimplemented!(),
5275 default_item_factory: |_, _| unimplemented!(),
5276 });
5277
5278 Channel::init(&client);
5279 Project::init(&client);
5280 cx.update(|cx| workspace::init(app_state.clone(), cx));
5281
5282 client
5283 .authenticate_and_connect(false, &cx.to_async())
5284 .await
5285 .unwrap();
5286 let peer_id = PeerId(connection_id_rx.next().await.unwrap().0);
5287
5288 let client = TestClient {
5289 client,
5290 peer_id,
5291 username: name.to_string(),
5292 user_store,
5293 project_store,
5294 fs,
5295 language_registry: Arc::new(LanguageRegistry::test()),
5296 buffers: Default::default(),
5297 };
5298 client.wait_for_current_user(cx).await;
5299 client
5300 }
5301
5302 fn disconnect_client(&self, user_id: UserId) {
5303 self.connection_killers
5304 .lock()
5305 .remove(&user_id)
5306 .unwrap()
5307 .store(true, SeqCst);
5308 }
5309
5310 fn forbid_connections(&self) {
5311 self.forbid_connections.store(true, SeqCst);
5312 }
5313
5314 fn allow_connections(&self) {
5315 self.forbid_connections.store(false, SeqCst);
5316 }
5317
5318 async fn make_contacts(&self, clients: &mut [(&TestClient, &mut TestAppContext)]) {
5319 for ix in 1..clients.len() {
5320 let (left, right) = clients.split_at_mut(ix);
5321 let (client_a, cx_a) = left.last_mut().unwrap();
5322 for (client_b, cx_b) in right {
5323 client_a
5324 .user_store
5325 .update(*cx_a, |store, cx| {
5326 store.request_contact(client_b.user_id().unwrap(), cx)
5327 })
5328 .await
5329 .unwrap();
5330 cx_a.foreground().run_until_parked();
5331 client_b
5332 .user_store
5333 .update(*cx_b, |store, cx| {
5334 store.respond_to_contact_request(client_a.user_id().unwrap(), true, cx)
5335 })
5336 .await
5337 .unwrap();
5338 }
5339 }
5340 }
5341
5342 async fn create_rooms(
5343 &self,
5344 clients: &mut [(&TestClient, &mut TestAppContext)],
5345 ) -> (u64, Vec<ModelHandle<Room>>) {
5346 self.make_contacts(clients).await;
5347
5348 let mut rooms = Vec::new();
5349
5350 let (left, right) = clients.split_at_mut(1);
5351 let (client_a, cx_a) = &mut left[0];
5352
5353 let room_a = cx_a
5354 .update(|cx| Room::create(client_a.client.clone(), client_a.user_store.clone(), cx))
5355 .await
5356 .unwrap();
5357 let room_id = room_a.read_with(*cx_a, |room, _| room.id());
5358
5359 for (client_b, cx_b) in right {
5360 let user_id_b = client_b.current_user_id(*cx_b).to_proto();
5361 room_a
5362 .update(*cx_a, |room, cx| room.call(user_id_b, None, cx))
5363 .await
5364 .unwrap();
5365
5366 cx_b.foreground().run_until_parked();
5367 let incoming_call = client_b
5368 .user_store
5369 .read_with(*cx_b, |user_store, _| user_store.incoming_call());
5370 let room_b = cx_b
5371 .update(|cx| {
5372 Room::join(
5373 incoming_call.borrow().as_ref().unwrap(),
5374 client_b.client.clone(),
5375 client_b.user_store.clone(),
5376 cx,
5377 )
5378 })
5379 .await
5380 .unwrap();
5381 rooms.push(room_b);
5382 }
5383
5384 rooms.insert(0, room_a);
5385 (room_id, rooms)
5386 }
5387
5388 async fn build_app_state(test_db: &TestDb) -> Arc<AppState> {
5389 Arc::new(AppState {
5390 db: test_db.db().clone(),
5391 api_token: Default::default(),
5392 invite_link_prefix: Default::default(),
5393 })
5394 }
5395
5396 async fn condition<F>(&mut self, mut predicate: F)
5397 where
5398 F: FnMut(&Store) -> bool,
5399 {
5400 assert!(
5401 self.foreground.parking_forbidden(),
5402 "you must call forbid_parking to use server conditions so we don't block indefinitely"
5403 );
5404 while !(predicate)(&*self.server.store.lock().await) {
5405 self.foreground.start_waiting();
5406 self.notifications.next().await;
5407 self.foreground.finish_waiting();
5408 }
5409 }
5410}
5411
5412impl Deref for TestServer {
5413 type Target = Server;
5414
5415 fn deref(&self) -> &Self::Target {
5416 &self.server
5417 }
5418}
5419
5420impl Drop for TestServer {
5421 fn drop(&mut self) {
5422 self.peer.reset();
5423 }
5424}
5425
5426struct TestClient {
5427 client: Arc<Client>,
5428 username: String,
5429 pub peer_id: PeerId,
5430 pub user_store: ModelHandle<UserStore>,
5431 pub project_store: ModelHandle<ProjectStore>,
5432 language_registry: Arc<LanguageRegistry>,
5433 fs: Arc<FakeFs>,
5434 buffers: HashSet<ModelHandle<language::Buffer>>,
5435}
5436
5437impl Deref for TestClient {
5438 type Target = Arc<Client>;
5439
5440 fn deref(&self) -> &Self::Target {
5441 &self.client
5442 }
5443}
5444
5445struct ContactsSummary {
5446 pub current: Vec<String>,
5447 pub outgoing_requests: Vec<String>,
5448 pub incoming_requests: Vec<String>,
5449}
5450
5451impl TestClient {
5452 pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
5453 UserId::from_proto(
5454 self.user_store
5455 .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
5456 )
5457 }
5458
5459 async fn wait_for_current_user(&self, cx: &TestAppContext) {
5460 let mut authed_user = self
5461 .user_store
5462 .read_with(cx, |user_store, _| user_store.watch_current_user());
5463 while authed_user.next().await.unwrap().is_none() {}
5464 }
5465
5466 async fn clear_contacts(&self, cx: &mut TestAppContext) {
5467 self.user_store
5468 .update(cx, |store, _| store.clear_contacts())
5469 .await;
5470 }
5471
5472 fn summarize_contacts(&self, cx: &TestAppContext) -> ContactsSummary {
5473 self.user_store.read_with(cx, |store, _| ContactsSummary {
5474 current: store
5475 .contacts()
5476 .iter()
5477 .map(|contact| contact.user.github_login.clone())
5478 .collect(),
5479 outgoing_requests: store
5480 .outgoing_contact_requests()
5481 .iter()
5482 .map(|user| user.github_login.clone())
5483 .collect(),
5484 incoming_requests: store
5485 .incoming_contact_requests()
5486 .iter()
5487 .map(|user| user.github_login.clone())
5488 .collect(),
5489 })
5490 }
5491
5492 async fn build_local_project(
5493 &self,
5494 root_path: impl AsRef<Path>,
5495 cx: &mut TestAppContext,
5496 ) -> (ModelHandle<Project>, WorktreeId) {
5497 let project = cx.update(|cx| {
5498 Project::local(
5499 self.client.clone(),
5500 self.user_store.clone(),
5501 self.project_store.clone(),
5502 self.language_registry.clone(),
5503 self.fs.clone(),
5504 cx,
5505 )
5506 });
5507 let (worktree, _) = project
5508 .update(cx, |p, cx| {
5509 p.find_or_create_local_worktree(root_path, true, cx)
5510 })
5511 .await
5512 .unwrap();
5513 worktree
5514 .read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
5515 .await;
5516 (project, worktree.read_with(cx, |tree, _| tree.id()))
5517 }
5518
5519 async fn build_remote_project(
5520 &self,
5521 host_project_id: u64,
5522 guest_cx: &mut TestAppContext,
5523 ) -> ModelHandle<Project> {
5524 let project_b = guest_cx.spawn(|cx| {
5525 Project::remote(
5526 host_project_id,
5527 self.client.clone(),
5528 self.user_store.clone(),
5529 self.project_store.clone(),
5530 self.language_registry.clone(),
5531 FakeFs::new(cx.background()),
5532 cx,
5533 )
5534 });
5535 project_b.await.unwrap()
5536 }
5537
5538 fn build_workspace(
5539 &self,
5540 project: &ModelHandle<Project>,
5541 cx: &mut TestAppContext,
5542 ) -> ViewHandle<Workspace> {
5543 let (_, root_view) = cx.add_window(|_| EmptyView);
5544 cx.add_view(&root_view, |cx| {
5545 Workspace::new(project.clone(), |_, _| unimplemented!(), cx)
5546 })
5547 }
5548
5549 async fn simulate_host(
5550 mut self,
5551 room: ModelHandle<Room>,
5552 project: ModelHandle<Project>,
5553 op_start_signal: futures::channel::mpsc::UnboundedReceiver<()>,
5554 rng: Arc<Mutex<StdRng>>,
5555 mut cx: TestAppContext,
5556 ) -> (
5557 Self,
5558 ModelHandle<Room>,
5559 ModelHandle<Project>,
5560 TestAppContext,
5561 Option<anyhow::Error>,
5562 ) {
5563 async fn simulate_host_internal(
5564 client: &mut TestClient,
5565 project: ModelHandle<Project>,
5566 mut op_start_signal: futures::channel::mpsc::UnboundedReceiver<()>,
5567 rng: Arc<Mutex<StdRng>>,
5568 cx: &mut TestAppContext,
5569 ) -> anyhow::Result<()> {
5570 let fs = project.read_with(cx, |project, _| project.fs().clone());
5571
5572 while op_start_signal.next().await.is_some() {
5573 let distribution = rng.lock().gen_range::<usize, _>(0..100);
5574 let files = fs.as_fake().files().await;
5575 match distribution {
5576 0..=19 if !files.is_empty() => {
5577 let path = files.choose(&mut *rng.lock()).unwrap();
5578 let mut path = path.as_path();
5579 while let Some(parent_path) = path.parent() {
5580 path = parent_path;
5581 if rng.lock().gen() {
5582 break;
5583 }
5584 }
5585
5586 log::info!("Host: find/create local worktree {:?}", path);
5587 let find_or_create_worktree = project.update(cx, |project, cx| {
5588 project.find_or_create_local_worktree(path, true, cx)
5589 });
5590 if rng.lock().gen() {
5591 cx.background().spawn(find_or_create_worktree).detach();
5592 } else {
5593 find_or_create_worktree.await?;
5594 }
5595 }
5596 20..=79 if !files.is_empty() => {
5597 let buffer = if client.buffers.is_empty() || rng.lock().gen() {
5598 let file = files.choose(&mut *rng.lock()).unwrap();
5599 let (worktree, path) = project
5600 .update(cx, |project, cx| {
5601 project.find_or_create_local_worktree(file.clone(), true, cx)
5602 })
5603 .await?;
5604 let project_path =
5605 worktree.read_with(cx, |worktree, _| (worktree.id(), path));
5606 log::info!(
5607 "Host: opening path {:?}, worktree {}, relative_path {:?}",
5608 file,
5609 project_path.0,
5610 project_path.1
5611 );
5612 let buffer = project
5613 .update(cx, |project, cx| project.open_buffer(project_path, cx))
5614 .await
5615 .unwrap();
5616 client.buffers.insert(buffer.clone());
5617 buffer
5618 } else {
5619 client
5620 .buffers
5621 .iter()
5622 .choose(&mut *rng.lock())
5623 .unwrap()
5624 .clone()
5625 };
5626
5627 if rng.lock().gen_bool(0.1) {
5628 cx.update(|cx| {
5629 log::info!(
5630 "Host: dropping buffer {:?}",
5631 buffer.read(cx).file().unwrap().full_path(cx)
5632 );
5633 client.buffers.remove(&buffer);
5634 drop(buffer);
5635 });
5636 } else {
5637 buffer.update(cx, |buffer, cx| {
5638 log::info!(
5639 "Host: updating buffer {:?} ({})",
5640 buffer.file().unwrap().full_path(cx),
5641 buffer.remote_id()
5642 );
5643
5644 if rng.lock().gen_bool(0.7) {
5645 buffer.randomly_edit(&mut *rng.lock(), 5, cx);
5646 } else {
5647 buffer.randomly_undo_redo(&mut *rng.lock(), cx);
5648 }
5649 });
5650 }
5651 }
5652 _ => loop {
5653 let path_component_count = rng.lock().gen_range::<usize, _>(1..=5);
5654 let mut path = PathBuf::new();
5655 path.push("/");
5656 for _ in 0..path_component_count {
5657 let letter = rng.lock().gen_range(b'a'..=b'z');
5658 path.push(std::str::from_utf8(&[letter]).unwrap());
5659 }
5660 path.set_extension("rs");
5661 let parent_path = path.parent().unwrap();
5662
5663 log::info!("Host: creating file {:?}", path,);
5664
5665 if fs.create_dir(parent_path).await.is_ok()
5666 && fs.create_file(&path, Default::default()).await.is_ok()
5667 {
5668 break;
5669 } else {
5670 log::info!("Host: cannot create file");
5671 }
5672 },
5673 }
5674
5675 cx.background().simulate_random_delay().await;
5676 }
5677
5678 Ok(())
5679 }
5680
5681 let result =
5682 simulate_host_internal(&mut self, project.clone(), op_start_signal, rng, &mut cx).await;
5683 log::info!("Host done");
5684 (self, room, project, cx, result.err())
5685 }
5686
5687 pub async fn simulate_guest(
5688 mut self,
5689 guest_username: String,
5690 room: ModelHandle<Room>,
5691 project: ModelHandle<Project>,
5692 op_start_signal: futures::channel::mpsc::UnboundedReceiver<()>,
5693 rng: Arc<Mutex<StdRng>>,
5694 mut cx: TestAppContext,
5695 ) -> (
5696 Self,
5697 ModelHandle<Room>,
5698 ModelHandle<Project>,
5699 TestAppContext,
5700 Option<anyhow::Error>,
5701 ) {
5702 async fn simulate_guest_internal(
5703 client: &mut TestClient,
5704 guest_username: &str,
5705 project: ModelHandle<Project>,
5706 mut op_start_signal: futures::channel::mpsc::UnboundedReceiver<()>,
5707 rng: Arc<Mutex<StdRng>>,
5708 cx: &mut TestAppContext,
5709 ) -> anyhow::Result<()> {
5710 while op_start_signal.next().await.is_some() {
5711 let buffer = if client.buffers.is_empty() || rng.lock().gen() {
5712 let worktree = if let Some(worktree) = project.read_with(cx, |project, cx| {
5713 project
5714 .worktrees(cx)
5715 .filter(|worktree| {
5716 let worktree = worktree.read(cx);
5717 worktree.is_visible()
5718 && worktree.entries(false).any(|e| e.is_file())
5719 })
5720 .choose(&mut *rng.lock())
5721 }) {
5722 worktree
5723 } else {
5724 cx.background().simulate_random_delay().await;
5725 continue;
5726 };
5727
5728 let (worktree_root_name, project_path) =
5729 worktree.read_with(cx, |worktree, _| {
5730 let entry = worktree
5731 .entries(false)
5732 .filter(|e| e.is_file())
5733 .choose(&mut *rng.lock())
5734 .unwrap();
5735 (
5736 worktree.root_name().to_string(),
5737 (worktree.id(), entry.path.clone()),
5738 )
5739 });
5740 log::info!(
5741 "{}: opening path {:?} in worktree {} ({})",
5742 guest_username,
5743 project_path.1,
5744 project_path.0,
5745 worktree_root_name,
5746 );
5747 let buffer = project
5748 .update(cx, |project, cx| {
5749 project.open_buffer(project_path.clone(), cx)
5750 })
5751 .await?;
5752 log::info!(
5753 "{}: opened path {:?} in worktree {} ({}) with buffer id {}",
5754 guest_username,
5755 project_path.1,
5756 project_path.0,
5757 worktree_root_name,
5758 buffer.read_with(cx, |buffer, _| buffer.remote_id())
5759 );
5760 client.buffers.insert(buffer.clone());
5761 buffer
5762 } else {
5763 client
5764 .buffers
5765 .iter()
5766 .choose(&mut *rng.lock())
5767 .unwrap()
5768 .clone()
5769 };
5770
5771 let choice = rng.lock().gen_range(0..100);
5772 match choice {
5773 0..=9 => {
5774 cx.update(|cx| {
5775 log::info!(
5776 "{}: dropping buffer {:?}",
5777 guest_username,
5778 buffer.read(cx).file().unwrap().full_path(cx)
5779 );
5780 client.buffers.remove(&buffer);
5781 drop(buffer);
5782 });
5783 }
5784 10..=19 => {
5785 let completions = project.update(cx, |project, cx| {
5786 log::info!(
5787 "{}: requesting completions for buffer {} ({:?})",
5788 guest_username,
5789 buffer.read(cx).remote_id(),
5790 buffer.read(cx).file().unwrap().full_path(cx)
5791 );
5792 let offset = rng.lock().gen_range(0..=buffer.read(cx).len());
5793 project.completions(&buffer, offset, cx)
5794 });
5795 let completions = cx.background().spawn(async move {
5796 completions
5797 .await
5798 .map_err(|err| anyhow!("completions request failed: {:?}", err))
5799 });
5800 if rng.lock().gen_bool(0.3) {
5801 log::info!("{}: detaching completions request", guest_username);
5802 cx.update(|cx| completions.detach_and_log_err(cx));
5803 } else {
5804 completions.await?;
5805 }
5806 }
5807 20..=29 => {
5808 let code_actions = project.update(cx, |project, cx| {
5809 log::info!(
5810 "{}: requesting code actions for buffer {} ({:?})",
5811 guest_username,
5812 buffer.read(cx).remote_id(),
5813 buffer.read(cx).file().unwrap().full_path(cx)
5814 );
5815 let range = buffer.read(cx).random_byte_range(0, &mut *rng.lock());
5816 project.code_actions(&buffer, range, cx)
5817 });
5818 let code_actions = cx.background().spawn(async move {
5819 code_actions
5820 .await
5821 .map_err(|err| anyhow!("code actions request failed: {:?}", err))
5822 });
5823 if rng.lock().gen_bool(0.3) {
5824 log::info!("{}: detaching code actions request", guest_username);
5825 cx.update(|cx| code_actions.detach_and_log_err(cx));
5826 } else {
5827 code_actions.await?;
5828 }
5829 }
5830 30..=39 if buffer.read_with(cx, |buffer, _| buffer.is_dirty()) => {
5831 let (requested_version, save) = buffer.update(cx, |buffer, cx| {
5832 log::info!(
5833 "{}: saving buffer {} ({:?})",
5834 guest_username,
5835 buffer.remote_id(),
5836 buffer.file().unwrap().full_path(cx)
5837 );
5838 (buffer.version(), buffer.save(cx))
5839 });
5840 let save = cx.background().spawn(async move {
5841 let (saved_version, _, _) = save
5842 .await
5843 .map_err(|err| anyhow!("save request failed: {:?}", err))?;
5844 assert!(saved_version.observed_all(&requested_version));
5845 Ok::<_, anyhow::Error>(())
5846 });
5847 if rng.lock().gen_bool(0.3) {
5848 log::info!("{}: detaching save request", guest_username);
5849 cx.update(|cx| save.detach_and_log_err(cx));
5850 } else {
5851 save.await?;
5852 }
5853 }
5854 40..=44 => {
5855 let prepare_rename = project.update(cx, |project, cx| {
5856 log::info!(
5857 "{}: preparing rename for buffer {} ({:?})",
5858 guest_username,
5859 buffer.read(cx).remote_id(),
5860 buffer.read(cx).file().unwrap().full_path(cx)
5861 );
5862 let offset = rng.lock().gen_range(0..=buffer.read(cx).len());
5863 project.prepare_rename(buffer, offset, cx)
5864 });
5865 let prepare_rename = cx.background().spawn(async move {
5866 prepare_rename
5867 .await
5868 .map_err(|err| anyhow!("prepare rename request failed: {:?}", err))
5869 });
5870 if rng.lock().gen_bool(0.3) {
5871 log::info!("{}: detaching prepare rename request", guest_username);
5872 cx.update(|cx| prepare_rename.detach_and_log_err(cx));
5873 } else {
5874 prepare_rename.await?;
5875 }
5876 }
5877 45..=49 => {
5878 let definitions = project.update(cx, |project, cx| {
5879 log::info!(
5880 "{}: requesting definitions for buffer {} ({:?})",
5881 guest_username,
5882 buffer.read(cx).remote_id(),
5883 buffer.read(cx).file().unwrap().full_path(cx)
5884 );
5885 let offset = rng.lock().gen_range(0..=buffer.read(cx).len());
5886 project.definition(&buffer, offset, cx)
5887 });
5888 let definitions = cx.background().spawn(async move {
5889 definitions
5890 .await
5891 .map_err(|err| anyhow!("definitions request failed: {:?}", err))
5892 });
5893 if rng.lock().gen_bool(0.3) {
5894 log::info!("{}: detaching definitions request", guest_username);
5895 cx.update(|cx| definitions.detach_and_log_err(cx));
5896 } else {
5897 client.buffers.extend(
5898 definitions.await?.into_iter().map(|loc| loc.target.buffer),
5899 );
5900 }
5901 }
5902 50..=54 => {
5903 let highlights = project.update(cx, |project, cx| {
5904 log::info!(
5905 "{}: requesting highlights for buffer {} ({:?})",
5906 guest_username,
5907 buffer.read(cx).remote_id(),
5908 buffer.read(cx).file().unwrap().full_path(cx)
5909 );
5910 let offset = rng.lock().gen_range(0..=buffer.read(cx).len());
5911 project.document_highlights(&buffer, offset, cx)
5912 });
5913 let highlights = cx.background().spawn(async move {
5914 highlights
5915 .await
5916 .map_err(|err| anyhow!("highlights request failed: {:?}", err))
5917 });
5918 if rng.lock().gen_bool(0.3) {
5919 log::info!("{}: detaching highlights request", guest_username);
5920 cx.update(|cx| highlights.detach_and_log_err(cx));
5921 } else {
5922 highlights.await?;
5923 }
5924 }
5925 55..=59 => {
5926 let search = project.update(cx, |project, cx| {
5927 let query = rng.lock().gen_range('a'..='z');
5928 log::info!("{}: project-wide search {:?}", guest_username, query);
5929 project.search(SearchQuery::text(query, false, false), cx)
5930 });
5931 let search = cx.background().spawn(async move {
5932 search
5933 .await
5934 .map_err(|err| anyhow!("search request failed: {:?}", err))
5935 });
5936 if rng.lock().gen_bool(0.3) {
5937 log::info!("{}: detaching search request", guest_username);
5938 cx.update(|cx| search.detach_and_log_err(cx));
5939 } else {
5940 client.buffers.extend(search.await?.into_keys());
5941 }
5942 }
5943 60..=69 => {
5944 let worktree = project
5945 .read_with(cx, |project, cx| {
5946 project
5947 .worktrees(cx)
5948 .filter(|worktree| {
5949 let worktree = worktree.read(cx);
5950 worktree.is_visible()
5951 && worktree.entries(false).any(|e| e.is_file())
5952 && worktree.root_entry().map_or(false, |e| e.is_dir())
5953 })
5954 .choose(&mut *rng.lock())
5955 })
5956 .unwrap();
5957 let (worktree_id, worktree_root_name) = worktree
5958 .read_with(cx, |worktree, _| {
5959 (worktree.id(), worktree.root_name().to_string())
5960 });
5961
5962 let mut new_name = String::new();
5963 for _ in 0..10 {
5964 let letter = rng.lock().gen_range('a'..='z');
5965 new_name.push(letter);
5966 }
5967 let mut new_path = PathBuf::new();
5968 new_path.push(new_name);
5969 new_path.set_extension("rs");
5970 log::info!(
5971 "{}: creating {:?} in worktree {} ({})",
5972 guest_username,
5973 new_path,
5974 worktree_id,
5975 worktree_root_name,
5976 );
5977 project
5978 .update(cx, |project, cx| {
5979 project.create_entry((worktree_id, new_path), false, cx)
5980 })
5981 .unwrap()
5982 .await?;
5983 }
5984 _ => {
5985 buffer.update(cx, |buffer, cx| {
5986 log::info!(
5987 "{}: updating buffer {} ({:?})",
5988 guest_username,
5989 buffer.remote_id(),
5990 buffer.file().unwrap().full_path(cx)
5991 );
5992 if rng.lock().gen_bool(0.7) {
5993 buffer.randomly_edit(&mut *rng.lock(), 5, cx);
5994 } else {
5995 buffer.randomly_undo_redo(&mut *rng.lock(), cx);
5996 }
5997 });
5998 }
5999 }
6000 cx.background().simulate_random_delay().await;
6001 }
6002 Ok(())
6003 }
6004
6005 let result = simulate_guest_internal(
6006 &mut self,
6007 &guest_username,
6008 project.clone(),
6009 op_start_signal,
6010 rng,
6011 &mut cx,
6012 )
6013 .await;
6014 log::info!("{}: done", guest_username);
6015
6016 (self, room, project, cx, result.err())
6017 }
6018}
6019
6020impl Drop for TestClient {
6021 fn drop(&mut self) {
6022 self.client.tear_down();
6023 }
6024}
6025
6026impl Executor for Arc<gpui::executor::Background> {
6027 type Sleep = gpui::executor::Timer;
6028
6029 fn spawn_detached<F: 'static + Send + Future<Output = ()>>(&self, future: F) {
6030 self.spawn(future).detach();
6031 }
6032
6033 fn sleep(&self, duration: Duration) -> Self::Sleep {
6034 self.as_ref().timer(duration)
6035 }
6036}
6037
6038fn channel_messages(channel: &Channel) -> Vec<(String, String, bool)> {
6039 channel
6040 .messages()
6041 .cursor::<()>()
6042 .map(|m| {
6043 (
6044 m.sender.github_login.clone(),
6045 m.body.clone(),
6046 m.is_pending(),
6047 )
6048 })
6049 .collect()
6050}
6051
6052#[derive(Debug, Eq, PartialEq)]
6053struct RoomParticipants {
6054 remote: Vec<String>,
6055 pending: Vec<String>,
6056}
6057
6058fn room_participants(room: &ModelHandle<Room>, cx: &mut TestAppContext) -> RoomParticipants {
6059 room.read_with(cx, |room, _| RoomParticipants {
6060 remote: room
6061 .remote_participants()
6062 .iter()
6063 .map(|(_, participant)| participant.user.github_login.clone())
6064 .collect(),
6065 pending: room
6066 .pending_users()
6067 .iter()
6068 .map(|user| user.github_login.clone())
6069 .collect(),
6070 })
6071}